Send Mail with PowerShell and Microsoft Graph API

We all know that the Basic Authentication end is near and that I am a huge fan of Microsoft Graph API, so I am providing an example on “How to send an Email with PowerShell and Microsoft Graph API.”

To learn more from Microsoft GRAPH API, see my Blog Series:
Part 1 – Authentication and Azure App – Use Microsoft Graph API with PowerShell – Part 1 » TechGuy
Part 2 – Oauth2.0 – Use Microsoft Graph API with PowerShell – Part 2 » TechGuy
Part 3 – First Powershell Script to get a Teams Lis and Walkthrough – Use Microsoft Graph API with PowerShell – Part 3 » TechGuy
Part 4 – this one – Use Microsoft Graph API with PowerShell – Part 4 » TechGuy

API Reference and Permissions

The official documentation is here: Send mail – Microsoft Graph v1.0 | Microsoft Docs

Azure App Registration Rights:

  • Mail.Send

The Script

$clientID = "yourClientID"
$Clientsecret = "yourSecret"
$tenantID = "yourTenantID"

$MailSender = "michael.seidl@au2mator.com"

#Connect to GRAPH API
$tokenBody = @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    Client_Id     = $clientId
    Client_Secret = $clientSecret
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method POST -Body $tokenBody
$headers = @{
    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-type"  = "application/json"
}

#Send Mail    
$URLsend = "https://graph.microsoft.com/v1.0/users/$MailSender/sendMail"
$BodyJsonsend = @"
                    {
                        "message": {
                          "subject": "Hello World from Microsoft Graph API",
                          "body": {
                            "contentType": "HTML",
                            "content": "This Mail is sent via Microsoft <br>
                            GRAPH <br>
                            API<br>
                            
                            "
                          },
                          "toRecipients": [
                            {
                              "emailAddress": {
                                "address": "michael.seidl@au2mator.com"
                              }
                            }
                          ]
                        },
                        "saveToSentItems": "false"
                      }
"@

Invoke-RestMethod -Method POST -Uri $URLsend -Headers $headers -Body $BodyJsonsend

The Result

GitHub Repo

Here you can find the GitHub Repo: Seidlm/Microsoft-Graph-API-Examples (github.com)

Michael Seidl aka Techguy
au2mate everything

Leave a Comment

Your email address will not be published. Required fields are marked *

*

%d bloggers like this: