azuremicrosoft-graph-apiazure-web-app-servicemicrosoft-teamsmicrosoft-graph-mail

Microsoft Azure - sending emails with attachments


I am trying to send email with attachment (zip file). I managed to do so, but now my main problem is that I need code to get access_token, if I try GET request to get the code

https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize?client_id={clientId}&response_type=code&redirect_uri=https%3A%2F%2Flocalhost&response_mode=query&scope=offline_access%20Mail.ReadWrite%20Mail.send&state=111111

I get error saying that I need to sign up, that's a problem because I can't do so from my app.

I tried this method I found

{
   client_id: clientId,
   scope: 'https://graph.microsoft.com/.default',
   grant_type: 'client_credentials',
   client_secret: clientSecret,
}

and I get access token but I cannot send a mail with video with that access token as I get http 401, my app has these permissions Mail.ReadWrite, Mail.Send, User.Read


Solution

  • Note that, you need to grant permissions of Application type while generating access token using client credentials flow.

    I registered one Entra ID application and granted Mail.Send permission of Application type as below:

    enter image description here

    Now, I generated access token using client credentials flow 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 website and check roles claim for permissions:

    enter image description here

    Using this access token, you can send the mail with attachments successfully like this:

    POST https://graph.microsoft.com/v1.0/users/userId/sendMail
    Content-type: application/json
    
    {
      "message": {
        "subject": "Meet for lunch?",
        "body": {
          "contentType": "Text",
          "content": "The new cafeteria is open."
        },
        "toRecipients": [
          {
            "emailAddress": {
              "address": "user@mail.com"
            }
          }
        ],
        "attachments": [
          {
            "@odata.type": "#microsoft.graph.fileAttachment",
            "name": "attachment.txt",
            "contentType": "text/plain",
            "contentBytes": "SGVsbG8gV29ybGQh"
          }
        ]
      }
    }
    

    Response:

    enter image description here

    Reference: user: sendMail - Microsoft Graph v1.0 | Microsoft