C#获取SMTP-服务器的SSL证书有效期从ServerCertificateValidationCallback
问题描述:
返回值此刻我有了这个代码,以获得SMTP-服务器的有效期限:C#获取SMTP-服务器的SSL证书有效期从ServerCertificateValidationCallback
namespace SMTPCert
{
public class SMTPCert
{
public static void GetSMTPCert(string ServerName)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
using (System.Net.Mail.SmtpClient S = new System.Net.Mail.SmtpClient(ServerName))
{
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 static bool RemoteServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Console.WriteLine(certificate);
return true;
}
}
}
我的问题是,我想将GetSMTPCert方法从void更改为字符串,以便将证书到期日期返回给我的主方法。 但目前我只能在RemoteServerCertificateValidationCallback方法中获得到期日期,并且无法从那里返回。是否有任何可能的方法获取证书到期日期到我的GetSMTPCert方法,然后将其返回到我的主要方法?
有关其他方式获取SMTP服务器的SSL证书过期日期的建议也是受欢迎的。
答
好吧我解决了这个问题,通过将类型字符串“CertificateDaysLeft”的公共静态字段添加到我的SMTPCert类。
namespace SMTPCert
{
public static string CertificateDaysLeft;
public static string GetSMTPCert(string ServerName)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
using (System.Net.Mail.SmtpClient S = new System.Net.Mail.SmtpClient(ServerName))
{
S.EnableSsl = true;
using (System.Net.Mail.MailMessage M = new System.Net.Mail.MailMessage("[email protected]", "[email protected]", "Test", "Test"))
{
try
{
S.Send(M);
string daysLeft = CertificateDaysLeft;
return daysLeft;
}
catch (Exception)
{
string daysLeft = CertificateDaysLeft;
return daysLeft;
}
}
}
}
private static bool RemoteServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
DateTime ExpirDate = Convert.ToDateTime(certificate.GetExpirationDateString());
string DaysLeft = Convert.ToString((ExpirDate - DateTime.Today).Days);
CertificateDaysLeft = DaysLeft;
Console.WriteLine(certificate);
return true;
}
}
}
我猜我想有点太复杂了。