Search code examples
c#.net-4.0smtpclient

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


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.


Solution

  • Note: .NET 4.5 SmtpClient implements async awaitable method SendMailAsync. For lower versions, use SendAsync as described below.


    You should always dispose of IDisposable instances at the earliest possibility. In the case of async calls, this is on the callback after the message is sent.

    var message = new MailMessage("from", "to", "subject", "body"))
    var client = new SmtpClient("host");
    client.SendCompleted += (s, e) => {
                               client.Dispose();
                               message.Dispose();
                            };
    client.SendAsync(message, null);
    

    It's a bit annoying the SendAsync doesn't accept a callback.