Here is my code, which has a comment to show where an exception occurs. I have a working implementation using Google's APIs directly, but I would rather use MailKit is it is an much friendlier API and I'd like to support other providers, not just Google.
internal async Task GmailTestAsync()
{
const string GMailAccount = "[email protected]";
var clientSecrets = new ClientSecrets
{
ClientId = "yourclientid",
ClientSecret = "yourclientsecret",
};
var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new FileDataStore("CredentialCacheFolder", false),
// Scopes = new[] { "https://mail.google.com/" }, maybe this works?
Scopes = new[] { GmailService.Scope.GmailReadonly, GmailService.Scope.GmailSend },
ClientSecrets = clientSecrets
});
var codeReceiver = new LocalServerCodeReceiver();
var authCode = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver);
var credential = await authCode.AuthorizeAsync(GMailAccount, CancellationToken.None);
if (credential.Token.IsExpired(SystemClock.Default))
await credential.RefreshTokenAsync(CancellationToken.None);
var oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken);
using (var client = new ImapClient())
{
await client.ConnectAsync("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);
// next line throws exception
await client.AuthenticateAsync(oauth2);
/*
MailKit.Security.AuthenticationException
HResult=0x80131500
Message=Authentication failed.
Source=MailKit
StackTrace:
at MailKit.Net.Imap.ImapClient.<AuthenticateAsync>d__103.MoveNext()
deleted...
*/
await client.DisconnectAsync(true);
}
}
Does MailKit support gmail and OAuth2? Is there some sample code somewhere? I have been following the code here: https://github.com/jstedfast/MailKit/blob/master/GMailOAuth2.md but I get a MailKit.Security.AuthenticationException at await client.AuthenticateAsync(oauth2);