What I want to do:
I want to send E-Mails over an email server authenticated via OAUTH2. To achive that I implemented a C# .NET 8.0 project to send emails via a Microsoft 365 mail server using MailKit authenticated with OAUTH2.
What I tried / Which guides I followed:
I am using MailKit / MimeKit and followed this guide: [1]
I registered my application and configured the API permissions as you can see here:
To test it I used this snippet: [2]
I entered all credentials needed but I get the following Error (1).
I also found this YT-Video from CodeWrecks [3]
I followed the steps and the “Generate code flow link” works perfectly [5:16 in the video]
The “Test Imap” returns ???? Result of accessing imap/smtp with XOAUTH2 for [email protected] IMAP Login OK
But the “Send mail with SMTP and actual token returned Error (2).
Here is the code i tried to run with my valid credentials:
var confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithAuthority ($"https://login.microsoftonline.com/{tenantId}/v2.0")
.WithClientSecret(clientSecret)
.Build();
var scopes = new string[] {
"https://ps.outlook.com/.default",
"https://outlook.office365.com/.default"
};
var authToken = await confidentialClientApplication
.AcquireTokenForClient(scopes)
.ExecuteAsync();
// the authToken is filled with an AccessToken
var oauth2 = new SaslMechanismOAuth2 (accountEmailAddress, authToken.AccessToken);
using var smtpclient = new MailKit.Net.Smtp.SmtpClient(new ProtocolLogger(Console.OpenStandardOutput()));
// works
await smtpclient.ConnectAsync(
"smtp.office365.com",
587,
SecureSocketOptions.Auto);
// throws the error
await smtpclient.AuthenticateAsync(oauth2);
var message = new MimeMessage();
message.From.Add(MailboxAddress.Parse(from));
message.To.Add(new MailboxAddress(to, to));
message.Subject = "Test email - Please no reply";
message.Body = new TextPart(MimeKit.Text.TextFormat.Html)
{
Text = "Test sending email"
};
await smtpclient.SendAsync(message)
Errors:
(1) 535: 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information.
(2) Result of accessing imap/smtp with XOAUTH2 for [email protected]: Error sending Mail: MailKit.Security.AuthenticationException: 535: 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information
Why do I need SmtpClientAuthentication when I try to authenticate via OAuth2?
Could it be that SMTP-Auth is used as a fallback when OAUTH2 does not work and that is the reason for this error?