Microsoft图形 API,发送电子邮件响应:状态代码:401 原因短语:"未经授权"



我正在尝试使用Microsoft图形API发送电子邮件,并得到以下响应:

StatusCode: 401, ReasonPhrase: 'Unauthorized'...

我正在尝试找出我的代码是否有问题,或者用户帐户是否缺少权限。

下面是代码:

string accessToken = GetADToken();
string graphRequest = "https://graph.microsoft.com/v1.0/me/sendMail";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var email = new {
message = new {
subject = "test subject",
body = new {
contentType = "Text",
content = "The cafeteria is open"
},
toRecepients = new List<object> {
new {
emailAddress = new {
address = "test.user@emailprovider.com"
}
}
},
ccRecipients = new List<object> {
new {
emailAddress = new {
address = "test.user@emailprovider.com"
}
}
}
},
saveToSentItems = false
};
string requestContent = JsonConvert.SerializeObject(email);
var buffer = Encoding.UTF8.GetBytes(requestContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new System.Net
.Http.Headers.MediaTypeHeaderValue("application/json");
var response = client.PostAsync(graphRequest, byteContent).Result;
return response;

我将不胜感激一些帮助,让我的代码通过图形 API 发送电子邮件

如果您使用的是 MVC,则可以在以下代码中检查范围(Web.配置文件(

<add key="ida:GraphScopes" value="Mail.Send"/> 

如果您使用的是 NETCore,则可以在以下代码中检查范围(appsettings.json(

"GraphScopes": "Mail.Send"

我们建议您启动邮件发送示例:https://github.com/microsoftgraph/aspnet-connect-rest-sample

最新更新