.netgmailimapmailkit

How to use MailKit with Google after May 30, 2022?


Up to this point I was happily connecting to my Gmail account with a method similar to this:

public async Task<IEnumerable<MimeMessage>> GetMessagesAsync()
{
    using var imapClient = new MailKit.Net.Imap.ImapClient();
    var secureSocketOptions = SecureSocketOptions.Auto;
    if (useSsl) secureSocketOptions = SecureSocketOptions.SslOnConnect;
    await imapClient.ConnectAsync(host, port, secureSocketOptions);

    await imapClient.AuthenticateAsync(login, password);

    await imapClient.Inbox.OpenAsync(FolderAccess.ReadOnly);

    var uids = await imapClient.Inbox.SearchAsync(SearchQuery.All);

    var messages = new List<MimeMessage>();
    foreach (var uid in uids)
        messages.Add(await imapClient.Inbox.GetMessageAsync(uid));

    imapClient.Disconnect(true);

    return messages;
}

Since May 30, 2022, this is no longer possible as support for 'less secure apps' was disabled:

To help keep your account secure, from May 30, 2022, ​​Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

How do I use Mailkit with Gmail now?


Solution

  • The deactivation of less secure applications prevents you from being able to log in directly with your username and password, but it does not prevent you from being able to generate a specific password for your application. Now, instead of logging in with your google password, you'll log in with a password that you generate for your specific app.

    The solution is simple and does not require much change:

    1. Turn on 2-Step Verification in your google account. This step is required as Google only allows generating passwords for apps on accounts that have 2-Step Verification enabled.

    2. Go to generate apps password (https://myaccount.google.com/apppasswords) and generate a password for your app.

      enter image description here

    3. Simply use your gmail username (your_mail@gmail.com) and the password generated in your c# application.