简体   繁体   English

在ASP.NET中使用AYNC发送多个邮件

[英]Sending multiple mail using aync in asp.net

I have to send mail to multiple recipient eg. 我必须将邮件发送给多个收件人,例如。 to all the employee of an organization. 组织的所有员工。 For this I go through the resources via search engine and decided to make multiple instant of SmtpClient and send mail using async. 为此,我通过搜索引擎浏览了资源,并决定将SmtpClient设置为多个实例并使用异步方式发送邮件。 So for test I write following code having gmail test server. 因此,对于测试,我编写了以下具有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);
    }


} 

And mailHelper would be: 和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;
            }
        }

This code snippet works fine but I couldnot send specified number of mail. 此代码段工作正常,但我无法发送指定数量的邮件。 The number of email sent is differnt each time I execute this code ie. 每当我执行此代码时,发送的电子邮件数量是不同的。 it may be 35, 40, 42 etc. It seems some instances of SmtpClient got failed, but I didnot get any exception. 它可能是35、40、42等。似乎SmtpClient的某些实例失败了,但我没有得到任何例外。 Am I doing something wrong. 难道我做错了什么。 Do We have better option to send multiple mail at one time? 我们是否有更好的选择一次发送多个邮件?

I want to share my experience with sending emails.I also used to send B-Day emails but in my case there were usually 100-150 people and all mails delivered successfully. 我想分享我发送电子邮件的经验。我也曾经发送过B天电子邮件,但就我而言,通常有100-150人,并且所有邮件都已成功发送。 I had made a web service for this whose only task was to send emails. 我为此做了一个Web服务,其唯一的任务就是发送电子邮件。 But before emails started to deliver successfully we tested on local machine which worked fine but when we tested it on server i face the same issue and cause of this failure was that we deployed our web service in .Net framework 2.0 than we changed it to 4.0 and tested it again with 10000,5000,1000 emails and it worked fine not all emails but most of them reached destination.Also one more thing to mention is that the address from which we were sending email was restricted by network department in email server to send only 100 emails.Also try to avoid sending too many emails from one sender and from one email server because you can get black listed. 但是,在电子邮件开始成功传递之前,我们在本地计算机上进行了测试,效果很好,但是当我们在服务器上对其进行测试时,我遇到了同样的问题,并且导致失败的原因是,我们在.Net Framework 2.0中部署了Web服务,而不是将其更改为4.0。并再次测试了10000,5000,1000封电子邮件,虽然并非所有电子邮件都能正常工作,但大多数邮件仍能到达目的地。另外还有一件事是,我们发送电子邮件的地址被电子邮件服务器中的网络部门限制为仅发送100封电子邮件。此外,请尽量避免从一个发件人和一个电子邮件服务器发送太多电子邮件,因为您可能会被列入黑名单。

Summary 摘要

  • First of all check that are you using .Net framework 2.0 if yes switch to 4.0. 首先,检查是否使用.Net framework 2.0(如果是),请切换到4.0。
  • Make sure that there are no restrictions by network department at email server and also to address which you use as sender. 确保电子邮件服务器的网络部门不受限制,并确保您用作发件人的地址不受限制。
  • Place all your code in using statement to make sure objects get disposed. 将所有代码放在using语句中,以确保对象被处置。
  • Send your emails in chunks(About 100 at a time). 批量发送您的电子邮件(一次发送约100个)。

using() 使用()
{ {
//Place you email sending code here. //将您的电子邮件发送代码放在此处。
} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM