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.