已设置useSsl为false,MailKit为何仍尝试建立SSL连接?
MailKit 非安全连接仍触发SSL握手异常的原因及解决方法
代码示例
var eMail = new MimeMessage(); eMail.From.Add(new MailboxAddress(sender, sender)); eMail.To.Add(new MailboxAddress(recipient, recipient)); eMail.Subject = subject; eMail.Body = new TextPart(TextFormat.Plain) { Text = body }; using (var smtpClient = new SmtpClient()) { smtpClient.Connect("smtp.foo.com", 25, false); smtpClient.Send(eMail); smtpClient.Disconnect(true); }
抛出异常
MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection. The host name (smtp.foo.com) did not match any of the names given in the server's SSL certificate: • ... • ... ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure. at ...
原因分析
你调用Connect时传入的第三个参数false仅表示不通过SSL直接建立初始连接,但MailKit的SmtpClient默认会检测服务器是否支持STARTTLS协议,若支持则自动发起TLS握手升级连接。这就导致即便你想使用纯非安全连接,仍会触发SSL证书校验,最终因为证书域名不匹配抛出异常。
解决方法
要彻底禁用所有SSL/TLS相关的连接升级,最直接的方式是在Connect方法中使用SecureSocketOptions.None枚举,明确指定不使用任何SSL/TLS:
var eMail = new MimeMessage(); eMail.From.Add(new MailboxAddress(sender, sender)); eMail.To.Add(new MailboxAddress(recipient, recipient)); eMail.Subject = subject; eMail.Body = new TextPart(TextFormat.Plain) { Text = body }; using (var smtpClient = new SmtpClient()) { // 明确指定不使用任何SSL/TLS,包括STARTTLS升级 smtpClient.Connect("smtp.foo.com", 25, SecureSocketOptions.None); smtpClient.Send(eMail); smtpClient.Disconnect(true); }
也可以通过设置EnableSsl和SslProtocols属性来实现:
using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = false; smtpClient.SslProtocols = System.Security.Authentication.SslProtocols.None; smtpClient.Connect("smtp.foo.com", 25, false); smtpClient.Send(eMail); smtpClient.Disconnect(true); }
两种方式都能阻止MailKit尝试建立SSL/TLS连接,推荐使用SecureSocketOptions.None的写法,语义更清晰。
内容的提问来源于stack exchange,提问作者Powerslave
相关产品推荐
相关产品推荐

