Properly disposing resources used by SmtpClient

emailmailmessagesendsmtpclient

I have a C# service that runs continuously with user credentials (i.e not as localsystem – I can't change this though I want to). For the most part the service seems to run ok, but ever so often it bombs out and restarts for no apparent reason (servicer manager is set to restart service on crash).

I am doing substantial event logging, and I have a layered approach to Exception handling that I believe makes at least some sort of sense:

  • Essentially I got the top level generic exception, null exception and startup exception handlers.
  • Then I got various handlers at the "command level" (i.e specific actions that the service runs)
  • Finally I handle a few exceptions handled at the class level

I have been looking at whether any resources aren't properly released, and I am starting to suspect my mailing code (send email). I noticed that I was not calling Dispose for the MailMessage object, and I have now rewritten the SendMail code as illustrated below.

The basic question is:

  • will this code properly release all resources used to send mails?
  • I don't see a way to dispose of the SmtpClient object?
  • (for the record: I am not using object initializer to make the sample easier to read)
    private static void SendMail(string subject, string html)
    {
        try
        {
            using ( var m = new MailMessage() )
            {
                m.From = new MailAddress("service@company.com");
                m.To.Add("user@company.com");
                m.Priority = MailPriority.Normal;
                m.IsBodyHtml = true;
                m.Subject = subject;
                m.Body = html;
                var smtp = new SmtpClient("mailhost");
                smtp.Send(m);
            }
        }
        catch (Exception ex)
        {
            throw new MyMailException("Mail error.", ex);
        }
    }

Best Solution

I know this question is pre .Net 4 but version 4 now supports a Dispose method that properly sends a quit to the smpt server. See the msdn reference and a newer stackoverflow question.