Sunday, May 5, 2013

Async Emails C#

In the past I've had to send multiple emails at a time with a list that ranged anywhere from 1-500.  Ideally when it comes to mass emails, you should setup a dedicated IP to prevent your site from possibly becoming blacklisted.  That said, if your needing to send multiple emails what better way to accomplish that task and not slow down your application then to do it asynchronously.  I hope this example helps to get you started.  Have Fun!!!
protected void Page_Load(object sender, EventArgs e)
        {
            MailMessage msg = new MailMessage();
            MailAddress from = new MailAddress("[YOUR EMAIL]");
            msg.Subject = "[SUBJECT]";
            msg.Body = "[BODY]";

            List emailList = new List();

            emailList.Add("email@email1.com");
            emailList.Add("email@email2.com");

            foreach (string str in emailList)
            {
                SendEmail(msg, str, from, true);
            }

        }

        public static void SendEmail(MailMessage m, string to, MailAddress from, Boolean Async)
        {
            SmtpClient smtpClient = null;
            NetworkCredential SMTPUserInfo = new NetworkCredential("[YOUR EMAIL]", "[YOUR PASSWORD]");

            smtpClient = new SmtpClient("[SMTP SERVER]", 587);
            smtpClient.Credentials = SMTPUserInfo;
            smtpClient.EnableSsl = true;

            m.To.Clear();
            m.To.Add(to);
            m.From = from;
            if (Async)
            {
                SendEmailDelegate sd = new SendEmailDelegate(smtpClient.Send);
                AsyncCallback cb = new AsyncCallback(SendEmailResponse);
                sd.BeginInvoke(m, cb, sd);
            }
            else
            {
                smtpClient.Send(m);
            }
        }

        private delegate void SendEmailDelegate(System.Net.Mail.MailMessage m);

        private static void SendEmailResponse(IAsyncResult ar)
        {
            SendEmailDelegate sd = (SendEmailDelegate)(ar.AsyncState);

            sd.EndInvoke(ar);
        }

No comments:

Post a Comment