JohnD91
JohnD91

Reputation: 583

Getting MailKit.Security.SslHandshakeException on my .NET 5.0 web API when trying send an email through Gmail SMTP

I'm trying to setup email alerts from my .NET core web api. I've created the following email service to test it.

I'm connecting to the gmail smtp server using the following details:

url:smtp.gmail.com
port: 465
ssl: true

And authenticating using my gmail address and password.

using MailKit.Net.Smtp;
using MimeKit;

public class EmailService
    {

        public SmtpClient ConnectSMTP() {
            SmtpClient client = new SmtpClient();
            //remove hard coding from this and place details in env settings
            client.Connect("smtp.gmail.com", 465, true);
            client.Authenticate("<EMAIL>", "<PASSWORD>");
            return client;
        }

        public void EmailTest(string toAddress)
        {
            MimeMessage msg = new MimeMessage();

            MailboxAddress from = new MailboxAddress("EzGig","[email protected]");
            msg.From.Add(from);

            MailboxAddress to = new MailboxAddress("EzGig User", toAddress);

            msg.Subject ="Test Email";

            BodyBuilder bodyBuilder = new BodyBuilder();

            bodyBuilder.TextBody = "This is a test email body";

            msg.Body = bodyBuilder.ToMessageBody();

            SmtpClient client = ConnectSMTP();
            client.Send(msg);
            client.Disconnect(true);
            client.Dispose();
        }
    }

When I try to call the EmailTest method from one of my controllers I'm getting the following error

MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.

The server's SSL certificate could not be validated for the following reasons:
• The server certificate has the following errors:
  • The revocation function was unable to check revocation for the certificate.

Upvotes: 1

Views: 1846

Answers (2)

Ms_Mariga
Ms_Mariga

Reputation: 31

I had the same issue. @jstedfast was correct but he forgot to mention one thing.

Ensure the client.CheckCertificateRevocation = false; comes before client.connect()

client.CheckCertificateRevocation = false;
client.connect();

Upvotes: 3

jstedfast
jstedfast

Reputation: 38538

Based on the error message, it probably means that the CRL server was down which would prevent the SslStream from checking revocation status of the server's SSL certificate.

You can disable CRL checks by setting client.CheckCertificateRevocation = false;

Upvotes: 1

Related Questions