2010-04-21 111 views
2

發送郵件列表時,我使用SmtpClient的SendCompletedEventHandler。使用SmtpClient發送郵件列表

SendCompletedEventHandler僅在已經發送列表中的所有電子郵件時才被調用。

我想到了,SendCompletedEventHandler在發送郵件時被調用。

我的代碼有什麼問題嗎?

public void SendAllNewsletters(List<string> recipients) 
    { 
     string mailText = "My Text"; 
     foreach(string recipient in recipients) 
     { 
      //if this loop takes 10min then the first call to 
      //SendCompletedCallback is after 10min 
      SendNewsletter(mailText,recipient); 
     } 
    } 

    public bool SendNewsletter(string mailText , string emailaddress) 
    { 

      SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort); 
      System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword); 
      sc.Credentials = SMTPUserInfo; 
      sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); 

      MailMessage mm = null; 
      mm = new MailMessage(_senderemail, emailaddress); 
      mm.IsBodyHtml = true; 
      mm.Priority = MailPriority.Normal; 
      mm.Subject = "Something"; 
      mm.Body = mailText ; 
      mm.SubjectEncoding = Encoding.UTF8; 
      mm.BodyEncoding = Encoding.UTF8; 

      //Mail 
      string userState = emailaddress; 
      sc.SendAsync(mm, userState); 

      return true; 
    } 


    public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) 
    { 
     // Get the unique identifier for this asynchronous operation. 
     String token = (string)e.UserState; 
     if (e.Error != null) 
     { 
      _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message); 
     } 
     else 
     { 
      _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty); 
     }    
    } 

回答

1

您正在創建的每個SmtpClient每當一個新的實例,(然後重新分配處理器)。使用一個更大範圍的靜態變量。

+0

這聽起來像你假設處理程序只能與一個不正確的SmtpClient關聯。此外,他每次都會創建一個新的處理程序,因此存在1:1的關係。 – 2010-04-21 16:25:42

0

它在我的機器上按預期工作,除了MailMessage的構造函數拋出一個格式異常,因爲"My Tex"不是有效的電子郵件地址。第一個參數是發件人的電子郵件地址。

正如Josh Stodola指出的那樣,您應該爲此類的生命緩存SmtpClient,而不是爲每次調用創建另一個。如果不緩存SmtpClient,那麼你應該將下面的行添加到您的SendCompletedCallback結束(最好在finally塊):

((SmtpClient)sender).SendCompleted -= SendCompletedCallback; 

如果不幫你,也許你可以發佈更多詳細信息 - 如做的被調用的事件參數中的數據是什麼?

+0

Thnx,我更新了帖子,使用MailMessage的正確語法 – 2010-04-21 21:29:46

+0

它是否修復了您的問題? – 2010-04-21 21:49:11

相關問題