Daily Archives: January 16, 2007

Importance of disposing MailMessage objects

Always, always, always follow the suggested usage patterns of disposable objects. I had a strange problem recently where e-mail messages with attachments weren’t releasing the lock on the files for a long time. I was using the System.Net.Mail namespace, specifically the Attachment and MailMessage classes.

Disposable objects represent resources not directly under control by the CLR–and this includes SMTP connections. By not calling dispose, the mail message was just sitting around, not getting sent. Why this is the case when I explicitly call SmtpClient.Send is unclear. The main symptom of this problem was that files that I attached to the e-mail message were still locked when I tried to delete them immediately after the send.

Something like this will do:

using (MailMessage msg = new MailMessage()) 
{ 
    msg.Attachments.Add(...); 
    client.Send(msg); 
}