Sending emails in the background
Recently I've noticed that mail servers can get really slow to respond sometimes. Perhaps that's just a symptom of using shared servers - it only takes one other client of my web hosting company to be sending 1,000 emails out for my email to be delayed a few seconds.
Because my CMS sends out notification emails whenever content is created/edited this means that there's a delay when using the CMS while the email is sent. Effectively it looks like the CMS is slow.
So I decided to write some code to send emails on a background thread. I use aspNetEmail so I figured someone may have already asked this question or Dave Wanta may have posted an example on his site, so I went looking.
And this is why I am such a fan of using best-in-class components like aspNetEmail or aspNetMX - Dave already has a method called BeginSend that does asynchronous email!
He also has another neat method - SendToMSPickup() - that I am also offering as an option to users. I'm not sure if it is quicker (I suspect it is too), but it's a great alternative for customers who don't have (or want to use) a SMTP mail server.
So, this HUGE improvement to the CMS - saving content is once again instantaneous - consisted of the few lines below:
#region Send email using correct method
switch (DAL.StringSetting("MailMethod").ToLower())
{
case "mspickup":
bSuccess = msg.SendToMSPickup();
break;
case "background":
bSuccess = msg.BeginSend(new AsyncCallback(EmailCallback), msg);
break;
case "regular":
bSuccess = msg.Send();
break;
default:
throw new ArgumentOutOfRangeException
("MailMethod",
DAL.StringSetting("MailMethod"),
"Unknown MailMethod setting in web.config");
}
if (!bSuccess)
{
EmailError(msg);
return false;
}
#endregion
and this simple method is called when background email is sent:
/// <summary>
/// Called after an email is sent
/// </summary>
private static void EmailCallback(IAsyncResult result)
{
EmailMessage msg = (EmailMessage)result.AsyncState;
if (!msg.EndSend(result))
EmailError(msg);
}
Thanks Dave, this is great!