Securely sending emails from PowerShell scripts with modern authentication enforced
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:
POST: https://graph.microsoft.com/v1.0/users/[email protected]/sendMail 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