In the code below, if there is no access token file for [email protected], the GoogleWebAuthorizationBroker.AuthorizeAsync function creates one. That token is NOT detected as stale by "if (credential.Token.IsStale)", but the await client.AuthenticateAsync(oauth2); statement throws an exception that states: "MailKit.Security.AuthenticationException: '535: 5.7.8 Username and Password not accepted. For more information, go to 5.7.8 https://support.google.com/mail/?p=BadCredentials d82-20020a254f55000000b00dbd9eee633dsm2147601ybb.59 - gsmtp'"
Why would the token that is automatically provided result in an authentication failure? I have a previous working token that still works, even after being refreshed. It's just those now generated by GoogleWebAuthorizationBroker.AuthorizeAsync that don't work. I recently added a Google Drive API to the cloud project. Might that be the problem?
string[] scopes = new[] { "https://mail.google.com/" };
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromFile(OAuth2Credentials).Secrets,
scopes,
"[email protected]",
CancellationToken.None,
new FileDataStore(Directory.GetCurrentDirectory(), true));
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
if (credential != null)
{
if (credential.Token.IsStale)
await credential.RefreshTokenAsync(CancellationToken.None);
var oauth2 = new SaslMechanismOAuth2("[email protected]", credential.Token.AccessToken);
await client.AuthenticateAsync(oauth2);
}
await client.SendAsync(mailkitMimeMessage);
client.Disconnect(true);
}