Karel Křesťan
Karel Křesťan

Reputation: 469

Mailkit.Net hangs on smtpClient.ConnectAsync(), throws no exception until Task timeout

Recently I run into a problem in one of our older applications. All of a sudden, application stopped sending registration/reset password emails to it's users. After some debugging, I discovered that the cause is a strange behaviour of Mailkit SmtpClient class. Problem occurs in following code:

public async Task Execute(EmailMessage email)
{
    var mimeMessage = CreateMimeMessageFromEmailMessage(email);

    using var smtpClient = new SmtpClient();

    await smtpClient.ConnectAsync(Options.SmtpServer, Options.Port, MailKit.Security.SecureSocketOptions.None);
    await smtpClient.AuthenticateAsync(Options.Username, Options.Password);
    await smtpClient.SendAsync(mimeMessage);
    await smtpClient.DisconnectAsync(true);
}

Error occurs every time in ConnectAsync() method, hovewer, it throws no exception, just freeze in this method for some time (about a minute), then it just throws Task cancelled with nothing mailkit specific.

At first, I thought that address to server, port or security options might be wrong, but we are using the same settings (and the same code!) in some of our other applications and they seem to work fine. It should also not be caused by something in my PC/network configuration, as other developers also run into same error when working on this program. I also tried to use Options for different email, but the error remains.

Any idea how to find a cause of this error, how to debug the problem when no exception is thrown etc.?

Upvotes: 1

Views: 3677

Answers (1)

jstedfast
jstedfast

Reputation: 38528

According to your comments, the following line is failing when the port used is 465:

await smtpClient.ConnectAsync(Options.SmtpServer, Options.Port, MailKit.Security.SecureSocketOptions.None);

That's your problem. You are trying to use port 465 while also using SecureSocketOptions.None.

You need to use SecureSocketOptions.SslOnConnect with port 465.

Port 465 is the SSL-port, but you are telling MailKit to connect and treat it as if it was connecting to a plain-text port. Obviously, that won't work.

Upvotes: 7

Related Questions