使用C#获取SMTP服务器证书

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

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

我不想调用openssl并解析其输出。 如何用C#做这个例子将非常感激。

一种方法是绑定到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("test@example.com", "test@example.com", "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; }