Properly disposing resources used by SmtpClient
Asked Answered
E

2

6

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("[email protected]");
                m.To.Add("[email protected]");
                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);
        }
    }
Etherize answered 14/7, 2009 at 22:24 Comment(0)
P
5

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.

Protean answered 15/10, 2010 at 0:36 Comment(0)
R
1

There are documented issues with the SmtpClient class. I recommend buying a third party control since they aren't too expensive. Chilkat makes a decent one.

Reconnoiter answered 14/7, 2009 at 22:29 Comment(2)
Thanks for the info - I might have to look at that. It's strange that the MailMessage object implements IDisposable, but the SmtpClient does not.Renowned
Yeah. There seems to be a work around posted on that link. May want to check that out.Reconnoiter

© 2022 - 2024 — McMap. All rights reserved.