Search code examples
gmailimapmailkit

How can I log into gmail IMAP using MailKit


I am trying to use MailKit (http://jstedfast.github.io/MailKit/docs/index.html) to log into Gmail using oAuth. I am able to log into Google API using a refreshed AuthToken, but when I try to use the refreshed token in MailKit, I get an error "Invalid Credentials"

Any clues?? Thanks, Jeff

Here is my code:

var secrets = new ClientSecrets()
{
    ClientId = "xxx-yyy.apps.googleusercontent.com",
    ClientSecret = "xyzSecret"
};

IAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = secrets,
            Scopes = new string[] { GmailService.Scope.GmailReadonly }
        });

var tokenResponse = flow.RefreshTokenAsync("", connection.RefreshToken, CancellationToken.None).Result;

using (var client = new MailKit.Net.Imap.ImapClient())
{
    var credentials = new NetworkCredential("emailtoconnect@gmail.com", tokenResponse.AccessToken);

    client.Connect("imap.gmail.com", 993, true, CancellationToken.None);
    try
    {
        client.Authenticate(credentials, CancellationToken.None);
    }
    catch (Exception ex)
    {
        
        throw;
    }
    

}

Solution

  • a clearer answer is that the scope was incorrect in the original code

    Scopes = new string[] { GmailService.Scope.GmailReadonly }
    

    needs to be

    Scopes = new string[] { GmailService.Scope.MailGoogleCom }
    

    in order to authenticate with imapi using a access token.