MailKit C# SmtpClient.Connect() 到 Office 365 生成异常:"An existing connection was forcibly closed by the remote host"

MailKit C# SmtpClient.Connect() to Office 365 generating exception: "An existing connection was forcibly closed by the remote host"

我在通过 Office 365 SMTP 和 MailKit 发送电子邮件时遇到问题。我得到的例外是:

Unhandled Exception: 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

https://github.com/jstedfast/MailKit

代码:

var smtpClient = new SmtpClient();

smtpClient.Connect("smtp.office365.com", 587, true);

Microsoft Office 365 设置应该正确:

https://support.office.com/en-us/article/POP-and-IMAP-settings-for-Outlook-Office-365-for-business-7fc677eb-2491-4cbc-8153-8e7113525f6c

奇怪的是,如果我使用以下一切正常,即使 Office 365 说需要 SSL。

smtpClient.Connect("smtp.office365.com", 587, false);

发布这个问题后又出现了另一个错误,这让我找到了答案:

Handshake failed due to an unexpected packet format

解决方案是像这样连接到 Office 365:

smtpClient.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);