问题
In Windows Console Application with .NET 3.5 ( I changed the existing .NET 2.0 application to .NET 3.5 )
I have strange problem, the code for sending email works few times(may be 5 to 10 times).
After few times, it fails to send the email with message "Failure sending mail". The same code works after restarting the system. ( which is not the expected solution in production).
Here is the piece of code, I felt , somewhere I have close this SmtpClient Connection. so I set the client to null and called GC.Collect as well, but did not help me.
Please help
private static void SendEmail(MailMessage msg)
{
SmtpClient client = new SmtpClient(GetSMTPServer(), GetSMTPPort());
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.EnableSsl = false;
client.ServicePoint.MaxIdleTime = 1;
//client.Timeout = GetSMTPTimeout(); 30000000
client.Send(msg);
client = null;
GC.Collect();
}
回答1:
Try simply using a using
block to properly dispose the SmtpClient
after sending.
private static void SendEmail(MailMessage msg)
{
using(SmtpClient client = new SmtpClient(GetSMTPServer(), GetSMTPPort()))
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.EnableSsl = false;
client.Send(msg);
}
}
See also: .NET Best Method to Send Email (System.Net.Mail has issues)
回答2:
If the interval between two mail sending is bigger than 60 seconds and smaller than 90 seconds, you will get this error definitely.
for example, you send out the first email at 8:08:08 am, and then send out the second email at 8:09:10 am, an exception will be throw out.
it is a bug on SmtpClient.TimeOut
settings, you can't change it.
how to solve this problem? three ways:
- try catch sending, if catch an exception, send again.
SmtpClient.Dispose()
for .net framework 3.0 and above- set
SmtpClient.servicepoint.maxidletime=1000;
set to 1 is too small, not work in debug mode
来源:https://stackoverflow.com/questions/13689265/net-3-5-smtpclient-failure-sending-email-works-only-after-restarting-everyt