【问题标题】:How to create JSON payload using power shell Foreach loop如何使用 power shell Foreach 循环创建 JSON 有效负载
【发布时间】:2020-04-03 12:10:59
【问题描述】:

要求:通过发送网格帐户(Send Grid API)附加多个附件发送电子邮件。

描述:我能够创建 json 有效负载,并能够通过硬编码附件值来发送单个附件。我正在打开窗口表单对话框并能够选择需要附加的单个/多个文件。

代码:

          $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{ 
    InitialDirectory = [Environment]::GetFolderPath('Desktop') 
    #Filter = 'Documents (*.docx)|*.docx|SpreadSheet (*.xlsx)|*.xlsx'
    Filter           = 'All files (*.*)| *.*'
    Title            = 'Select  File(s) for Attachments'
    Multiselect      = $true
  }
  $FileBrowser.ShowDialog() | Out-Null
  $FilesEncodedContents = New-Object System.Collections.ArrayList
  $AttachmentsjsonRequest = @()
  if ($FileBrowser.FileNames.Count -gt 0) {
    foreach ($file in $FileBrowser.FileNames) {
      [string] $filerawContent = $null
      $filedetails = Get-Item $file
      $filerawContent = ConvertToBase64Encode $file

      if (![string]::IsNullOrWhitespace($filerawContent)) {
        $FilesEncodedContents.Add($filerawContent) 
          $obj = New-Object -TypeName PSObject
        $obj | Add-Member -MemberType NoteProperty -Name filename -Value (Get-Item $file).Name
        $obj | Add-Member -MemberType NoteProperty -Name content_id -Value (Get-Item $file).Name
        $obj | Add-Member -MemberType NoteProperty -Name content -Value $filerawContent
        $obj | Add-Member -MemberType NoteProperty -Name disposition -Value 'attachment'
        $AttachmentsjsonRequest += $obj
      }
    }
  }    
      Write-Host "$AttachmentsjsonRequest"

          $headers = @{ }
$headers.Add("Authorization", "Bearer $ApiKey")
$headers.Add("Content-Type", "application/json")
$jsonRequest = [ordered]@{
  personalizations = @(@{to = @(@{email = "$MailTo" })
      subject               = "$Subject" 
    })
  from             = @{email = "no-reply@xxx.com" }
  attachments      = "$AttachmentsjsonRequest"
  content          = @( @{ type = "text/plain"
      value            = "Sample Mail Body" 
    }
  )
} | ConvertTo-Json -Depth 100
           Write-Host $jsonRequest | ConvertTo-Json -Depth 100
       Invoke-RestMethod   -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers 
    $headers -Body $jsonRequest

Write-Host "Mail Sent"



      #region ConvertToBase64Encode
     Function ConvertToBase64Encode([string] $AttachementFile) {
     [string] $fileContentEncoded = $null
     if (Test-Path $AttachementFile -PathType leaf) {
$fileContent = get-content $AttachementFile
$fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$fileContentEncoded | set-content ((Get-Item -Path $AttachementFile).Name + ".b64")
   }
   else {
     $fileContentEncoded = $null
     Write-Host "File : $FileAttachment not exists,skipping and continue to add if any other 
   attachments  uploaded"
    }
    return $fileContentEncoded

     }
      #endregion

问题: [已更新]

尝试上传单个或多个附件后出现以下错误

  {"errors":[{"message":"Invalid type. Expected: array, given: string.","field":"attachments","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments"}]} .

参考链接: 发送网格 API 文档:

https://sendgrid.com/docs/API_Reference/api_v3.html

【问题讨论】:

  • 尝试使用数组对象。更新了代码,仍然出现错误。还有什么问题?
  • 您没有将 $jsonRequest 变量传递给 Invoke-RestMethod 的 -Body 参数:Invoke-RestMethod -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers $headers -Body $jsonRequest
  • @Zachafer,抱歉,在代码出现之前更新代码时似乎遗漏了它。但如果我们尝试使用更新的代码,我们在调用 API 后会出现错误,除非我们按照我回答的解决方案修改代码.
  • 如何在to部分添加多个邮箱地址?
  • @Pradeep 创建一个数组并添加电子邮件并分配。个性化 = @(@{to = @($validMails) $validMails 是数组类型

标签: json powershell email sendgrid sendgrid-api-v3


【解决方案1】:

我的建议是考虑不将 JSON 构建为文本,首先构建一个 Powshell 对象,然后使用 ConvertTo-Json 将其转换为 JSON。

使用此方法,数组将在 JSON 中正确表示。不要忘记设置-DEPTH 参数。

attachments array[object] An array of objects in which you can specify any attachments you want to include.

因此,在您的 Powershell 对象中,attachments 将成为 @()

具有内容、类型、文件名、处置、conten_id 属性的对象。

【讨论】:

  • 我也尝试过使用对象,因为我对 powershell 很陌生,我无法做到。能否请您提供一些代码或参考链接。
【解决方案2】:

我在后期深入了解了错误细节。它在 JSON 有效负载“附件”字段中给出提示,显示为字符串而不是数组对象,通过将 @(@()) 添加到 @(@()) 到 attachmentjsonrequest 来修复 >“$jsonrequest”变量。

简而言之: "attachmentjsonrequest 是一个数组对象,需要使用 @() 转换为 JSON 负载强>

感谢您建议使用数组对象。

       attachments      = @(@($AttachmentsjsonRequest))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-22
    • 2017-01-29
    • 1970-01-01
    • 2019-12-16
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多