 | MailServiceServerCertificateValidationCallback Property |
Get or set a callback function to validate the server certificate.
Namespace: MailKitAssembly: MailKit (in MailKit.dll) Version: 4.12.1
Syntax
RemarksGets or sets a callback function to validate the server certificate.
Exampleusing System;
using System.Net.Security;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using MimeKit;
using MailKit;
using MailKit.Security;
using MailKit.Net.Smtp;
namespace MailKit.Examples
{
public static class SslCertificateValidationExample
{
public static void SendMessage (MimeMessage message)
{
using (var client = new SmtpClient ()) {
client.ServerCertificateValidationCallback = MySslCertificateValidationCallback;
client.Connect ("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);
client.Authenticate ("username@gmail.com", "password");
client.Send (message);
client.Disconnect (true);
}
}
static bool MySslCertificateValidationCallback (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
var host = (string) sender;
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) {
Console.WriteLine ("The SSL certificate was not available for {0}", host);
return false;
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) {
var certificate2 = certificate as X509Certificate2;
var cn = certificate2 != null ? certificate2.GetNameInfo (X509NameType.SimpleName, false) : certificate.Subject;
Console.WriteLine ("The Common Name for the SSL certificate did not match {0}. Instead, it was {1}.", host, cn);
return false;
}
Console.WriteLine ("The SSL certificate for the server could not be validated for the following reasons:");
foreach (var element in chain.ChainElements) {
if (element.ChainElementStatus.Length == 0)
continue;
Console.WriteLine ("\u2022 {0}", element.Certificate.Subject);
foreach (var error in element.ChainElementStatus) {
Console.WriteLine ("\t\u2022 {0}", error.StatusInformation);
}
}
return false;
}
}
}
See Also