DEV Community

WilliamRamirez
WilliamRamirez

Posted on

Powershell script to call microsoft graph and send email using azure app registration

PowerShell script to call Microsoft Graph and send email using Azure app registration.

You will need to follow these steps:

-Register a new application in Azure and create a client secret for it. You will also need to assign the Mail.Send permission to the application in the API permissions section. You can refer to this article or this article for detailed instructions on how to do this.

-Connect to the Graph API using the client ID, client secret, and tenant ID of your application. You will need to get an access token and use it in the Authorization header of your requests. You can use the Invoke-RestMethod cmdlet to make HTTP requests to the Graph API. You can see an example of how to do this in this article.

-Send an email using the Graph API by specifying the sender, the subject, the body, and the recipients of the message. You can use the /users/{id}/sendMail endpoint to send an email on behalf of a user in your tenant. You will need to provide the message details in the JSON format in the body of your request. You can see an example of how to do this in this article.
Here is a sample PowerShell script that follows these steps and sends an email using the Graph API:

`

Replace these values with your own

$clientID = "yourClientID"
$clientSecret = "yourSecret"
$tenantID = "yourTenantID"
$mailSender = "sender@contoso.com"
$mailRecipient = "recipient@contoso.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 email

$URLsend = "https://graph.microsoft.com/v1.0/users/$mailSender/sendMail"
$BodyJsonsend = @"
{
"message": {
"subject": "Hello from Graph API",
"body": {
"contentType": "HTML",
"content": "This email is sent via Microsoft Graph API"
},
"toRecipients": [
{
"emailAddress": {
"address": "$mailRecipient"
}
}
]
},
"saveToSentItems": "false"
}
"@
Invoke-RestMethod -Method POST -Uri $URLsend -Headers $headers -Body $BodyJsonsend`

Here is a sample PowerShell script that follows these steps and inserts an item to a SharePoint list using the Graph API:

# Replace these values with your own
$clientID = "yourClientID"
$clientSecret = "yourSecret"
$tenantID = "yourTenantID"
$siteID = "yourSiteID"
$listID = "yourListID"

# 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"
}

# Insert an item to a SharePoint list
$apiUrl = "https://graph.microsoft.com/v1.0/sites/$siteID/lists/$listID/items"
$itemBody = @{
    fields = @{
        Title = "Test Item"
        Color = "Red"
        Weight = 10
    }
}
$payload = ConvertTo-Json $itemBody -Depth 5
Invoke-RestMethod -Method POST -Uri $apiUrl -Headers $headers -Body $payload
Enter fullscreen mode Exit fullscreen mode

PowerShell script that follows these steps and sends an email using the SharePoint SP.Utilities.Utility.SendEmail method:

# Replace these values with your own
$clientID = "yourClientID"
$clientSecret = "yourSecret"
$tenantID = "yourTenantID"
$siteID = "yourSiteID"
$mailSubject = "Hello from SharePoint"
$mailBody = "This email is sent via SharePoint SP.Utilities.Utility.SendEmail"
$mailTo = "recipient@contoso.com"
$mailFrom = "sender@contoso.com"

# Import the Microsoft.Graph module
Import-Module Microsoft.Graph

# Connect to Graph API using connect-mggraph
Connect-MgGraph -ClientSecretCredential $(New-Object Microsoft.Graph.Authentication.ClientSecretCredential -ArgumentList $tenantID, $clientID, $clientSecret)

# Get the request digest for the SharePoint site
$digestUrl = "https://graph.microsoft.com/v1.0/sites/$siteID/contextinfo"
$digestResponse = Invoke-MgGraphRequest -Method POST -Uri $digestUrl
$requestDigest = $digestResponse.FormDigestValue

# Send email using SharePoint SP.Utilities.Utility.SendEmail
$emailUrl = "https://graph.microsoft.com/v1.0/sites/$siteID/SP.Utilities.Utility.SendEmail"
$emailBody = @{
    properties = @{
        To = @($mailTo)
        Subject = $mailSubject
        Body = $mailBody
        From = $mailFrom
    }
}
$payload = ConvertTo-Json $emailBody -Depth 5
$headers = @{
    "X-RequestDigest" = $requestDigest
}
Invoke-MgGraphRequest -Method POST -Uri $emailUrl -Headers $headers -Body $payload

Enter fullscreen mode Exit fullscreen mode

Top comments (0)