在与.NET 3.5的Windows控制台应用程序(我改变了现有的.NET 2.0应用程序到.NET 3.5)
我有奇怪的问题,code用于发送电子邮件的工作几次(可能是5到10倍)。
在几次,它无法与消息失败发送邮件发送电子邮件。同样的code重新启动系统后,工作。 (这是不是在生产预期的溶液)。
下面是一张code,我觉得,冥冥之中我已经接近这个SmtpClient连接。所以我设置客户端为null,叫GC.Collect的为好,但并没有帮助我。
请帮忙
私有静态无效SendEmail(MailMessage MSG)
{
SmtpClient客户=新SmtpClient(GetSMTPServer(),GetSMTPPort());
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.EnableSsl = FALSE;
client.ServicePoint.MaxIdleTime = 1;
//client.Timeout = GetSMTPTimeout(); 3000
client.Send(MSG);
客户端= NULL;
所以GC.Collect();
}
解决方案
尝试简单地使用使用
块来妥善处理 SmtpClient
后发送。
私有静态无效SendEmail(MailMessage MSG)
{
使用(SmtpClient客户端=新SmtpClient(GetSMTPServer(),GetSMTPPort()))
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.EnableSsl = FALSE;
client.Send(MSG);
}
}
另请参见:.NET最好的方法来发送电子邮件(System.Net.Mail有问题)
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();
}
解决方案
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)