Proper allocation of resources used by SmtpClient

I have a C # service that works continuously with user credentials (that is, not like the localsystem - I cannot change this, although I want to). For the most part, the service seems to be working fine, but so often it explodes and restarts for no apparent reason (the surf manager is configured to restart the service if it fails).

I am making a substantial event log , and I have a multi-level approach to Exception Handling , which in my opinion makes at least some sense

  • Essentially, I got a high level of general exclusion, exception exclusion, and launch exception handlers.
  • Then I got various handlers at the level "(e.g. specific actions performed by the service)
  • Finally, I handle a few exceptions handled at the level

I looked to see if any resources were released, and I'm starting to suspect my zip code (send email). I noticed that I did not call Dispose on the MailMessage object, and now I rewrote the SendMail code, as shown below.

The main question :

  • Will this code correctly issue all resources used to send emails?
  • I don’t see a way to delete the SmtpClient object?
  • (for writing: I don't use an object initializer to make reading easier)
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); } } 
+6
email smtpclient mailmessage send
source share
2 answers

I know this question is pre.Net 4, but now version 4 supports the Dispose method, which correctly sends the output to the smpt server. See the msdn link and the new transition stack question .

+5
source share

documented problems with the SmtpClient class. I recommend buying a third-party control as they are not too expensive. Chilkat makes worthy.

+1
source share

All Articles