C# – ny way to close mail smtp session

cnetsmtp

I am using Gmail STMP server to send emails. It works just fine. But from few days, it sometimes stops working. Now, it is only working 5 out of 10 times.

Exception: Failure Sending Email

Inner Exception: Unable to connect to remote server.

After talking to hosting technical support, they said there is a mail session limit on their server. This is a Shared Hosting, so when it exceeds all new connections are blocking. They said they are trying to fix it. But also said please check that you are closing the mail session properly or not.

I looked into it, but there is no Close() or Dispose(). I also read there is no acknowledgement for SMTP tranfer?

Please let me know if there is anyway to close the mail session? Or any workaround to fix this issue.

Update

I am using System.Net.Mail

MailMessage msg = new MailMessage();

SmtpClient sc = new SmtpClient("smtp.gmail.com", 587);

NetworkCredential info = new NetworkCredential("email", "password");

Then there is another method which calls sc.Send().

Best Answer

The System.Net.Mail.SmtpClient implements IDisposable, so I would suggest you use that rather than whatever code you are currently using. Use a using block to ensure it gets correctly disposed of.

Note particularly that use of System.Web.Mail is deprecated in favour of System.Net.Mail.

using (SmtpClient client = new SmtpClient("mail.google.com")) 
{

}

EDIT You've noted now that you are using System.Net.Mail. In that case, you will find that the SMTPClient does have a Dispose method (as it implements IDisposable), which will gracefully close the SMTP connection. However, it is considered better practice to use a using block, rather than calling Dispose directly. Finally, please note the following from the linked documentation:

The SmtpClient class has no Finalize method. So an application must call Dispose to explicitly free up resources.

The Dispose method iterates through all established connections to the SMTP server specified in the Host property and sends a QUIT message followed by gracefully ending the TCP connection. The Dispose method also releases the unmanaged resources used by the underlying Socket.