使用PowerShell调用Graph API发送含&符号HTML邮件遇问题求助
问题描述
通过PowerShell调用Graph API发送HTML格式邮件时,遇到两个问题:
- 邮件正文href链接包含
&符号,将其编码为%26后,收到的邮件中直接显示%26,点击链接返回404错误。 - 将请求的
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&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"
关键说明
- 严格遵循HTML结构规范:
<html>标签内包含<head>(样式定义)和<body>(正文内容),确保邮件客户端正确渲染。 - 直接使用原始HTML字符串:无需对HTML内容做JSON转换,将其直接嵌入请求体的
content字段即可(注意HTML内的双引号用""转义)。 - 恢复正确的请求
ContentType:application/json是Graph APIsendMail接口唯一支持的请求体格式。 - 保留HTML标准转义:链接中的
&用&转义,邮件客户端会自动解析为&,保证链接参数正常传递。
内容的提问来源于stack exchange,提问作者TechSavvy8102
相关产品推荐
相关产品推荐

