PowerShell使用SendGrid按指定结构发送邮件给多个动态收件人
SendGrid PowerShell函数多收件人改造方案
核心修改点
- 将原函数的收件人参数从单字符串类型调整为字符串数组,支持动态传入任意数量收件人
- 调整请求体中
personalizations.to字段的构造逻辑,匹配SendGrid API要求的多收件人格式 - 可选优化:新增附件存在性判断,避免无附件时调用报错
修改后完整函数代码
function Send-SendGridEmail { param( [Parameter(Mandatory = $true)] # 改这里:单字符串改为字符串数组,支持传入多个收件人 [String[]] $destEmailAddress, [Parameter(Mandatory = $true)] [String] $fromEmailAddress, [Parameter(Mandatory = $true)] [String] $subject, [Parameter(Mandatory = $false)] [string]$contentType = 'text/plain', [Parameter(Mandatory = $true)] [String] $contentBody, [parameter(Mandatory = $false)] [string]$FileName, [parameter(Mandatory = $false)] [string]$FileNameWithFilePath, [parameter(Mandatory = $false)] [string]$AttachementType ) <# .Synopsis Function to send email with SendGrid .Description A function to send a text or HTML based email This script provided as-is with no warranty. Test it before you trust it. .Parameter apiKey The SendGrid API key associated with your account .Parameter destEmailAddress The destination email address .Parameter fromEmailAddress The from email address .Parameter subject Email subject .Parameter type The content type, values are “text/plain” or “text/html”. "text/plain" set by default .Parameter content The content that you'd like to send .Example Send-SendGridEmail #> ############ 这里替换为你自己的SendGrid API Key #################### $apiKey = "你的SendGrid API密钥" $headers = @{ 'Authorization' = 'Bearer ' + $apiKey 'Content-Type' = 'application/json' } # 构造基础请求体 $body = @{ personalizations = @( @{ # 改这里:遍历所有收件人生成对应格式 to = @( $destEmailAddress | ForEach-Object { @{ email = $_ } } ) } ) from = @{ email = $fromEmailAddress } subject = $subject content = @( @{ type = $contentType value = $contentBody } ) } # 附件存在时才添加附件字段,避免无附件报错 if ($FileNameWithFilePath -and (Test-Path $FileNameWithFilePath)) { $base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($FileNameWithFilePath)) $body['attachments'] = @( @{ content=$base64string filename=$FileName type= $AttachementType disposition="attachment" } ) } 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 } }
调用示例
# 示例HTML正文 $htmlBody = @" <p>这是测试邮件正文</p> "@ $splat2 = @{ # 这里传入多个收件人,数组格式,支持动态生成 destEmailAddress = @('user1@example.com','user2@example.com','user3@example.com') fromEmailAddress = 'noreply@yourdomain.com' subject = '多收件人测试邮件' contentType = 'text/html' contentBody = $htmlBody FileName = "测试表格.xlsx" FileNameWithFilePath = "本地路径\excel.xlsx" AttachementType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" } Send-SendGridEmail @splat2
补充说明
如果需要暗送收件人(所有收件人看不到彼此地址),可以在personalizations节点下新增bcc字段,结构和to字段完全一致,传入暗送邮箱数组即可。
内容的提问来源于stack exchange,提问作者Milan Patel
相关产品推荐
相关产品推荐

