emailmicrosoft-graph-apismtpmicrosoft365

Microsoft 365 send mail via smtp with oauth2 token "Authentication unsuccessful"


I want to send emails via smtp with an oauth2 token. But I always get the following error message: "Authentication unsuccessful".

Steps I have done:

  1. I registered an app in the Azure panel.
  2. Added the following permissions:
  1. Enabled "Authenticated SMTP" in the Microsoft Admin Center for the specific user.

  2. I have recieved a token using the following endpoint: "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token" with the grant type: client_credentials. With the grant type client_credentials i can only use a default scope.

    and followed this tutorial: https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth#smtp-protocol-exchange

    And then authenticate myself, but got the following error message: "Authentication unsuccessful"


Solution

  • For sending mail via SMTP these permission are wrong

    https://graph.microsoft.com/SMTP.Send

    https://graph.microsoft.com/User.Read

    basically your token will have the wrong audience if you try to use them.

    Also

    Currently, Exchange Online doesn't support SMTP Oauth 2.0 client credential flow with non-interactive sign in. We are working on this, and it will be available by the end of 2023.

    ref https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth

    So what your trying to do with the client credentials flow won't work (until the end of the year), you can use the Delegate flow or switch to use the Graph API to send messages if you can which will be a better long term option

    Where can i find the permission https://outlook.office.com/SMTP.Send?

    If you follow the steps for POP and IMAP https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth#add-the-pop-and-imap-permissions-to-your-aad-application and use the "Office 365 Exchange Online" that will make sure you can request a Token with the correct audience.

    enter image description here