C# how to correctly dispose of an SmtpClient?
- by JL
VS 2010 code analysis reports the following:
Warning 4 CA2000 : Microsoft.Reliability : In method 'Mailer.SendMessage()', object 'client' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'client' before all references to it are out of scope.
My code is :
public void SendMessage()
{
SmtpClient client = new SmtpClient();
client.Send(Message);
client.Dispose();
DisposeAttachments();
}
How should I correctly dispose of client?
Update: to answer Jons question, here is the dispose attachments functionality:
private void DisposeAttachments()
{
foreach (Attachment attachment in Message.Attachments)
{
attachment.Dispose();
}
Message.Attachments.Dispose();
Message = null;
}