代码之家  ›  专栏  ›  技术社区  ›  Mathias F

使用SmtpClient发送邮件列表

  •  2
  • Mathias F  · 技术社区  · 15 年前

    在发送电子邮件列表时,我使用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);
            }            
        }
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   Josh Stodola    15 年前

    SmtpClient 每次(然后重新分配处理程序)。使用范围更大的静态变量。

        2
  •  0
  •   Damian Powell    15 年前

    它在我的机器上正常工作,只是MailMessage的构造函数抛出了一个格式异常,因为 "My Tex" 不是有效的电子邮件地址。第一个参数是发件人的电子邮件地址。

    正如Josh Stodola指出的,你应该缓存 SmtpClient ,则应在SendCompletedCallback的末尾添加以下行(最好在finally块中):

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

    如果这对您没有帮助,也许您可以发布更多详细信息—例如,事件参数中的数据是什么 接到电话了吗?