I am using the sendgrid module in Powershell to send out an email with an attachment and some plain text content body. However, I am constantly getting an error:
Send-SendGridEmail : Error with Invoke-RestMethod The remote server returned an error: (400) Bad Request.
The Attachment is a CSV file of size less than 10KB and being generated in a defined $csvpath on a daily basis after fetching data from the Active directory. The Body is plain text with few lines.
Any help would be highly appreciated:
Here is the code-
####### Function for Sending the Email using Sendgrid Starts Here ##############################
function Send-SendGridEmail {
param(
[Parameter(Mandatory = $true)]
[String] $destEmailAddress,
[Parameter(Mandatory = $true)]
[String] $subject,
[Parameter(Mandatory = $false)]
[string]$contentType = 'text/plain',
[Parameter(Mandatory = $true)]
[String] $contentBody,
[Parameter(Mandatory = $false)]
[String] $attachmentPath
)
############ Update with your SendGrid API Key and Verified Email Address ####################
$apiKey = "*************************"
$fromEmailAddress = "************"
$headers = @{
'Authorization' = 'Bearer ' + $apiKey
'Content-Type' = 'application/json'
}
$body = @{
personalizations = @(
@{
to = @(
@{
email = $destEmailAddress
}
)
}
)
from = @{
email = $fromEmailAddress
}
subject = $subject
content = @(
@{
type = $contentType
value = $contentBody
}
)
attachments = @(
@{
filename = $attachmentPath.Name
content = [System.IO.File]::ReadAllBytes($attachmentPath)
type = $attachmentPath.Extension
}
)
}
try {
$bodyJson = $body | ConvertTo-Json -Depth 4
}
catch {
$ErrorMessage = $_.Exception.message
write-error ('Error converting body to json ' + $ErrorMessage)
Break
}
try {
Invoke-RestMethod -Uri https://api.sendgrid.com/v3/mail/send -Method Post -Headers $headers -Body $bodyJson
}
catch {
$ErrorMessage = $_.Exception.message
write-error ('Error with Invoke-RestMethod ' + $ErrorMessage)
Break
}
}
# Examples, call the function using splat to pass in parameters:
# Sample code with plain text
$contentBody = "Hello Team,
Please find attached the list of users whose passwords are nearing expiration.
Thank you."
$splat = @{
destEmailAddress = '*****************'
subject = '*******************'
contentType = 'text/plain'
contentBody = $contentBody
attachmentPath = $csvPath
}
Send-SendGridEmail @splat