使用C#获取SMTP服务器证书 [英] Use C# to get an SMTP server certificate

查看:140
本文介绍了使用C#获取SMTP服务器证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我不想调用openssl并解析其输出.一个用C#做到这一点的例子将不胜感激.

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.

推荐答案

一种方法是绑定到

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

这篇关于使用C#获取SMTP服务器证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆