1
votes

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. So for test I write following code having gmail test server.

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 = "[email protected]";
        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:

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. Am I doing something wrong. Do We have better option to send multiple mail at one time?

1

1 Answers

0
votes

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. I had made a web service for this whose only task was to send emails. 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.

Summary

  • First of all check that are you using .Net framework 2.0 if yes switch to 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.
  • Send your emails in chunks(About 100 at a time).

using()
{
//Place you email sending code here.
}