使用 Powershell 使用 REST API 发送电子邮件

send email using REST API using Powershell

是否可以通过 Powershell 使用 REST API 发送电子邮件?

我已经尝试使用 this reference 但我 运行 遇到了问题:

这也使用了旧版 API(我使用的是 V1.0)

我可以快速方便地阅读电子邮件(为我自己和代表)。它只是基于 Invoke-RestMethod -Uri "https://outlook.office365.com/api/v1.0/Users

的一行

这是我目前所拥有的,但它没有用..好像我得到通常的 Invoke-RestMethod 并不奇怪:

The remote server returned an error: (400) Bad Request.

$uri = "https://outlook.office365.com/api/v1.0/me/sendmail"


$UserName = "andrew.stevens@my.domain"
$Password = cat C:\MydomainCreds.txt | convertto-securestring
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password


$body = "{
 ""Subject"": ""This is a send test"",
 ""Importance"": ""High"",
 ""Body"": {
 ""ContentType"": ""HTML"",
 ""Content"": ""How about this for a surprise!""
 },
 ""ToRecipients"": [
 {
  ""Address"": ""mytestmailbox@anywhere.com""
 }
 ]
 }"



Invoke-RestMethod -Uri $uri -Method Post -Credential $cred -ContentType "application/json" -Body $Body

代表消息的JSON数据格式不正确。消息的根元素应该是 MessageRecipient 也不正确,它应该包含 EmailAddress 属性 即 EmailAddress类型。

下面是一个示例,供您参考:

$body = "{
""Message"":{
 ""Subject"": ""This is a send test"",
 ""Importance"": ""High"",
 ""Body"": {
 ""ContentType"": ""HTML"",
 ""Content"": ""How about this for a surprise!""
 },
 ""ToRecipients"": [
 {
 ""EmailAddress"":{
  ""Address"": ""mytestmailbox@anywhere.com""
  }
 }
 ]
 }}"

有关 Office 365 REST 的更多信息,请参阅下面的链接API:

Outlook Mail REST API reference

Resource reference for the Mail, Calendar, Contacts, and Task REST APIs