What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0

tofutim picture tofutim · Sep 1, 2011 · Viewed 83.2k times · Source

I'm a bit perplexed on how to manage SmtpClient now that it is disposable, especially if I make calls using SendAsync. Presumably I should not call Dispose until SendAsync completes. But should I ever call it (e.g., using "using"). The scenario is a WCF service which mails out email periodically when calls are made. Most of the computation is fast, but the sending of email can take a second or so, so Async would be preferable.

Should I create a new SmtpClient each time I send mail? Should I create one for the entire WCF? Help!

Update In case it makes a difference, each email is always customized to the user. The WCF is hosted on Azure and Gmail is used as the mailer.

Answer

Boris Lipschitz picture Boris Lipschitz · Mar 18, 2014

The original question was asked for .NET 4, but if it helps as of .NET 4.5 SmtpClient implements async awaitable method SendMailAsync.

As a result, to send email asynchronously is as the following:

public async Task SendEmail(string toEmailAddress, string emailSubject, string emailMessage)
{
    using (var message = new MailMessage())
    {
        message.To.Add(toEmailAddress);

        message.Subject = emailSubject;
        message.Body = emailMessage;

        using (var smtpClient = new SmtpClient())
        {
            await smtpClient.SendMailAsync(message);
        }
    }
}

It's better to avoid using SendAsync method.