SMTP - SSL 证书问题 - C# - 为啥此代码有效?
Posted
技术标签:
【中文标题】SMTP - SSL 证书问题 - C# - 为啥此代码有效?【英文标题】:SMTP - SSL Certificate Issue - C# - Why this code works?SMTP - SSL 证书问题 - C# - 为什么此代码有效? 【发布时间】:2019-03-12 19:55:41 【问题描述】:现在,这个问题在 Stack Overflow 中有几个版本,例如 most viewed question,其中大多数答案建议用户关闭 SSL 作为绕过代码的方法。
我在尝试发送电子邮件时遇到了同样的异常。
System.Security.Authentication.AuthenticationException: 远程证书根据验证无效 过程。
这是我的代码
private void sendAMail(String toAddress, String messageBody)
String msg = "Sending mail to : " + toAddress;
MailMessage mail = new MailMessage();
mail.To.Add(toAddress);
mail.From = new MailAddress("from@mydomain.com");
mail.Subject = "Subject: Test Mail";
mail.Body = messageBody;
mail.IsBodyhtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "myhostname.com";
smtp.Credentials = new System.Net.NetworkCredential("sender@sample.com", "");
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Send(mail);
在尝试几件事时,最后我尝试从服务器打印 SSL 证书,如此处所述。Print SSL Cert
然后,异常消失了。!!!我不知道为什么。
这是有效的代码
private void sendAMail(String toAddress, String messageBody)
String msg = "Sending mail to : " + toAddress;
MailMessage mail = new MailMessage();
mail.To.Add(toAddress);
mail.From = new MailAddress("from@mydomain.com");
mail.Subject = "Subject: Test Mail";
mail.Body = messageBody;
mail.IsBodyHtml = true;
//Added this line here
System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
SmtpClient smtp = new SmtpClient();
smtp.Host = "myhostname.com";
smtp.Credentials = new System.Net.NetworkCredential("sender@sample.com", "");
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Send(mail);
private bool RemoteServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
//Console.WriteLine(certificate);
return true;
请解释它在原始代码仍然抛出异常时工作的原因。
【问题讨论】:
【参考方案1】:以下代码告诉您的应用程序信任所有证书,即使它们无效。
最好不要这样做。
private bool RemoteServerCertificateValidationCallback(object sender,
System.Security.Cryptography.X509Certificates.X509Certificate
certificate, System.Security.Cryptography.X509Certificates.X509Chain
chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
//Console.WriteLine(certificate);
return true;
【讨论】:
以上是关于SMTP - SSL 证书问题 - C# - 为啥此代码有效?的主要内容,如果未能解决你的问题,请参考以下文章