-
We used MailKit before, but now more and more service providers no longer support basic auth smtp, so we now need to inherit Oauth2 authentication method. We use Mailkit, but it keeps prompting me public async Task SendEmailAsync(string from, string to, string subject, string body)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(from, from));
message.To.Add(new MailboxAddress(to, to));
message.Subject = subject;
var bodyBuilder = new BodyBuilder { TextBody = body };
message.Body = bodyBuilder.ToMessageBody();
using (var client = new SmtpClient())
{
await client.ConnectAsync(smtpServer, 587, SecureSocketOptions.StartTls);
// from is my google gmail address
var oauth2 = new SaslMechanismOAuth2(from, this.AccessToken);
try
{
// 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 d2e1a72fcca58-71e774a2b2bsm4392811b3a.111 - gsmtp'
await client.AuthenticateAsync(oauth2, CancellationToken.None);
}
catch (Exception e)
{
await Console.Out.WriteLineAsync("Exception");
}
await client.SendAsync(message);
client.Disconnect(true);
}
} We mainly use it to send emails, I looked at https://github.com/jstedfast/MailKit/blob/master/GMailOAuth2.md#obtaining-an-oauth2-client-id-and-secret but didn't find a solution, I looked at this question, MailKit OAuth2 SMTP Office365 Send Mail But I still can't solve it. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
I don't see any code to verify that the access token is still valid (e.g. not stale). Is that being done somewhere else? Access tokens only last for a short period of time (a few hours? a day? depends on the service I think) |
Beta Was this translation helpful? Give feedback.
Those are all scopes, yes, but they are not the correct scopes which is why it is failing for you.
You need to use specifically "https://mail.google.com/" and ONLY that scope in order to authenticate via "legacy protocols" like SMTP.