What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0
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.
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.