I'm trying to send an email from my .Net 6 application from my office365 email account using following configuration following this

"EmailConfiguration": {
   "From": "XXXXXXXXXXX",
   "SmtpServer": "smtp.office365.com",
   "Port": 25, // tried port 587 also
   "Username": "XXXXXXXXX",
   "Password": "XXXXXXXX"
}

And this is my code to send the email:

using var client = new SmtpClient();
try
{
    client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, MailKit.Security.SecureSocketOptions.StartTls);
    //client.AuthenticationMechanisms.Remove("XOAUTH2");
    client.Authenticate(_emailConfig.UserName, _emailConfig.Password);

    client.Send(mailMessage);
}
catch
{
    //log an error message or throw an exception or both.
    throw;
}
finally
{
    client.Disconnect(true);
    client. Dispose();
}

But I'm getting this error on client.Authenticate call

MailKit.Security.AuthenticationException: '535: 5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy. Contact your administrator. [PN2PR01CA0027.INDPRD01.PROD.OUTLOOK.COM 2023-12-10T12:33:11.474Z 08DBF8259ECF3F85]'

We tried to check everything in the admin panel to see if the particular email account or user is locked but we found nothing like that.

I have enabled the Authenticated SMTP setting for that particular email account using the following

I tried to disable that setting also, but then I started getting an error for Authentication failure.

Can anybody guide me please to what could be wrong?

1

There are 1 best solutions below

3
Kupokev On

I ran into the same issue and found that you have to enable conditional access in Entra. This is NOT recommended by Microsoft, but it is the only way I have been able to get this to work correctly.

To do this:

  • Sign in to the Microsoft Entra admin center as at least a Security Administrator.
  • Browse to Identity > Overview > Properties.
  • Select Manage security defaults. (It's at the bottom of page)
  • Set Security defaults to Enabled.
  • Select Save.

The official Microsoft instructions to do this are here: https://learn.microsoft.com/en-us/entra/fundamentals/security-defaults

You also have to turn off multi-factor authentication for the user you are wanting to send emails as. There might be other ways around this part with app keys or something, but I am not 100% sure on that one. I am sure someone will pipe up here and mention it.