microsoft-graph-apimicrosoft-graph-mail

Send mail via Microsoft Graph as Application (Any User)


We recently migrated from on premise exchange to Microsoft 365 and I'm wanting to turn on 2FA for all users (Enable security defaults). However this disables SMTP authentication which we have been using for sending mail from a distribution group address. (Not achievable via EWS as it doesn't have a physical mailbox)

From what I can see, the only method would be to set up a SMTP relay or send via Microsoft Graph.

I've tried going down the Microsoft Graph route, and here's what I've got so far.

  1. Create application in Azure Active Directory > App Registrations

  2. Add Mail.Send and User.Read.All (Application, not delegated) API Permissions and have granted Admin Consent.

  3. Request token using the following

  4. Once I have the token, Now I perform a request to send some mail

    • https://graph.microsoft.com/v1.0/users/{fromAddress}/sendMail
    • This works when fromAddress is the email address of the user that requested the token, however when I try to send from a different address it gives this error {"error":{"code":"ErrorAccessDenied","message":"Access is denied. Check credentials and try again."}}
    • I even tried adding the SendAs permission to the token user for the mailbox I was trying to send as, but this didn't make any difference. Regardless - I want to be able to send as any user without delegating permissions to each mailbox.

Glad of any help. Thanks!!


Solution

  • The behavior you are getting is expected because you are using delegated permissions - authorization code flow. This flow will not allow your app to send email as any user except the user that is signed in/"requested the token".

    In your case you can add the permissions as application permissions and then use Client Credentials flow with either secret or certificate(more secure). Your token request will look like the Get Access Token Section. Note that this means two things: