Thursday, February 20, 2025

mail sending using app registration and MSGraph

Create an App registrion with permissions:





$TenantId = "XXXXXXXXXXXXXXX"

$ClientId = "XXXXXXXXXXXXXXXXX" $ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX" $Body = @{ grant_type = "client_credentials" client_id = $ClientId client_secret = $ClientSecret scope = "https://graph.microsoft.com/.default" } $TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" ` -Method POST ` -ContentType "application/x-www-form-urlencoded" ` -Body $Body $AccessToken = $TokenResponse.access_token # Write-Output $AccessToken # Variables $Recipient = "john@gmail.com" # Replace with the recipient's email address $Subject = "Test Email from PowerShell" $Body = @{ Message = @{ Subject = $Subject Body = @{ ContentType = "Text" Content = "This is a test email sent using Microsoft Graph API and PowerShell." } ToRecipients = @(@{ EmailAddress = @{ Address = $Recipient } }) } SaveToSentItems = "true" } # Convert body to JSON $BodyJson = $Body | ConvertTo-Json -Depth 10 -Compress # Define headers for the API request $Headers = @{ "Authorization" = "Bearer $AccessToken" "Content-Type" = "application/json" } $Response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/no-reply@source.domain.com/sendMail" ` -Headers $Headers ` -Method POST ` -Body $BodyJson Write-Output "Email sent successfully!"

No comments:

Post a Comment