You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell使用SendGrid发送带Excel附件的邮件时附件损坏如何解决?

你的附件损坏的核心原因是二进制文件转Base64的逻辑存在多余的编码转换步骤,即便你修改了Get-Content的编码参数,后续的UTF8字节转换逻辑仍然会破坏Excel二进制文件的原始结构,可按以下方案修改:

  1. 替换原有的附件转码逻辑,删除多余的UTF8编码转换步骤,直接将读取到的二进制字节转换为Base64字符串,同时适配不同PowerShell版本的读取参数:
    原错误转码代码:
#Convert File to Base64
$FileContent = get-content $FileNameWithFilePath
$ConvertToBytes = [System.Text.Encoding]::UTF8.GetBytes($FileContent)
$EncodedFile = [System.Convert]::ToBase64String($ConvertToBytes)

替换为:

# 读取二进制文件并直接转Base64
if ($PSVersionTable.PSVersion.Major -ge 7) {
    $FileBytes = Get-Content -Path $FileNameWithFilePath -AsByteStream -Raw
}
else {
    $FileBytes = Get-Content -Path $FileNameWithFilePath -Encoding Byte -Raw
}
$EncodedFile = [System.Convert]::ToBase64String($FileBytes)
  1. 你已经修改的application/vnd.openxmlformats-officedocument.spreadsheetml.sheet是XLSX文件的标准MIME类型,无需再调整。
  2. 可选校验步骤:你可以在本地先验证转码逻辑是否正确,将生成的$EncodedFile解码后写入新文件,对比新文件与原Excel文件的哈希值是否一致,确认转码过程没有损坏文件:
# 测试转码正确性
$decodedBytes = [System.Convert]::FromBase64String($EncodedFile)
[System.IO.File]::WriteAllBytes("C:\test\decoded_test.xlsx", $decodedBytes)

内容的提问来源于stack exchange,提问作者Milan Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:15:00