在asp.net中使用aync发送多个邮件

时间:2014-12-29 05:24:28

标签: asp.net email smtpclient

我必须向多个收件人发送邮件,例如。给组织的所有员工。为此,我通过搜索引擎浏览资源,并决定多次使用SmtpClient并使用异步发送邮件。所以对于测试我写下以下代码有gmail测试服务器。

public void SendMail()
{
    try
    {
        string strEmail = string.Empty;
        // for collecting multiple recepient
        //foreach (GridViewRow grd in gdv_txtMailTo.Rows)
        //{
        //    CheckBox chkBx = (CheckBox)grd.FindControl("chkBxSelect");
        //    if (chkBx != null && chkBx.Checked)
        //    {
        //        strEmail += ((Label)grd.FindControl("Label1")).Text + ',';
        //    }

        //}
        strEmail = "yogendra.paudyal44@gmail.com";
        string emails = strEmail;
        string output = DBNull.Value.ToString();
        //if (emails != "")
        //{
        //    output = emails.Remove(emails.Length - 1, 1);
        //}
        MassMail_Controller.SaveSelectedEmails(output, PortalID);
        MassMail_Info info = new MassMail_Info();
        info.SendFrom = txtMailFrom.Text;
        info.Subject = txtSubject.Text;
        info.CC = txtCC.Text;
        info.BCC = txtBCC.Text;
        info.FileName = "";
        info.SendTo = strEmail;
        string messageTemplate = txtBody.Text;
        info.Body = messageTemplate;
        info.UserModuleId = UserModuleID;
        info.PortalId = PortalID;
        for (int i = 0; i < 50; i++) {
            MailHelper.SendMailOneAttachment(info.SendFrom, info.SendTo, info.Subject, info.Body, info.FileName, info.CC, info.BCC);
        }

        //Thread thread = new Thread(new ParameterizedThreadStart(GetAllEmail));

        //thread.IsBackground = true;
        //thread.Start(bit);

        //while (thread.IsAlive)
        //{
        //    ShowMessage(SageMessageTitle.Exception.ToString(), "Mail Sent", "", SageMessageType.Success);


        //}
    }
    catch (Exception ex)
    {
        ProcessException(ex);
    }


} 

mailHelper将是:

public static void SendEMail(string From, string sendTo, string Subject, string Body, ArrayList AttachmentFiles, string CC, string BCC, bool IsHtmlFormat)
        {
            SageFrameConfig sfConfig = new SageFrameConfig();
            //string ServerPort = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPServer);
            //string SMTPAuthentication = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPAuthentication);
            //string SMTPEnableSSL = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPEnableSSL);
            //string SMTPPassword = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPPassword);
            //string SMTPUsername = sfConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.SMTPUsername);
            string ServerPort = (SageFrameSettingKeys.SMTPServer);
            string SMTPAuthentication =(SageFrameSettingKeys.SMTPAuthentication);
            string SMTPEnableSSL = (SageFrameSettingKeys.SMTPEnableSSL);
            string SMTPPassword = (SageFrameSettingKeys.SMTPPassword);
            string SMTPUsername = (SageFrameSettingKeys.SMTPUsername);
            string[] SMTPServer = ServerPort.Split(':');
            try
            {
                MailMessage myMessage = new MailMessage();
                myMessage.To.Add(sendTo);
                myMessage.From = new MailAddress(From);
                myMessage.Subject = Subject;
                myMessage.Body = Body;
                myMessage.IsBodyHtml = true;

                if (CC.Length != 0)
                    myMessage.CC.Add(CC);

                if (BCC.Length != 0)
                    myMessage.Bcc.Add(BCC);

                if (AttachmentFiles != null)
                {
                    foreach (string x in AttachmentFiles)
                    {
                        if (File.Exists(x)) myMessage.Attachments.Add(new Attachment(x));
                    }
                }
                SmtpClient smtp = new SmtpClient();
                if (SMTPAuthentication == "1")
                {
                    if (SMTPUsername.Length > 0 && SMTPPassword.Length > 0)
                    {
                        smtp.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
                    }
                }
                smtp.EnableSsl = bool.Parse(SMTPEnableSSL.ToString());
                if (SMTPServer.Length > 0)
                {
                    if (SMTPServer[0].Length != 0)
                    {
                        smtp.Host = SMTPServer[0];
                        if (SMTPServer.Length == 2)
                        {
                            smtp.Port = int.Parse(SMTPServer[1]);
                        }
                        else
                        {
                            smtp.Port = 25;
                        }
                        object userState = myMessage;

                        //wire up the event for when the Async send is completed
                        smtp.SendCompleted += new
                        SendCompletedEventHandler(SendCompletedCallback);

                        smtp.SendAsync(myMessage,userState);
                        Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
                        //string answer = Console.ReadLine();
                        // If the user canceled the send, and mail hasn't been sent yet, 
                        // then cancel the pending operation. 
                        //if (answer.StartsWith("c"))
                        //{
                        //    smtp.SendAsyncCancel();
                        //}
                        //// Clean up.
                        //myMessage.Dispose();
                        Console.WriteLine("Goodbye.");
                    }
                    else
                    {
                        throw new Exception("SMTP Host must be provided");
                    }
                }

            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

此代码段工作正常但我无法发送指定数量的邮件。每次执行此代码时发送的电子邮件数量不同,即。它可能是35,40,42等。似乎某些SmtpClient实例失败了,但我没有得到任何异常。难道我做错了什么。我们有更好的选择一次发送多封邮件吗?

1 个答案:

答案 0 :(得分:0)

我想分享我发送电子邮件的经验。我还习惯发送B-Day电子邮件,但在我的情况下,通常有100-150人,所有邮件都成功发送。我为此制作了一个Web服务,其唯一的任务是发送电子邮件。但是在电子邮件开始成功交付之前,我们在本地机器上进行了测试,但是当我们在服务器上进行测试时,我面临同样的问题,导致这种失败的原因是我们在.Net framework 2.0中部署了我们的Web服务而不是将其更改为4.0然后用10000,5000,1000封电子邮件再次测试它,它工作得很好,不是所有的电子邮件,但大多数都到达目的地。还有一件事要提到我们发送电子邮件的地址是由电子邮件服务器的网络部门限制的只发送100封电子邮件。同时尽量避免从一个发件人和一个电子邮件服务器发送太多电子邮件,因为您可能会将其列入黑名单。

摘要

  • 首先检查您是否使用.Net framework 2.0,如果是的话 切换到4.0。
  • 确保网络部门没有任何限制 电子邮件服务器以及您用作发件人的地址。
  • 将所有代码放在using语句中以确保对象获取 地布置。
  • 发送电子邮件(每次约100个)。
  

使用()
  {
  //给你发电子邮件发送代码。
  }