我在尝试连接到“smtp.office365.com“时收到MailKit.Security.SslHandshakeException异常

6yt4nkrj  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(62)

我正在尝试使用MailKit通过“smtp.office365.com“发送电子邮件。这是我使用的代码。

using (var client = new SmtpClient(new ProtocolLogger("smtp.log")))
{
    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
    client.Connect("smtp.office365.com", 587, SecureSocketOptions.SslOnConnect);
    client.Authenticate(new SaslMechanismNtlmIntegrated());
    Debug.WriteLine(client.IsAuthenticated);
    client.Send(message);
    client.Disconnect(true);
}

字符串
我从GitHub上的这条评论中得到的SaslMechanismNtlmIntegrated类。
每当我运行这段代码时,我都会得到一个SslHandshakeException
以下是例外的详细信息:

MailKit.Security.SslHandshakeException
  HResult=0x80131500
  Message=An error occurred while attempting to establish an SSL or TLS connection.

One possibility is that you are trying to connect to a port which does not support SSL/TLS.

The other possibility is that the SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. The certificate presented by the server is expired or invalid.

See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#InvalidSslCertificate for possible solutions.
  Source=MailKit
  StackTrace:
   at MailKit.Net.Smtp.SmtpClient.<ConnectAsync>d__70.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at MailKit.Net.Smtp.SmtpClient.Connect(String host, Int32 port, SecureSocketOptions options, CancellationToken cancellationToken)
   at QuoteAndOrder.SpecialsQuoteWindow.BtnEmail_Click(Object sender, RoutedEventArgs e) in SpecialsQuoteWindow.xaml.cs:line 501

Inner Exception 1:
IOException: The handshake failed due to an unexpected packet format.


我去了细节中提到的常见问题解答,但给出的解决方法并没有解决这个问题。

sxpgvts3

sxpgvts31#

willaien提到的解决方案解决了这个问题,即使用SecureSocketOptions.StartTls代替SecureSocketOptions.SslOnConnect

lsmd5eda

lsmd5eda2#

我花了几个小时调试这个异常,MailKit的FAQ中指出的原因都没有帮助。
因此,我为未来可能遇到这种错误并降落在这里的谷歌人增加了2美分。

背景

对于TLS/SSL的东西.NET在某种程度上使用操作系统的加密原语(Windows上的SChannel和Linux上的OpenSSL)。这些库可以配置为使用一组“cihper套件”,这些套件不受您试图连接到的远程服务器的支持。
仔细看看SslHandShakeException的内部异常。
在我的例子中,我在Linux上得到了一个"SSL Handshake failed with OpenSSL error - SSL_ERROR_SSL"错误。
假设你不能直接打电话给电子邮件服务器提供商,要求他们升级他们的密码套件,你可以这样做:

Linux修复

要在Linux上解决此错误,通常需要编辑/etc/openssl/openssl.cnf文件并将CipherString SECLEVEL从“2”降低到“1”

[system_default_sect]
CipherString = DEFAULT:@SECLEVEL=1

字符串

Windows修复

在Windows上,启用/禁用密码套件由注册表控制,您可以Google更改键和值。或者尝试一个名为“IISCrypto”的免费工具,每个人都将其用作此类东西的GUI编辑器(我不隶属于IISCrypto,但我在Windows时代确实经常使用它)

相关问题