【发布时间】:2021-10-27 23:37:09
【问题描述】:
当我尝试使用 MailKit SmtpClient 连接到我的 SMTP 服务器时出现异常。 但是如果我使用 System.Net.Mail.SmtpClient 和相同的参数,我的邮件已经发送成功了!
异常消息:An error occurred while attempting to establish an SSL or TLS connection.
内部异常消息:The handshake failed due to an unexpected packet format.
问题
- 为什么
MailKit.Net.Smtp.SmtpClient会抛出异常而System.Net.Mail.SmtpClient不会?它们有什么区别? - 如何解决?
代码
初始化邮件发送所需的参数:
var host = "myhost.com";
var port = 2525;
var from = "from@mydomain.com";
var to = "to@mydomain.com";
var username = "from@mydomain.com";
var password = "myPassword";
var enableSsl = true;
使用System.Net.Mail.SmtpClient发送邮件:
var client = new System.Net.Mail.SmtpClient
{
Host = host,
Port = port,
EnableSsl = enableSsl,
Credentials = new NetworkCredential(username, password)
};
client.Send(from, to, "subject", "body"); // success.
但是当我尝试使用MailKit 连接到具有相同主机和端口的主机时,出现异常:
var mailKitClient = new MailKit.Net.Smtp.SmtpClient();
mailKitClient.Connect(host, port, enableSsl); // it throws the exception.
【问题讨论】: