We received an inquiry from PlatOps regarding potential integration with our Exchange online. Due to our strict security protocols that prohibit non-secure authentication methods, I took the initiative to develop a script that utilizes MS Graph and Modern Auth for sending emails in a secure manner.
Step one is to create an app in Azure AD and allow this app to send emails on behalf of everyone (And then limit that with the application policy to a single user)
Then the limiting:
Step two is generating a client secret for this app:
Generate new Client Secret and link to key-vault | Microsoft Learn
And now the script itself:
Import-Module Microsoft.Graph.Authentication
$ApplicationId = "AppID"
$SecuredPassword = "ClientSecret"
$tenantID = "TenantID"
$from = "[email protected]"
$to = "[email protected]"
$body = @{
grant_type = "client_credentials";
client_id = $ApplicationId;
client_secret = $SecuredPassword;
scope = "https://graph.microsoft.com/.default";
}
$response = Invoke-RestMethod -Method Post -Uri https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token -Body $body
$accessToken = $response.access_token
$accessToken
Select-MgProfile -Name Beta
Connect-MgGraph -AccessToken $accessToken
Select-MgProfile v1.0
$body = @{
message = @{
subject = "My Microsoft Graph Test Email"
body = @{
contentType = "Text"
content = "Hello, this is a test email"
}
toRecipients = @(
@{
emailAddress = @{
address = "$to"
}
}
)
}
saveToSentItems = "false"
}
Send-MgUserMail -UserId $from -BodyParameter $body
References:
Connect To Microsoft Graph PowerShell With a Client Secret (ourcloudnetwork.com)
How to Send Emails Using Microsoft Graph PowerShell (ourcloudnetwork.com)