目前我已获得此代码以获取SMTP服务器的到期日期:
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("test@example.com", "test@example.com", "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更改为string,我可以将证书过期日期返回到我的main方法。 但目前我只能在RemoteServerCertificateValidationCallback方法中获取到期日期,并且无法从那里返回它。有没有办法让证书到期日期到我的GetSMTPCert方法,然后将其返回到我的main方法?
有关获取SMTP服务器SSL证书过期日期的其他方法的建议也欢迎。
答案 0 :(得分:0)
好的我通过添加string" 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("test@example.com", "test@example.com", "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;
}
}
}
我想我觉得有点太复杂了。