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

使用PowerShell调用Graph API发送含&符号HTML邮件遇问题求助

问题描述

通过PowerShell调用Graph API发送HTML格式邮件时,遇到两个问题:

  1. 邮件正文href链接包含&符号,将其编码为%26后,收到的邮件中直接显示%26,点击链接返回404错误。
  2. 将请求的ContentType改为application/x-www-form-urlencoded后,邮件无法发送,报错:
Invoke-RestMethod: C:\Temp\imf4ah0e.3rb\fbb14734-21b4-4a83-a2ea-c774b3f7045a.ps1:67
Line |
  67 |  Invoke-RestMethod -Method POST -Uri $URLsend -Headers $headers -Body  …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | {"error":{"code":"RequestBodyRead","message":"A supported MIME type
     | could not be found that matches the content type of the response. None
     | of the supported type(s) 'Microsoft.OData.ODataMediaType,
     | Microsoft.OData.ODataMediaType,...' matches the content type
     | 'application/x-www-form-urlencoded'."

解决方案

问题根源分析

  • HTML结构拼接顺序错误:原代码把闭合标签放在最前面,导致邮件客户端无法正确解析HTML内容。
  • 错误使用ConvertTo-Json:将HTML字符串转为JSON格式后嵌入请求体,会导致邮件正文显示JSON文本而非HTML。
  • 请求ContentType错误:Graph API的sendMail接口仅接受JSON格式请求体,application/x-www-form-urlencoded不属于支持的媒体类型。
  • 链接转义方式错误:HTML中&的正确转义是&,而非%26(%26是URL编码,直接放在HTML中会被当作文本显示)。

修正后的代码

$htmlhead = "<html>
<head>
<style>
    body {
        font-family: 'verdana';font-size: 16px;
    }
    h1 {
        font-family: 'verdana';font-size: 18px;color: grey;
    }
    h2 {
        font-family: 'verdana';font-size: 18px;color: #2596be;
    }
    h3 {
        font-family: 'verdana';font-size: 16px;color: black;
    }
</style>
</head>"

$HtmlBody = "<body>
<h1>test</h1>
<p>request <a href=""https://www.somedomain/help?id=sc_cat_item&amp;sys_id=12345"">here.</a></p>
</body></html>"

# 按标准HTML结构拼接内容
$content = $htmlhead + $HtmlBody

$URLsend = "https://graph.microsoft.com/v1.0/users/$MailSender/sendMail"
$BodyJsonsend = @"
{
    "message": {
        "subject": "$mailSubject",
        "body": {
            "contentType": "HTML",
            "content": "$content"
        },
        "toRecipients": [
            $toJsonAddress
        ]
    },
    "saveToSentItems": false
}
"@

# 使用Graph API要求的JSON格式请求头
Invoke-RestMethod -Method POST -Uri $URLsend -Headers $headers -Body $BodyJsonsend -ContentType "application/json"

关键说明

  1. 严格遵循HTML结构规范:<html>标签内包含<head>(样式定义)和<body>(正文内容),确保邮件客户端正确渲染。
  2. 直接使用原始HTML字符串:无需对HTML内容做JSON转换,将其直接嵌入请求体的content字段即可(注意HTML内的双引号用""转义)。
  3. 恢复正确的请求ContentType:application/json是Graph APIsendMail接口唯一支持的请求体格式。
  4. 保留HTML标准转义:链接中的&用&amp;转义,邮件客户端会自动解析为&,保证链接参数正常传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:30:50