2010-04-21 48 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