首页 > 解决方案 > 来自PowerShell的Outlook rest-api返回誓言请求(401)

问题描述

我正在尝试从 Outlook 创建一个自动通知应用程序,我尝试使用 Outlook Rest API 来做到这一点。

现在我只是做一个简单的代码,但结果总是返回错误代码 401

我尝试将我的应用注册到我的 Azure 租户上的应用注册中。但没有运气,我也不明白下一步该怎么做......

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

$userName = << my username >>
$password = << my password >>

$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$password

$body = "{
 ""Subject"":""rest API test"",
 ""Importance"":""High"",
 ""Body"":{
 ""ContentType"":""HTML"",
 ""Content"":""test test 1 2 3""
 },
 ""ToRecipients"":[{
 ""Address"":""<< my recipients >>""
 }]
 }"

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

api的结果说:

{"error":{"code":"OAuthMissingForThisApiVersion","message":"Authentication for this API version requires OAuth."}}

这就是为什么我试图将我的应用程序注册到 azure 应用程序注册以获取我的令牌。

有谁知道如何解决这个问题?甚至一些教程向我展示如何设置应用程序注册,直到我可以将令牌获取到我的 powershell 应用程序。

问候,

标签: azurepowershelloauth-2.0outlookoutlook-restapi

解决方案


https://outlook.office.com/api/v1.0不支持基本身份验证,因为 OAuth 是推荐的身份验证机制,但您可以继续使用https://outlook.office365.com/api/v1.0如果您需要继续使用基本身份验证。

尝试以下类似的方法,它应该可以工作

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


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


$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""
  }
 }
 ]
 }}"  

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

希望能帮助到你。


推荐阅读