PowerShell调用Graph API发送HTML邮件返回400 Bad Request错误如何解决
问题根因
你遇到的400错误和Graph API的HTML内容限制无关,完全是请求体JSON格式错误导致的,问题出在两处:
- 手动构造JSON时混用了PowerShell哈希表语法
@{,JSON不支持该写法 - 带大量换行、双引号的HTML变量直接嵌入JSON,没有做特殊字符转义,导致JSON格式非法
可行解决方案
优先使用PowerShell内置的ConvertTo-Json自动构造合法JSON,不要手动拼接,修正后的代码如下:
$MailSender = "user@domain.com" $reportBody = @" <!DOCTYPE html> <HTML> <head> <title>Distribution Groups Email Notification</title> <style> body { font-family:Verdana,Arial,sans-serif; background-color: white; color: #000000; } table { border: 0px; border-collapse: separate; padding: 3px; } tr, td, th { padding: 3px; } th { color: #FFFFFF; font-weight: bold; text-align: center; } h1,h2,h3,h4,h5 { color: #002C54; } </style></head><BODY> <h2 align="center">Distribution Groups Report</h2> <h4 align="center">9/13/2021 2:40:01 PM</h4> <br><table> <tr bgcolor="#325777"><th>Created On</th><th>Created By</th><th>DG Display Name</th><th>DG Email Address</th><th># Members</th></tr> <tr><td>09/13/2021 14:05:26</td><td>isaiah.hanson@domain.com</td><td>Isaiahstest2</td><td>Isaiahstest2@domain.com</td><td>0</td></tr> </table></BODY></HTML> "@ # 先构造PowerShell哈希表 $sendMailParams = @{ message = @{ subject = "Distribution Group Report" body = @{ contentType = "HTML" content = $reportBody } toRecipients = @( @{ emailAddress = @{ address = "user@domain.com" } } ) } saveToSentItems = $false } # 自动转成合法JSON,自动处理特殊字符转义 $BodyJsonsend = $sendMailParams | ConvertTo-Json -Depth 10 $URLsend = "https://graph.microsoft.com/v1.0/users/$MailSender/sendMail" # 后续调用Invoke-RestMethod/Invoke-WebRequest时传入$BodyJsonsend即可
额外优化建议
你原HTML里有多余的</font>闭合标签,没有对应的开启标签,删除即可,不影响接口调用但可以避免部分邮件客户端渲染异常。
内容的提问来源于stack exchange,提问作者Isaiah Hanson
相关产品推荐
相关产品推荐

