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

时间:2018-10-08 07:22:07

标签: c# ssl smtp

现在,这个问题在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 个答案:

答案 0 :(得分:3)

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

最好不要这样做。

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; }