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 = "myuser@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