Unable to send email to multiple recipients in powershell using sendgrid API
I am testing send mail feature in PowerShell using sendgrid API key. The problem is when I give one email in the To list, test email comes successfully but when I add multiple email ids it gives "Cannot convert value to type System.String" error. Can anyone please help :(
function Send-EmailWithSendGrid {
Param
(
[Parameter(Mandatory=$true)]
[string] $From,
[Parameter(Mandatory=$true)]
[String] $To,
[Parameter(Mandatory=$true)]
[string] $ApiKey,
[Parameter(Mandatory=$true)]
[string] $Subject,
[Parameter(Mandatory=$true)]
[string] $Body
)
$headers = @{}
$headers.Add("Authorization","Bearer $apiKey")
$headers.Add("Content-Type", "application/json")
$jsonRequest = [ordered]@{
personalizations= @(@{to = @(@{email = "$To"})
subject = "$SubJect" })
from = @{email = "$From"}
content = @( @{ type = "text/html"
value = "$Body" }
)} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers $headers -Body $jsonRequest
}
$MailParams = @{
From = "[email protected]"
To = "[email protected]" , "[email protected]"
APIKEY = "putapikeyhere"
Subject = "TEST MAIL"
Body = $HTMLmessage
}
Send-EmailWithSendGrid @MailParams
I have tried multiple combinations like below but couldn't able to solve this problem.
To = "[email protected]" , "[email protected]"
or
To = "[email protected] , [email protected]"
or
To = " ; "
Error:
Send-EmailWithSendGrid : Cannot process argument transformation on parameter 'To'. Cannot convert value to type System.String.
At line:82 char:24
+ Send-EmailWithSendGrid @MailParams
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Send-EmailWithSendGrid], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Send-EmailWithSendGrid
Not sure if this has already been answered, but I was able to resolve this by using the parameter type as Array and using the FOREACH loop inside the function. (See below).
function Send-EmailWithSendGrid {
Param
(
[Parameter(Mandatory=$true)]
[string] $From,
[Parameter(Mandatory=$true)]
[String[]] $To,
[Parameter(Mandatory=$true)]
[string] $ApiKey,
[Parameter(Mandatory=$true)]
[string] $Subject,
[Parameter(Mandatory=$true)]
[string] $Body
)
$headers = @{}
$headers.Add("Authorization","Bearer $apiKey")
$headers.Add("Content-Type", "application/json")
foreach($t in $To){
$jsonRequest = [ordered]@{
personalizations= @(@{to = @(@{email = "$t"})
subject = "$SubJect" })
from = @{email = "$From"}
content = @( @{ type = "text/html"
value = "$Body" }
)} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers $headers -Body $jsonRequest
}
}
$From = "[email protected]"
$To = @("[email protected]" , "[email protected]")
$APIKEY = "putapikeyhere"
$Subject = "TEST MAIL"
$Body = $HTMLmessage
Send-EmailWithSendGrid -from $From -to $To -ApiKey $APIKEY -Body $Body -Subject $Subject