首页 > 解决方案 > "The handshake failed due to an unexpected packet format" with SmtpClient

问题描述

I use SmtpClient to send email as below code:

SmtpClient client = new SmtpClient("host", 587);
client.EnableSsl = true;

client.Credentials = new System.Net.NetworkCredential("user", "pass");

MailAddress from = new MailAddress("from_mail", String.Empty, System.Text.Encoding.UTF8);

MailAddress to = new MailAddress("to_mail");
MailMessage message = new MailMessage(from, to);
message.Body = "Say hello";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "Testing";
message.SubjectEncoding = System.Text.Encoding.UTF8;

client.Send(message);

If I use .Net Framework 4.5, it will raise the error:The handshake failed due to an unexpected packet format. If I use .Net Framework 4.6.1, it will send mail successfully.

Please give me recommandation?

标签: c#.net

解决方案


可能是 TLS 版本问题。

如果在初始化 SMTP 客户端之前将 System.Net.ServicePointManager.SecurityProtocol 设置为使用 tls1.2,会发生什么?

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

推荐阅读