2

Using C# how do I connect to a SMTP server that supports STARTTLS and get its SSL certificate? I know it can be done using openssl with something like this

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

I don't want to call openssl and parse its output though. An example of how to do it with C# would be very much appreciated.

mozza
  • 965
  • 1
  • 9
  • 9

1 Answers1

4

One way would be to bind to the ServerCertificateValidationCallback callback and send a test message to the server. The mail message might fail but the certificate will still be valid.

    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;
    }
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • I should point out that `RemoteServerCertificateValidationCallback` is actually intended to be used to perform custom validation of certificates. I'm just returning true here because I don't care whether the cert is actually valid. – Chris Haas Feb 24 '11 at 20:57