MailKit C#SmtpClient.Connect()到Office 365生成异常:"远程主机强行关闭现有连接"

Ogg*_*las 8 c# office365 mailkit

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

未处理的异常:System.IO.IOException:无法从传输连接读取数据:远程主机强制关闭现有连接.

System.Net.Sockets.SocketException:远程主机强制关闭现有连接

https://github.com/jstedfast/MailKit

码:

var smtpClient = new SmtpClient();

smtpClient.Connect("smtp.office365.com", 587, true);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

Ogg*_*las 16

发布此问题后得到了另一个错误,这让我得到了答案:

由于意外的数据包格式,握手失败

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

smtpClient.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
Run Code Online (Sandbox Code Playgroud)

  • 只需评论以确认这是正确的解决方案。SMTP实际上仅在端口465上使用SSL包装的连接。如果端口2和587完全使用“ SSL”,则它们将使用StartTLS。不幸的是,这在配置指南中通常没有很好地解释。 (2认同)