Microsoft Office 365 Outlook sending emails using OAuth2 Authentication

Alberto Mori 6 Reputation points
2021-08-13T13:29:27.727+00:00

Hi all,

I'm trying to build a deamon service which sends email using OAuth2 Authentication with Office 365.

We created the app on Azure and set all scopes and permissions (both to Graph section and Exchange Online section).

We're using MailKit as library. We successfully obtain an access token with the follow implementation:

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

var app = ConfidentialClientApplicationBuilder

.Create(client_id)

.WithTenantId(tenant)

.WithCertificate(certificate)

.Build();

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

return token;

But when we try to authenticate using the SmtpClient we receive an error 535: 5.7.3 Authentication unsuccessfull. The code we're using is the following:

var parser = await GetOfficeCredentialsServiceV1();

var office365User = "******@mydomain.onmicrosoft.com";

using (var client = new MailKit.Net.Smtp.SmtpClient())

{

client.ServerCertificateValidationCallback = OnValidateCertificate;

await client.ConnectAsync("smtp.office365.com", 587, SecureSocketOptions.StartTls);

var oauth2 = new SaslMechanismOAuth2(office365User, parser.AccessToken);

await client.AuthenticateAsync(oauth2); // ERROR

//.....

}

Using a personal account withthe following code we're not experiencing any error and the e-mails are sent correctly:

var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(options).Build();

var accounts = await app.GetAccountsAsync();

var scopes = new []

{

"user.read", "Mail.Read", "Mail.ReadBasic", "Mail.ReadWrite", "Mail.Send", "email",

"https://outlook.office.com/IMAP.AccessAsUser.All", "https://outlook.office.com/POP.AccessAsUser.All", "https://outlook.office.com/SMTP.Send"

};

var authToken = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())

.WithForceRefresh(true)

.ExecuteAsync();

Are we missing some configuration on the Azure App or something else?

Thank you

Outlook | Windows | Classic Outlook for Windows | For business
Exchange | Exchange Server | Management
Microsoft Security | Microsoft Graph
{count} vote

1 answer

Sort by: Most helpful
  1. Vasil Michev 119.7K Reputation points MVP Volunteer Moderator
    2021-08-13T17:37:38.853+00:00

    You don't need to use SmptClient, once you have the access token (with necessary permissions), use the /sendMail endpoint. Here's a recent article that walks you over the process: https://practical365.com/upgrade-powershell-scripts-sendmailmessage/


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.