Sending mail asynchronously in MVC

With the release of .NET 4.5, SmtpClient.SendAsync() will cause exceptions in MVC controller methods.

“An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle.”

The solution is NOT changing MVC controller methods.  The solution is:

  • Create a wrapper function.  Make it an asynchronous function by using the keyword async.  You can optionally change the return type to “Task<xxx>”.
  • Call SmtpClient.Send() instead of SmtpClient.SendAsync().
  • “await Task.Yield()” in order to force SmtpClient.Send() to complete asynchronously.
  • MVC controller methods will just invoke this wrapper function normally.
public static async Task<bool> SendEmailAwaitable(MailMessage message, string server, int port) {    
SmtpClient smtpClient = new SmtpClient(server, port);
smtpClient.Send(messsage);
await Task.Yield();
return true;
}