【发布时间】:2021-11-27 20:59:06
【问题描述】:
我有一个应用程序已经运行了一段时间,偶尔用户可以触发发送电子邮件,它使用 SmtpClient 和 Office 365。
从大约 3 天前开始,我们在发送电子邮件时遇到了一些失败,这似乎是全天随机发生的。错误总是
“验证失败,因为远程方关闭了传输流。”
我在下面附上了代码和完整的堆栈跟踪。有谁知道这个错误是什么意思?
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);
}
}
堆栈跟踪:
System.Net.Mail.SmtpException:发送邮件失败。 ---> System.IO.IOException: 身份验证失败,因为远程方已关闭传输流。 在 System.Net.Security.SslState.StartReadFrame(字节 [] 缓冲区,Int32 读取字节,AsyncProtocolRequest asyncRequest) 在 System.Net.Security.SslState.StartReceiveBlob(字节 [] 缓冲区,AsyncProtocolRequest asyncRequest) 在 System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken 消息,AsyncProtocolRequest asyncRequest) 在 System.Net.Security.SslState.StartSendBlob(字节 [] 传入,Int32 计数,AsyncProtocolRequest asyncRequest) 在 System.Net.Security.SslState.ForceAuthentication(布尔接收第一,字节 [] 缓冲区,AsyncProtocolRequest asyncRequest) 在 System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResultlazyResult) 在 System.Net.TlsStream.CallProcessAuthentication(对象状态)
【问题讨论】:
-
我最近也遇到了这个错误。不会一直随机发生。
-
看看这篇文章。它有一个可能的解决方案...stackoverflow.com/questions/43240611/…