How to send Asynchronous email from .net :

May 25, 2012 By Anil Gaikwad

In this article I will show you how to send mail asynchronously, which can be used in sending bulk mail. This feature is very useful when you send lots of bulk mails like news letter. You don’t have to wait for response from mail server and you can do other task or with the help of this feature you don’t need to wait for the email to be sent before performing other tasks in the page. But instead these tasks can be performed while the mail is being sent asynchronously.

System.Net.Mail has also added asynchronous support for sending email. To send asynchronously, you need need to

  • Declare event handler which will asynchronously call Email send completed Event.
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
  • Create the SendCompleted event which will have functionality to send asynchronous mail.
void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { MailMessage mail = e.UserState as MailMessage; if (!e.Cancelled && e.Error!=null) { Finalmessage.Text = "Mail sent successfully"; } }
  • Call SmtpClient.SendAsync will send that mail.
smtpClient.SendAsync(mail, state);

Complete Code Example:

public void SendAsyncMail() { MailMessage mail = new MailMessage(); mail.From = new MailAddress("def@def.com"); mail.To.Add(new MailAddress("xyz@xyz.com")); mail.To.Add(new MailAddress("abc@abc.com ")); mail.Subject = "Enter mail subject"; mail.Body = "Enter mail body"; SmtpClient smtpClient = new SmtpClient(); Object state = mail; //event handler for asynchronous call smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted); try { smtpClient.SendAsync(mail, state); } catch (Exception ex) { } } void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { MailMessage mail = e.UserState as MailMessage; if (!e.Cancelled && e.Error!=null) { message.Text = "Mail sent successfully"; } }