smtp.net-coremailkit.net-core-1.1

Weird Issue in dotnet core website using MailKit to send email


I just inherited a website from a vendor and going through the bugs and source code for the website.

The application is built on dotnet core 1.1 and uses Mailkit to send emails via SMTP thorugh our corporate proxy.

The issue is that the mail send feature behaves erratically in sending emails. Most of the times I debug the send method it errors out. We use the Authentication Required Flag and pass the userId and Password to MailKit Authenticate Method

StackTrace message

AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful

at MailKit.Net.Smtp.SmtpClient.Authenticate(Encoding encoding, ICredentials credentials, CancellationToken cancellationToken) at MailKit.MailService.Authenticate(String userName, String password, CancellationToken cancellationToken) at Rules.Emailer.SendNotification.Send(String to, String from, String subject, String body) in C:\Workspace\G\Rules\Emailer\SendNotification.cs:line 94 at G.Rules.Emailer.UserNotifications.ResetPassword(String

Code snippet

using (var client = new SmtpClient())
{
    client.Connect(EmailConfiguration.SmtpServer, EmailConfiguration.SmtpPort, EmailConfiguration.UseSsl);

    if (EmailConfiguration.RequiresAuthentication)
    {
        client.Authenticate(EmailConfiguration.Username, EmailConfiguration.Password);
    }

    //TODO: Only Send if PROD
    client.Send(message);
    client.Disconnect(true);
}

return true;
}

Solution

  • To NTLM connection, you can try that:

    await client.ConnectAsync(SmtpServer.SenderServer, SmtpServer.Port).ConfigureAwait(false);
    
    if (client.AuthenticationMechanisms.Contains("NTLM"))
    {
        var ntlm = new SaslMechanismNtlm(SmtpServer.UserName, SmtpServer.Password);
        await client.AuthenticateAsync(ntlm).ConfigureAwait(false);
    }
    else
    {
        await client.AuthenticateAsync(SmtpServer.UserName, SmtpServer.Password).ConfigureAwait(false);
    }