The Send-MailMessage
cmdlet has been around for a couple of years and is mostly used to send email messages from PowerShell. But with the deprecation and security flaws of legacy authentication it’s time for a better option which actually supports modern authentication. For this purpose we can use the Microsoft Graph API and the Microsoft Graph PowerShell SDK. The best thing is that this solution works without any service account and does not need any exclusions from conditional access.
Microsoft Graph resource
To send a mail we simply specify the user account from which we want to send the email:
|
|
Create an app registration
Simply create a new app registration with the Mail.Send
permissions and use a certificate for the authentication.
We need to take additional steps to limit the permissions of the app registration. Otherwise the app can send mails on behalf of any user in your tenant. To limit the permissions we leverage exchange application access policies.
Connect to Exchange Online with the ExchangeOnlineManagement PowerShell module
Connect-ExchangeOnline
Create a mail enabled security group which contains all the accounts you want to send mails from
$restrictedGroup = New-DistributionGroup -Name "Mail service accounts" -Type "Security" -Members @("[email protected]")
Optionally hide the group from the address list
Set-DistributionGroup -Identity $restrictedGroup.Identity -HiddenFromAddressListsEnabled $true
Create the application access policy to only allow sending the app mails for the specified distribution group
1 2 3 4 5 6 7 8
$params = @{ AccessRight = "RestrictAccess" AppId = "1f5ffbea-f13f-4f1a-af63-258ce4344daf" PolicyScopeGroupId = $restrictedGroup.PrimarySmtpAddress Description = "Restrict app permissions to only allow access to service account" } New-ApplicationAccessPolicy @params
Wait a couple of minutes / hours for the policy to take effect
If you now try to send a mail from an account not within the referenced distribution list you get some kind of access denied message
Sending emails
To actually send an email message make sure to have the MSAL.PS
Module installed to acquire an access token.
Afterwards we can send an email message with the following PowerShell code:
|
|
And the result will look like this: