Powershell通过Graph API发送带有JSON正文的电子邮件

qyswt5oh  于 2023-04-30  发布在  Shell
关注(0)|答案(1)|浏览(138)

我尝试通过Graph API发送一封带有JSON正文的电子邮件,但我得到了HTTP 400错误的请求应答。尝试将contentType更改为Text,但也失败了。
嵌入json内容的正确方法是什么?
谢谢!

$content=$data | ConvertTo-Json

$URLsend = "https://graph.microsoft.com/v1.0/users/$sender/sendMail"
$BodyJsonsend = @"
                    {
                        "message": {
                          "subject": "$subject",
                          "body": {
                            "contentType": "application/json",
                            "content": "$content"
                          },
                          
                          "toRecipients": [
                            {
                              "emailAddress": {
                                "address": "$recipient"
                              }
                            }
                          ]
                          ,"attachments": [
                            {
                              "@odata.type": "#microsoft.graph.fileAttachment",
                              "name": "$FileName",
                              "contentType": "text/plain",
                              "contentBytes": "$base64string"
                            }
                          ]
                        },
                        "saveToSentItems": "false"
                      }
"@

Invoke-RestMethod -Method POST -Uri $URLsend -Headers $headers -Body $BodyJsonsend
sdnqo3pr

sdnqo3pr1#

下面是我遵循的一些东西,它给了我预期的结果。
出于演示目的,我使用了下面的JSON作为我的内容。

[{
    "name": "Project1",
    "description": "ABCD",
    "Last updatetime": "2022-04-11T03:29:25Z"
}, {
    "name": "Project2",
    "description": "EFGH",
    "Last updatetime": "2022-07-21T03:29:25Z"
}, {
    "name": "Project3",
    "description": "IJKL",
    "Last updatetime": "2022-11-10T03:29:25Z"
}]

下面是我用来发送邮件的完整脚本

$result = Get-Content result.json | ConvertFrom-Json

$BodyJsonsend = @{                                             
    "message"= @{
        "subject"= "Sample"
        "body"= @{
            "contentType"= "Text"
            "content"= $result
        }
        "toRecipients"=@(
        @{
            "emailAddress"= @{
                "email"= "<Your_Email_Id>"
                "name"= "<Name>"
            }
        }
        )
        "attachments"= @(
        @{
            "@odata.type"= "#microsoft.graph.fileAttachment"
            "name"= "$FileName"
            "contentType"= "application/json"
            "contentBytes"= "$base64string"
        }
        )
    }
 } | ConvertTo-Json -Depth 5

$BodyJsonsend

相关问题