简体   繁体   中英

Intermittent System.IO.IOException while using SmtpClient

I'm having a problem with .NET's SmtpClient . Every so often, the Send method throws the following exception:

System.Net.Mail.SmtpException: Failure sending mail.
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   --- End of inner exception stack trace ---

We're averaging around 550 emails per hour (or ~9 emails per minute) in production, and the problem never seems to occur in QA.

Every email is sent like this:

using (var newMessage = new MailMessage { ReplyTo = new MailAddress(supportEmail, "Support") })
{
    newMessage.To.Add(recipients);
    newMessage.From = new MailAddress(fromEmail, "From Name");
    newMessage.Subject = message.Subject;
    newMessage.Body = body;
    using (var mailHost = new SmtpClient())
    {
        mailHost.Send(newMessage);
    }
}

Note that we're disposing all resources, we aren't using SSL, and we're loading the Smtp settings from web.config , which look like this:

   <mailSettings>
      <smtp from="validEmail"  deliveryMethod="Network"  >        
        <network defaultCredentials ="false" host="dedicatedSmtpServer" port="port"/>
      </smtp>
    </mailSettings>

Some notes I've put together:

  1. Every email is sent with its own instance of SmtpClient . This is true even in bulk-sending scenarios. I've read that this could have performance implications since the sockets aren't pooled. However, performance seems to be adequate when it does work.
  2. We're using .NET 4, so the bug where SmtpClient wasn't terminating connections is fixed.
  3. According to a colleague (I don't have access to the server logs myself), the SMTP server doesn't log connection attempts for the emails that fail (although the successful emails do have log entries)

Your code has nothing to do with this. This particular error:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

basically means that the remote end has terminated the socket. The 'forcibly" just means it was done in an unusual way but it is still the remote end. It may be due to how long the socket stayed open, so implementing a socket pool definitely is a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM