Proper Disposing of System.Net.Mail.MailMessage
Friday, October 31st, 2008I ran into this today while working on some client code.
Some of the overrides for System.Net.Mail.Attachment take a Stream parameter. The Attachment class will hold on to that stream until you send the corresponding MailMessage.
To ensure that the stream is cleaned up properly you need to call Dispose() on the MailMessage instance when you are finished with it:
using (MailMessage message = BuildMessage())
{
SmtpClient client = new SmtpClient();
client.Send(message);
}
Using .NET Reflector, you can see that disposing the MailMessage disposes each Attachment, which will in turn close each Stream.
If you don’t dispose the MailMessage, you are at the mercy of the garbage collector. For a FileStream that can cause unexpected, and seemingly unrelated, problems.