Search code examples
c#azureoauth-2.0microsoft-graph-apioffice365api

Sending email OAuth2 Office365


I have an application's clientId, tenantId, and secret from registering an app in Microsoft Azure services.

I managed to get a token, from here: https://login.microsoftonline.com/{tenantId} I also figured out that the scope should be this: https://graph.microsoft.com/.default

I tried to send an email with https://graph.microsoft.com/v1.0/me/sendMail endPoint, but I finally realized he /me is not good for me (I tried to replace the "me" with the email address that I want to send the email from, but that also not working).

Please give me help how should I use this API? I just want to send an email with OAuth2.


Solution

  • I registered one Azure AD application and granted Mail.Send permission of Application type as below:

    enter image description here

    Now, I generated access token using client credentials flow via Postman with below parameters:

    POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
    grant_type:client_credentials
    client_id: appId
    client_secret: secret 
    scope: https://graph.microsoft.com/.default
    

    Response:

    enter image description here

    You can decode the above token in jwt.ms and check whether it has roles claim with Mail.Send permission:

    enter image description here

    When I used this token to send mail with below API call via Postman, I got response like this:

     POST https://graph.microsoft.com/v1.0/users/userId/sendMail
     {
      "message": {
        "subject": "Invitation for Diwali Event",
        "body": {
          "contentType": "Text",
          "content": "Hi Sri! We welcome you to attend Diwali event on 2 November 2023"
        },
        "toRecipients": [
          {
            "emailAddress": {
              "address": "sri@xxxxxxxxx.onmicrosoft.com"
            }
          }
        ]
      },
      "saveToSentItems": "true"
    }
    

    Response:

    enter image description here

    To confirm that, I checked the same in user's Sent Items where mail sent successfully as below:

    enter image description here

    In your case, "Access is denied. Check credentials and try again" error occurs if you granted Mail.Send permission of Delegated type for client credentials flow.

    To resolve the error, make sure to grant Mail.Send permission of Application type. Refer this SO thread that I previously answered.