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)