- Create function app (or other resource) that will be sending the mail.
- Create a managed identity to the resource.
- Run the following code to give the managed identity permission to send mail via Graph API:
Connect-Azaccount -AuthScope MicrosoftGraphEndpointResourceId
$ManagedIdentityId = 'faca44fa-870f-4a2b-a120-e38e2f71d9f3'
$PermissionName = "Mail.Send"
$GraphAppId = "00000003-0000-0000-c000-000000000000"
$ManagedIdentity = Get-AzADServicePrincipal -ObjectId $ManagedIdentityId
$GraphServicePrincipal = Get-AzADServicePrincipal -Filter "appId eq '$GraphAppId'"
$AppRole = $GraphServicePrincipal.AppRole | Where-Object { $_.Value -eq $PermissionName }
New-AzADServicePrincipalAppRoleAssignment -ServicePrincipalId $ManagedIdentity.Id -ResourceId $GraphServicePrincipal.Id -AppRoleId $AppRole.Id
This will give the identity permission to send mail as ALL mailboxes in the organization. To restrict this, a role assignment will be created in M365 between the identity, graph role and a resource scope. The resource scope is a scoped number of mailboxes.
- To connect to M365, download the Powershell module: Exchange Online Management module. Note that some of these commands are unavailable in powershell until you have connected to M365.
Connect-ExchangeOnline
New-ServicePrincipal -AppId 4e91ac94-b9bf-47e0-a11a-f342938b97a6 -ObjectId faca44fa-870f-4a2b-a120-e38e2f71d9f3 -DisplayName "MI-Mail Function"
Use application id and object id for the managed identity, in Entra. This will create a service principal in M365 that acts as a link between M365 and the identity in Entra ID.
- Now we need to create a management scope which acts as a filter for the mailboxes that should be included:
New-ManagementScope -Name "MySharedMailbox" -RecipientRestrictionFilter "UserPrincipalName -eq 'sharedmailbox@mydomain.com'"
- To connect the management scope to the Graph role, create a role assignment:
New-ManagementRoleAssignment -App 876e190f-e540-422c-8f15-3342b851acd3 -Role "Application Mail.Send" -CustomResourceScope "MySharedMailbox"
- Now verify that the identity only has access to send mail as the specific mailbox:
Test-ServicePrincipalAuthorization -Identity 4e91ac94-b9bf-47e0-a11a-f342938b97a6 -Resource MySharedMailbox
Instead of creating a role assignment to a management scope, an administrative unit och entra group can be used, see more at:
https://janbakker.tech/a-love-story-about-role-based-access-control-for-applications-in-exchange-online-managed-identities-entra-id-admin-units-and-graph-api/
