Trying to Send Email through Graph API
Hello, I have constructed script to send email with attachments and body text (which is taken from txt file), but it still fails. Here is my script
$tenantId = "xxxxx"
$clientId = "xxxxxx"
$clientSecret = "$(O365Secret)"
$resource = "https://graph.microsoft.com"
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
# Obtain access token
$body = @{
client_id = $clientId
scope = "https://graph.microsoft.com/.default"
client_secret = $clientSecret
grant_type = "client_credentials"
}
$tokenResponse = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"
$accessToken = $tokenResponse.access_token
Write-Host "Access token obtained successfully"
$headers = @{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
}
$fromEmail = "[email protected]"
$toEmail = @("[email protected]", "[email protected]")
$subject = "$(Release.DefinitionName) - $(Get-Date -Format G)"
$bodyContent = Get-Content "$(System.DefaultWorkingDirectory)/xxxx/test-summary.txt" -Raw
# Serialize toRecipients
$recipients = $toEmail | ForEach-Object {
@{
emailAddress = @{
address = $_
}
}
} | ConvertTo-Json -Depth 10
# Compose the email properties
$emailProps = @{
message = @{
subject = $subject
body = @{
contentType = "Text"
content = $bodyContent
}
toRecipients = $recipients
}
saveToSentItems = $true
}
# Convert the entire emailProps to JSON
$emailJson = $emailProps | ConvertTo-Json -Depth 20 -Compress
if (-not $emailJson) {
Write-Error "JSON conversion produced an empty result."
exit
}
# Logging JSON for debugging
Write-Host "JSON Payload: $emailJson"
# Attempt to create the message
try {
$createMessageUrl = "$resource/v1.0/users/$fromEmail/messages"
$response = Invoke-RestMethod -Uri $createMessageUrl -Headers $headers -Method Post -Body $emailJson -Verbose
$messageId = $response.id
Write-Host "Message created successfully, ID: $messageId"
} catch {
Write-Error "Failed to create message: $_"
exit
}
# Upload attachments
$attachmentPaths = @(
"$(System.DefaultWorkingDirectory)/xxxxxxxxx/screenshots.zip",
"$(System.DefaultWorkingDirectory)/xxxxxxxxxx/test-summary.txt"
)
foreach ($path in $attachmentPaths) {
$fileBytes = [System.IO.File]::ReadAllBytes($path)
$fileContentEncoded = [System.Convert]::ToBase64String($fileBytes)
$attachmentProps = @{
"@odata.type" = "#microsoft.graph.fileAttachment"
name = [System.IO.Path]::GetFileName($path)
contentType = if ($path -like "*.zip") {"application/zip"} else {"text/plain"}
contentBytes = $fileContentEncoded
}
$attachmentJson = $attachmentProps | ConvertTo-Json -Depth 10
$uploadAttachmentUrl = "$resource/v1.0/users/$fromEmail/messages/$messageId/attachments"
Invoke-RestMethod -Uri $uploadAttachmentUrl -Headers $headers -Method Post -Body $attachmentJson
Write-Host "Attachment uploaded: $path"
}
# Send the email
$sendMailUrl = "$resource/v1.0/users/$fromEmail/messages/$messageId/send"
Invoke-RestMethod -Uri $sendMailUrl -Headers $headers -Method Post
Write-Host "Email sent successfully"
It fails on this line $emailJson = $emailProps | ConvertTo-Json -Depth 20 -Compress
with following log: Failed to create message: Failed to serialize to JSON: Cannot convert value to type System.String.
Any help would be appreciated!