Office 365 smtp OAUTH2 granting access token but when i try to send email get the error 535: 5.7.3 Authentication unsuccessful

Balasubramanian Ramanathan 5 Reputation points
2024-05-07T11:20:56.2233333+00:00

I followed the procedure mentioned in https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md (Web Services section) and configured everything correctly. But when i try to send sample email with mailkit smtpclient with the granted accesstoken i get the error 535: 5.7.3 Authentication unsuccessful

Here is the code i am using

// Office 365 SMTP settings

using MailKit.Net.Smtp;

using MailKit.Security;

using Microsoft.Identity.Client;

string smtpServer = "smtp.office365.com";

int portNumber = 587;

// Office 365 credentials

string clientId = "xxxxx";

string tenantId = "xxxxxxxxx";

string clientSecret = "xxxxxxxxxx";

// Sender and recipient email addresses

string from = "******@xx.com";

string to = "******@xx.com";

string[] scopes = { "https://graph.microsoft.com/.default" };

string authority = $"https://login.microsoftonline.com/{tenantId}/v2.0";

var app = ConfidentialClientApplicationBuilder.Create(clientId)

.WithClientSecret(clientSecret)

.WithAuthority(new Uri(authority))

.Build();

var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();

string accessToken = result.AccessToken;

using (var client = new SmtpClient())

{

var oauth2smtp = new SaslMechanismOAuth2(from, accessToken);

await client.ConnectAsync(smtpServer, portNumber, SecureSocketOptions.StartTls);

await client.AuthenticateAsync(oauth2smtp);

var message = new MimeKit.MimeMessage();

message.From.Add(new MimeKit.MailboxAddress("from", from));

message.To.Add(new MimeKit.MailboxAddress("to", to));

message.Subject = "Test email from C# using MailKit";

message.Body = new MimeKit.TextPart("plain")

{

Text = "This is a test email sent from C# using MailKit with OAuth2 authentication."

};

await client.SendAsync(message);

await client.DisconnectAsync(true);

}

Thank in advance for the help

Microsoft 365 and Office | Development | Other
Microsoft 365 and Office | Install, redeem, activate | For business | Windows
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Balasubramanian Ramanathan 5 Reputation points
    2024-05-07T12:39:36.75+00:00

    Able to solve it by changing the scopes to

    string[] scopes = { "https://outlook.office365.com/.default" };
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.