SMTP - SSL 证书问题 - C# - 为什么此代码有效?

Erd*_*ase 2 c# ssl smtp

现在,这个问题在 Stack Overflow 中有多个版本,就像这个最受关注的问题一样,其中大多数答案都建议用户关闭 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);            
        }
Run Code Online (Sandbox Code Playgroud)

在尝试了几件事的同时,最后我尝试从服务器打印 SSL 证书,如此处所述。打印 SSL 证书

然后,异常就消失了。!!!我不明白为什么。

这是有效的代码

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;
}
Run Code Online (Sandbox Code Playgroud)

请解释一下它在原始代码仍然抛出异常时起作用的原因。

小智 6

以下代码告诉您的应用程序信任所有证书,即使它们无效。

最好不要这样做。

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; }
Run Code Online (Sandbox Code Playgroud)