Asynchronously sending a System.Net.Mail.MailMessage in C#

When sending an email in your ASP.NET application there are times when you do not want the user experience to slow just to wait for an email to be sent.  The code sample below is how to send a System.Net.Mail.MailMessage asynchronously so that the current thread can continue while a secondary thread sends the email. 

public static void SendEmail(System.Net.Mail.MailMessage m)
{
    SendEmail(m, true);
}

public static void SendEmail(System.Net.Mail.MailMessage m, Boolean Async)
{

    System.Net.Mail.SmtpClient smtpClient = null;

    smtpClient = new System.Net.Mail.SmtpClient("localhost");

        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);
}

To use this just call the SendEmail() method with System.Net.Mail.MailMessage object.

 



14 Comments

  • Nice article. Can u please explain little bit about "Asynchronous" call

    Many Thanks

  • What's wrong with:
    smtpClient.SendAsync(m, null);

    "Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes."

    http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx
    http://www.systemnetmail.com/faq/4.6.aspx

  • Hey RichardD,
    I didn't know that SmtpClient.SendAsync existed. I wrote the above code back in .NET 1.0 days and it looks like SendAsync was introduced in .NET 2.0. Cool! Thanks for info... I will make a note to possibly rewrite this sample with SendAsync instead.
    Thanks!
    -Jeff

  • Hi Padma,
    Asynchronous means that the current thread will not wait while the email is getting sent. So if you send the email Synchronously, then the thread will wait for the email to send... which could be several seconds depending on your mail server. Sending the email Asynchronously means the current thread will continue on with whatever it was doing and the email will send on another thread. For web applications making the customer wait for several seconds can be a bit too long, and then taking into account that many customers could all be waiting for the same action, could mean a lot of waiting going on for something that is probably not a necessary action for the web application (such as sending a confirmation email).

    Hope this helps,
    -Jeff

  • thank you for a great tip on sending email (or doing other heavy lifting on the back end of the website)


  • Asynchronous means that the current thread will not wait while the email is getting sent.

    why i'm getting error for more recipients.

    any body who have an idea. please help me. tnx

  • Please see my code below...

    System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("sample@yahoo.com", "1234");
    smtpClient.UseDefaultCredentials = true;
    smtpClient.Credentials = SMTPUserInfo;
    smtpClient.EnableSsl = true;


    string[] to = { "sampleEmail@yahoo.com", "sample1Email@yahoo.com" };

    for (int i = 0; i < to.Length; i++)
    {

    m.To.Clear();
    m.To.Add(to[i]);
    SendEmailDelegate sd = new SendEmailDelegate(smtpClient.Send);
    AsyncCallback cb = new AsyncCallback(SendEmailResponse);
    sd.BeginInvoke(m, cb, sd);

    }

  • Hi Ryan,
    You are setting smtpClient.EnableSsl to true which could cause an issue and there is no from email address specified. Look into each one of those items for the problem.
    -Jeff

  • Hi Scott,
    Certain ISPs will only allow a set number of emails through in a certain time frame. So if you are trying to blast 500 emails as fast as your application can, your ISP may block you after the fifth email sent within a certain number of milliseconds. Check with your ISP and see if they do this and then if they do try to either pause for a second or so between emails or use a different ISP to send through.
    -Jeff

  • Thanks for posting your code. I found it to be very helpful since I have not been able to implement SendAsync successfully.

  • Excellent Article ....

  • It is really nice article.. Very helpful.. Thanks for posting..

  • Thanks man,
    itz working

  • Thanks for nice article

Comments have been disabled for this content.