MimeKit azure gmail -> Authentication failed

821 views Asked by At

I am using MimeKit on aspnet core and everything is working locally but I get "Authentication failed" when I try to send email on a azure App Service.

I had to enable "Allow less secure apps" in order to get it to work locally.

This is the code I am using:

        using (var client = new SmtpClient())
        {
            await client.ConnectAsync("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);
            await client.AuthenticateAsync(_emailOptions.Username, _emailOptions.Password);
            await client.SendAsync(emailMessage);
            await client.DisconnectAsync(true);
        }

I have verified that _emailOptions.Username and _emailOptions.Password are correct by logging them in the exception thrown

        catch (Exception ex)
        {
            _log.LogError(new EventId(1), ex, "Username: '{0}', Password: '{1}'", _emailOptions.Username, _emailOptions.Password);
            throw;
        }

Do you have any ideas of how to troubleshoot this?

2

There are 2 answers

2
Fei Han On BEST ANSWER

I create a sample to send email using MimeKit and MailKit email framework, I find the code works fine on local and azure, if I provide valid username&password and allow less secure apps to access gmail account (the account not use 2-Step Verification).

using (var client = new SmtpClient())
{
    MimeMessage mes = new MimeMessage();
    mes.From.Add(new MailboxAddress("xxx", "[email protected]"));
    mes.To.Add(new MailboxAddress("xxx", "[email protected]"));
    mes.Subject = "hello";
    mes.Body = new TextPart("plain")
    {
        Text = @"hi,
        i'm azure! " + DateTime.Now.ToString()
    };

    client.Connect("smtp.gmail.com", 465, SecureSocketOptions.SslOnConnect);
    client.Authenticate("username here", "password here");
    client.Send(mes);
    client.Disconnect(true);
}

Please make sure if the account that you provide use 2-Step Verification or not enable less secure apps to access account. Besides, SendGrid is a cloud-based email service, you could try it.

0
Andrei Kapitanchik On

Thanks for direction. I had same problem with azure app and gmail. After reading this page I turned on two steps verification and generated app specific password. And that's solved my problem too.