Oauth2 for SMTP.Send granting AccessToken but returns 535: 5.7.3 Authentication unsuccessful when used

Will Wilding 150 Reputation points
2023-02-07T00:43:54.4+00:00

Our application was updated late last year to support Oauth2 for obtaining (via IMAP) and sending (via SMTP) emails on behalf of outlook.com consumer accounts. (Edit: See responses below if experiencing the problem with Microsoft 365 accounts.)

We have both SAS and premise based deployments which were tested as able to send and receive in December 2022, but are now getting 5.7.3 Authentication unsuccessful when attempting to authenticate with the SMTP server. IMAP continues to work just fine.

Here's an example flow:

User is prompted for authorization:

https://login.microsoftonline.com:443/common/oauth2/v2.0/authorize?prompt=consent&response_type=code&state=59b234bd-fdc0-4905-8e57-bbd4b091cf4f&scope=https%3a%2f%2foutlook.office.com%2fSMTP.Send+https%3a%2f%2foutlook.office.com%2fIMAP.AccessAsUser.All+offline_access&access_type=offline&redirect_uri=http%3a%2f%2flocalhost%3a68%2fEmail%2foauth%2f&login_hint={outlook.com email address}&client_id={our registered + verified clientid}

The scopes are

https://outlook.office.com/SMTP.Send

https://outlook.office.com/IMAP.AccessAsUser.All

offline_access

We receive our callback after the user logs in and provides permission.

?code={access_code}&state=59b234bd-fdc0-4905-8e57-bbd4b091cf4f

Then call to exchange the access code for a token...

https://login.microsoftonline.com/common/oauth2/v2.0/token

client_id={client id}&code={access code}&redirect_uri=http%3a%2f%2flocalhost%3a68%2fEmail%2foauth%2f&grant_type=authorization_code

...and receive our access and refresh tokens in response.

{
  "token_type": "Bearer",
  "scope": "https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All",
  "expires_in": "3600",
  "ext_expires_in": "3600",
  "access_token": "{access_token}",
  "refresh_token": "{refresh_token}"
}

MailKit is then used to connect and authenticate to the IMAP server outlook.office365.com. No errors. New mail can be read from the user's inbox.

But attempting to authenticate the SMTP (again using MailKit) client results in "535: 5.7.3 Authentication unsuccessful"

The same SaSLMechanismOAuth2 with the account's email address and current access token are used for both.

Other notes:

  • Our Application ID / Client ID on Azure AD has been verified.
  • I haven't been able to identify any changes in our methodology since this was tested as working in December.
  • I tried some variations on the scope, such as including https://graph.microsoft.com/SMTP.Send but this made no difference.
  • I'd prefer not to use any separate Graph APIs for sending email as our product must communicate with other SMTP servers/providers
  • I'm aware that SMTP Authentication can still be used, but since we can no longer use basic authentication for IMAP or POP, I'd prefer not to store the user's credentials at all.
  • I added additional API permissions to our clientId but again no effect (screenshot below)

User's image

Microsoft 365
Microsoft 365
Formerly Office 365, is a line of subscription services offered by Microsoft which adds to and includes the Microsoft Office product line.
5,375 questions
Microsoft Exchange Online
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,661 questions
Microsoft Exchange Online Management
Microsoft Exchange Online Management
Microsoft Exchange Online: A Microsoft email and calendaring hosted service.Management: The act or process of organizing, handling, directing or controlling something.
4,657 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,657 questions
{count} votes

6 answers

Sort by: Most helpful
  1. Will Wilding 150 Reputation points
    2023-04-11T18:25:24.3566667+00:00

    The issue with sending on behalf of outlook.com consumer addresses appears to have been resolved.

    2 people found this answer helpful.

  2. Akshay-MSFT 17,891 Reputation points Microsoft Employee
    2023-02-15T09:05:24.5733333+00:00

    @Will Wilding

    Thanks for your time and patience. I was able to test this with Gmail and got authentication error as "SMTP AUTH" is disabled in your tenant, The issue was fixed after enabling Authenticated SMTP.

    In your tenant kindly validate the following :

    • If Authenticated SMTP is enabled for your impacted user (this setting does over ride tenant configuration)
    1. Navigate to https://admin.microsoft.com/Adminportal/Home?source=applauncher#/users
    2. Select the user you are testing this with.
    3. Ensure "Authenticated SMTP" is checked.User's image

    User's image

    User's image

    • If your authentication policy disables basic authentication for SMTP, clients cannot use the SMTP AUTH protocol even if you enable the settings outlined in this article. For more information, see Disable Basic authentication in Exchange Online.

    Thanks,

    Akshay Kaushik

    Please "Accept the answer", "Upvote" and share your feedback (Yes/No) if the suggestion works as per your business need. This will help us and others in the community as well.


  3. Armstrong Shi 5 Reputation points
    2023-02-21T01:51:45.3733333+00:00

    Hi there, I also have this issue. here are screenshots of my setup and sample code.

    AzurePortal_API_Permissions

    AzurePortal_SecurityDefaults_Disabled

    365AdminCenter_ActiveUser_Authenticated SMTP_Enabled

    ExchangeAdminCenter_MailFlowSettings_TurnOffSMTPAuth_Unchecked

    // acquire token
    var scopes = new[] { "https://outlook.office.com/.default" };
    var options = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };
    
    var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
    Azure.Core.TokenRequestContext tokenRequestContext = new Azure.Core.TokenRequestContext(scopes);
    Azure.Core.AccessToken accessToken = clientSecretCredential.GetToken(tokenRequestContext);
    
    // send email
    using (SmtpClient smtpClient = new SmtpClient())
    {
        smtpClient.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);
    
        // Exception: 535: 5.7.3 Authentication unsuccessful 
        // https://learn.microsoft.com/en-us/answers/questions/1168272/oauth2-for-smtp-send-granting-accesstoken-but-retu
        smtpClient.Authenticate(new SaslMechanismOAuth2(username, accessToken.Token));
    
        MimeMessage message = new MimeMessage();
        // to do: build message
        smtpClient.Send(message);
    
        smtpClient.Disconnect(true);
    }
    

  4. Enzo Tech 0 Reputation points
    2023-04-19T01:43:05.6466667+00:00

    Hello Any updates on this? When will Microsoft fix this issue?


  5. Enzo Tech 0 Reputation points
    2023-05-16T07:51:28.07+00:00

    Hi all, it seems there was a mystery fix happened on MS side. It is now working. :)
    Anyway, due to this issue I was able to produce a Test Tool written in Rust Programming Language just to test this workflow. https://github.com/LorenzoLeonardo/microsoft-smtp-xoauth2-test-tool

    0 comments No comments

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.