Dispose SmtpClient in SendComplete?

Jeff Chen picture Jeff Chen · Apr 14, 2011 · Viewed 8k times · Source

When I use SmtpClient's SendAsync to send email, how do I dispose the smtpclient instance correctly?

Let's say:


MailMessage mail = new System.Net.Mail.MailMessage()
{
   Body = MailBody.ToString(),
   IsBodyHtml = true,
   From = new MailAddress(FromEmail, FromEmailTitle),
   Subject = MailSubject
};
mail.To.Add(new MailAddress(i.Email, ""));
SmtpClient sc = new SmtpClient(SmtpServerAddress);
//Add SendAsyncCallback to SendCompleted
sc.SendCompleted += new SendCompletedEventHandler(SendAsyncCallback);
//using SmtpClient to make async send (Should I pass sc or mail into SendAsyncCallback?)
sc.SendAsync(mail, sc);

In the SendAsyncCallback method, should I call sc.Dispose(), or mail.Dispose()?

I checked MSDN document, one example calls MailMessage.Dispose(), but will this dispose method also dispose the SmtpClient instance?

Answer

Bradley Grainger picture Bradley Grainger · May 19, 2011

You should dispose both the MailMessage and the SmtpClient in SendAsyncCallback.

Disposing the MailMessage will not dispose the SmtpClient automatically (because you might want to send two messages with the same SmtpClient, and you wouldn't want the client to be disposed as soon as you disposed the first message).