jacek_podwysocki
jacek_podwysocki

Reputation: 807

How to use Azure App to send email on users behalf?

I try to send an email on users behalf from Azure Web App using Open Graph. Email has to be sent using office365 mail server and should be saved in users Sent mailbox. Mentioned App can be accessed by authorized users only, authorization is performed with the use of below endpoint:

https://login.microsoftonline.com/{tennantid}/oauth2/authorize?response_type=code+id_token&redirect_uri={domain}.auth%2Flogin%2Faad%2Fcallback&client_id={clientId}&scope=openid+profile+email&response_mode=form_post

Once user logs in, I fetch access token for further requests to Open Graph:

https://login.microsoftonline.com/{tennantid}/oauth2/v2.0/token

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

Next, I post to sendMail endpoint:

https://graph.microsoft.com/v1.0/me/sendMail

and pass necessary parameters, as well as authorization Bearer {accessToken} header where accessToken was retrieved in previous step. This returns an error:

"code":"NoPermissionsInAccessToken","message":"The token contains no permissions, or permissions can not be understood."

As for permissions, app has delegated permissions set up for mail.send so that it can send emails on behalf of logged in user only. App does not ask user for permissions when logging in, ther are no consents presented.

I have no more ideas how to make it work after digging into documentations and spending there quite some time so any tip will be appreciated.

Upvotes: 0

Views: 2486

Answers (1)

Shiva Keshav Varma
Shiva Keshav Varma

Reputation: 3575

As you are using the Client Credential grant type you will be getting the App token and you need to have application token set for it.

The API doesn't know what is the meaning of /me here since its a client credential flow.

If you want to use client credential flow then to send mail you need to specify the call this way.

https://graph.microsoft.com/v1.0/users/{Userid/UPN}/sendMail

So please add Mail.Send Application permission in you App in Azure as shown in the below screenshot and then make the above call.

enter image description here

You can also verify whether you are have permissions or not by using your access token at JWT site.

Upvotes: 1

Related Questions