Unable to send email using Sendgrid - Using Powershell - (400) Bad Request.

Mohit Pathak 25 Reputation points
2023-09-06T11:27:47.85+00:00

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

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,329 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,126 Reputation points
    2023-09-08T07:34:08.5166667+00:00

    Hello there,

    This is a common 'error handling technique' where the developer catches the error and simply returns false, hiding any of the details or reasons for the failure.

    Check for duplicate addresses.

    One possible reason, as was in my case, one of the CC addresses was also the TO address. You see among many other things, SendGrid does not allow an email address to occur more than once in a send request, and if you happen to list an email recipient more than once in any of the TO,CC, or BCC lists SendGrid just sends back 400 BAD REQUEST.

    Hope this resolves your Query !!

    --If the reply is helpful, please Upvote and Accept it as an answer--

    0 comments No comments