Как исправить «Удаленный сертификат недействителен в соответствии с процедурой проверки»

Я собираюсь попытаться отправить электронную почту через Mailkit, но столкнулся с проблемами из-за ошибки «System.Security.Authentication.AuthenticationException», которая означает «Удаленный сертификат недействителен в соответствии с процедурой проверки» (перевод с датского) Мой почтовый сервер использует SSL TLS и TLS поддерживают версии 1.2 и 1.3. мой код выглядит следующим образом: я не надеюсь, что это слишком много кода, но я не знаю, где улучшить код, чтобы он мог правильно обрабатывать SSL :-(

Ошибка возникает в строке "client.Connect("servername", 587, true);"

Итак, мой вопрос: как избежать этого сообщения об ошибке через Mailkit?

public void SendMail(string AFromMailAdr, string AFromName, string AToMailAdr, string AToName, string ASubject, string ABody)
{
    MimeMessage message = new MimeMessage();
    ...
    using (var client = new MailKit.Net.Smtp.SmtpClient())
    {
        client.Timeout = 30000;
        client.Connect("servername", 587, true);
        client.Authenticate("Username", "password");
        client.Send(message);
        client.Disconnect(true);
    }
}

До сих пор я много гуглил, не найдя правильного ответа, поэтому прошу здесь, на SO.

🤔 А знаете ли вы, что...
C# позволяет создавать приложения для разных платформ, включая Windows, Linux и macOS, с использованием .NET Core и .NET 5+.


65
1

Ответ:

Решено

Чтобы быть справедливым, основная проблема должна быть проверена/исправлена.

Вы можете контролировать, как MailKit выполняет проверку сертификата сервера, используя a ServerCertificateValidationCallback.

В целях отладки вы можете return true; в функции обратного вызова.

Код из документации MailKit:

using (var client = new MailKit.Net.Smtp.SmtpClient())
{
    // Set our custom SSL certificate validation callback.
    client.ServerCertificateValidationCallback = MySslCertificateValidationCallback;

    client.Timeout = 30000;
    client.Connect("servername", 587, true);
    client.Authenticate("Username", "password");
    client.Send(message);
    client.Disconnect(true);
}

    static bool MySslCertificateValidationCallback (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        // If there are no errors, then everything went smoothly.
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        // Note: MailKit will always pass the host name string as the `sender` argument.
        var host = (string) sender;

        if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) {
            // This means that the remote certificate is unavailable. Notify the user and return false.
            Console.WriteLine ("The SSL certificate was not available for {0}", host);
            return false;
        }

        if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) {
            // This means that the server's SSL certificate did not match the host name that we are trying to connect to.
            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;
        }

        // The only other errors left are chain errors.
        Console.WriteLine ("The SSL certificate for the server could not be validated for the following reasons:");

        // The first element's certificate will be the server's SSL certificate (and will match the `certificate` argument)
        // while the last element in the chain will typically either be the Root Certificate Authority's certificate -or- it
        // will be a non-authoritative self-signed certificate that the server admin created. 
        foreach (var element in chain.ChainElements) {
            // Each element in the chain will have its own status list. If the status list is empty, it means that the
            // certificate itself did not contain any errors.
            if (element.ChainElementStatus.Length == 0)
                continue;

            Console.WriteLine ("\u2022 {0}", element.Certificate.Subject);
            foreach (var error in element.ChainElementStatus) {
                // `error.StatusInformation` contains a human-readable error string while `error.Status` is the corresponding enum value.
                Console.WriteLine ("\t\u2022 {0}", error.StatusInformation);
            }
        }

        return false;
    }