简体   繁体   中英

Sporadic SMTP email sending failures in C#

I have an application that has been live a while and occasionally users can trigger an email to be sent , which uses SmtpClient with Office 365.

Since about 3 days ago we're having some failures sending emails, which seem to occur randomly throughout the day. The error is always

“ Authentication failed because the remote party has closed the transport stream.”

I've attached the code and full stack trace below. Does anyone know what this error means?

string fromEmailAddress = ProgramHelpers.SMTPFrom; // for 365 have to use the from email setup in the ini. NR 28/9/20
        int portNumber = ProgramHelpers.SMTPPort == "" ? 25 : Convert.ToInt32(ProgramHelpers.SMTPPort);
        bool ssl = true;
 
        using (SmtpClient smtp = new SmtpClient(ProgramHelpers.SMTPHost))
        {
            smtp.Port = portNumber;
            smtp.EnableSsl = ssl;
            var user = ProgramHelpers.SMTPUser;
            if (user != string.Empty)
                smtp.Credentials = new NetworkCredential(user, ProgramHelpers.SMTPPassword);
 
            MailMessage m = new MailMessage();
            m.From = new MailAddress(fromEmailAddress);
 
            if (string.IsNullOrWhiteSpace(to))
            {
                var warningMessage = $"Cannot send email with subject '{subject}' as the 'to' email address is blank";
                _logger.Warn(warningMessage);
                return Result.Failure(new Exception(warningMessage));
            }
 
            foreach (var email in to.Split(';', ',').Where(a => !a.IsNullOrWhiteSpace()))
                m.To.Add(email.Trim());
 
            m.Subject = subject;
            m.Body = body;

            m.IsBodyHtml = isHtml;
            if (fileAttachment != null)
            {
                m.Attachments.Add(fileAttachment);
            }
 
            if (additionalAttachment != null && additionalAttachment.Trim() != "")
            {
                m.Attachments.Add(new Attachment(additionalAttachment));
            }
 
            //Try and send the message
            try
            {
                smtp.Send(m);
                return Result.Success();
            }
            //Catch any errors...
            catch (Exception x)
            {
                var ex = new SmtpException($"Failed to send mail with subject {m.Subject} to {m.To.FirstOrDefault()} with SMTP server {smtp.Host}/{smtp.Port} (SSL: {smtp.EnableSsl}", x);
                _logger.Error(ex, ex.Message);
                return Result.Failure(x);
            }
        }

Stack trace:

System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Authentication failed because the remote party has closed the transport stream. at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.TlsStream.CallProcessAuthentication(Object state)

I had this exact same error and traced it down to the fact that our service was hardcoded to use TLS 1.0 for encyrpting the SMTP connection and Office 365 is in the process of turning off support for TLS 1.0 and TLS 1.1 and enforcing TLS 1.2.

You can read more about this on this stack overflow question which explains more about this specific exception, and in the microsoft docs that explain they are in the process of turning off TLS 1.0 and 1.1. There is no official documentation for it but I think something changed in the last few weeks as our service was working totally fine until about October 1 but since then has been really unreliable (but still working just enough to get by).

You can see a report on TLS usage in Office 365 here: https://protection.office.com/mailflow/dashboard . Just expand the "SMTP Auth Clients" report and you'll see a breakdown of TLS usage. Ideally you want everything to be using TLS 1.2 so if you see anything using TLS 1.0 or 1.1 you need to update that ASAP.

Assuming this explains your problem, I'm not sure what exactly you need to do in your specific case to switch to TLS 1.2, but this stack overflow question should give you some leads to try.

Microsoft posted this:

We are fully aware that many customers will not have noticed the multiple Message Center posts and blog posts, and are not aware of clients or devices that are still using TLS1.0 to submit messages. With this in mind, starting in September 2021, we will reject a small percentage of connections that use TLS1.0 for SMTP AUTH. Clients should retry as with any other temporary errors that can occur during submission. Over time we will increase the percentage of rejected connections, causing delays in sending that more and more customers should notice.

Seems likely to be the cause of this issue.

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