【问题标题】:Unable to send email to multiple recipients in powershell using sendgrid API无法使用 sendgrid API 在 Powershell 中向多个收件人发送电子邮件
【发布时间】:2020-05-20 16:36:34
【问题描述】:

我正在使用 sendgrid API 密钥在 PowerShell 中测试发送邮件功能。问题是,当我在收件人列表中提供一封电子邮件时,测试电子邮件成功发送,但是当我添加多个电子邮件 ID 时,它给出“无法将值转换为 System.String 类型”错误。谁能帮忙:(

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 = "abc@gmail.com"
                To =  "abc@gmail.com" , "cde@gmail.com"
            APIKEY = "putapikeyhere"
           Subject = "TEST MAIL"
              Body = $HTMLmessage
            }

Send-EmailWithSendGrid @MailParams

我尝试了以下多种组合,但无法解决此问题。

To = "abc@gmail.com" , "cde@gmail.com"

To = "abc@gmail.com , cde@gmail.com"

到 = " ; "

错误:

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

【问题讨论】:

标签: json powershell sendgrid


【解决方案1】:

不确定这是否已经得到解答,但我能够通过使用参数类型为 Array 并在函数内使用 FOREACH 循环来解决此问题。 (见下文)。

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 = "abc@gmail.com"
$To =  @("abc@gmail.com" , "cde@gmail.com")
$APIKEY = "putapikeyhere"
$Subject = "TEST MAIL"
$Body = $HTMLmessage

Send-EmailWithSendGrid -from $From -to $To -ApiKey $APIKEY -Body $Body -Subject $Subject

【讨论】:

  • 如果我没记错的话,这将在整个交易中执行 X 次,因为它正在逐一发送电子邮件。这与仅在 To 数组中提供多个 email= 不同。
【解决方案2】:

在为此搜索了很多之后,我终于不得不自己构建它。挑战在于 SendGrid 希望 To 数组采用格式

{
  "personalizations": [
    {
      "to": [
        {
          "email": "recipient1@example.com"
        },
        {
          "email": "recipient2@example.com"
        },
        {
          "email": "recipient3@example.com"
        }
      ],
      "subject": "YOUR SUBJECT LINE GOES HERE"
    }
  ]
}

所以我发现具有挑战性的是,在 Powershell 中,键值对(又名哈希表)不容易让键一遍又一遍地使用相同的名称。经过一番战斗,我使它起作用了。就是这样:

function Send-EmailWithSendGrid {
    #"text/plain" or "text/html"
    $body_type = "text/html"
    #Body
    $Body = "<h1>Hello, test email from Powershell using SendGrid</h1><p>Paragraph</p>"
    #From
    $From = "sender@example.com"
    #Subject
    $Subject = "Test Email"
    #Api Key
    $ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    #Array with recipients
    $recipients = "recipient1@example.com", "recipient2@example.com"
    #To needs to be an array which consists of hashtable with multiple "email" keys and the different reciepients as values
    $to_hashtable = [Collections.ArrayList]::new()
    #loop through the recipients array and add it to the $to_hashtable array
    foreach ($recipient in $recipients) {
        $null = $to_hashtable.Add( @{email=$recipient} )
    }    
    #Prepare the headers using a hashtable
    $headers = @{}
    $headers.Add("Authorization","Bearer $apiKey")
    $headers.Add("Content-Type", "application/json")
    #build the JSON body of the http request
    $jsonRequest = [ordered]@{
                            personalizations= @(@{to = @($to_hashtable) 
                                subject = "$SubJect" })
                                from = @{email = "$From"}
                                content = @( @{ type = $body_type
                                            value = "$Body" }
                                )} | ConvertTo-Json -Depth 10 
    #$jsonRequest
    #send the actual HTTP request to the SendGrid API
    Invoke-RestMethod -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers $headers -Body $jsonRequest
 
}

#Call the function
Send-EmailWithSendGrid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-12
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2012-05-18
    相关资源
    最近更新 更多