.NET 3.5 Smtpclient - failure sending email - works only after restarting everytime

别说谁变了你拦得住时间么 提交于 2019-12-11 02:05:49

问题


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:

  1. try catch sending, if catch an exception, send again.
  2. SmtpClient.Dispose() for .net framework 3.0 and above
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!