2011-02-24 85 views
1

使用C#如何连接到支持STARTTLS的SMTP服务器并获取其SSL证书?我知道这可以使用openssl这样的事情来完成使用C#获取SMTP服务器证书

openssl s_client -starttls smtp -crlf -connect 192.168.0.1:25 

我不想调用openssl并解析它的输出。非常感谢如何用C#做到这一点的一个例子。

回答

1

一种方法是绑定到ServerCertificateValidationCallback回调并发送测试消息到服务器。邮件可能失败,但证书仍然有效。

private void Form1_Load(System.Object sender, System.EventArgs e) 
    { 
     System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback); 
     using (System.Net.Mail.SmtpClient S = new System.Net.Mail.SmtpClient("smtp.gmail.com")) 
     { 
      S.EnableSsl = true; 
      using (System.Net.Mail.MailMessage M = new System.Net.Mail.MailMessage("[email protected]", "[email protected]", "Test", "Test")) 
      { 
       try 
       { 
        S.Send(M); 
       } 
       catch (Exception) 
       { 
        return; 
       } 
      } 
     } 
    } 
    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; 
    } 
+0

谢谢克里斯。这看起来非常有用。 – mozza 2011-02-24 20:51:08

+0

我应该指出'RemoteServerCertificateValidationCallback'实际上是用来执行证书的自定义验证。我只是在这里返回true,因为我不在乎证书是否真的有效。 – 2011-02-24 20:57:47

+0

是的,理解。 – mozza 2011-02-24 21:02:14