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);
await Task.Yield();
return true;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s