Skip to main content

C# extension method for sending a MailMessage object in a Task; encapsulating the SMTP client Send operation.

//
// ref: https://nazimkuet.wordpress.com/2015/08/05/how-to-send-email-asynchronously-in-asp-net-using-background-thread/

public static void Send(this MailMessage self)
{
    Task.Factory.StartNew(() =>
    {
        // Make sure your caller Dispose()'s the email it passes in at some point!
        using (SmtpClient client = new SmtpClient("smtp.server.address"))
        {
            client.Send(self);
        }
    }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}

// http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
// Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);