Is there a way to close the smtp mail session?

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

Exception: Failure Sending Email

Internal exception: Unable to connect to remote server.

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

I looked at it, but there is no Close() or Dispose() . I also read that there is no confirmation for the SMTP transfer?

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

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 that calls sc.Send() .

+7
source share
1 answer

System.Net.Mail.SmtpClient implements IDisposable, so I suggest you use this, and not any code that you are currently using. Use using the unit to make sure it is disposed of correctly.

Note that using System.Web.Mail is deprecated in favor of System.Net.Mail .

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

EDIT You have already noticed that you are using System.Net.Mail . In this case, you will find that SMTPClient has a Dispose method (since it implements IDisposable) that gracefully closes the SMTP connection. However, it is believed that it is better to use the using block rather than a direct call to Dispose . Finally, pay attention to the following from related documentation:

The SmtpClient class does not have a Finalize method. Therefore, the application must invoke utilize explicit release resources.

The Dispose method iterates through all the established connections with the SMTP server specified in the Host property and sends a QUIT message followed by a graceful TCP connection termination. The Dispose method also releases unused resources used by the underlying Socket.

+12
source

All Articles