In my Blazor server application, I want to use OAuth2 authentication instead of basic auth. Using Mailkit and .NET 8.0.
private async Task<string> CreateSmtpClientAndSendMailAsync()
{
_smtpClient = new SmtpClient();
try
{
_smtpClient.Connect(MySmtpHost, MySmtpPort, SecureSocketOptions.StartTls);
var confidentialClientApplicationBuilder = ConfidentialClientApplicationBuilder.Create("xx").WithClientSecret("xx").WithTenantId("xx").Build();
var scopes = new string[] { "/.default" };
var authToken = await confidentialClientApplicationBuilder.AcquireTokenForClient(scopes).ExecuteAsync();
SaslMechanismOAuth2 oAuth2 = new SaslMechanismOAuth2("xxxxx",authToken.AccessToken);
_smtpClient.Authenticate(oAuth2);
_smtpClient.Send(_mailMessage);
_smtpClient.Disconnect(true);
return Resource.mailSentSuccessfully;
}
catch (Exception ex)
{
// logging...
}
}
I successfully get an access token, but then authentication fails
(MailKit.Security.AuthenticationException: '535: 5.7.3 Authentication unsuccessful[...]')
In my Blazor server application, I want to use OAuth2 authentication instead of basic auth. Using Mailkit and .NET 8.0.
private async Task<string> CreateSmtpClientAndSendMailAsync()
{
_smtpClient = new SmtpClient();
try
{
_smtpClient.Connect(MySmtpHost, MySmtpPort, SecureSocketOptions.StartTls);
var confidentialClientApplicationBuilder = ConfidentialClientApplicationBuilder.Create("xx").WithClientSecret("xx").WithTenantId("xx").Build();
var scopes = new string[] { "https://outlook.office/.default" };
var authToken = await confidentialClientApplicationBuilder.AcquireTokenForClient(scopes).ExecuteAsync();
SaslMechanismOAuth2 oAuth2 = new SaslMechanismOAuth2("xxxxx",authToken.AccessToken);
_smtpClient.Authenticate(oAuth2);
_smtpClient.Send(_mailMessage);
_smtpClient.Disconnect(true);
return Resource.mailSentSuccessfully;
}
catch (Exception ex)
{
// logging...
}
}
I successfully get an access token, but then authentication fails
Share Improve this question edited Mar 26 at 8:35 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 26 at 8:32 bbWebDevbbWebDev 811 silver badge7 bronze badges(MailKit.Security.AuthenticationException: '535: 5.7.3 Authentication unsuccessful[...]')
1 Answer
Reset to default 0Make sure that your Outlook account is set up to allow SMTP authentication, and ensure you are passing the correct info for your auth.