Microsoft Graph API,发送电子邮件响应:StatusCode:401 ReasonPhrase:“未经授权”

时间:2018-09-05 09:40:34

标签: c# microsoft-graph

我正在尝试使用Microsoft Graph 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发送电子邮件

1 个答案:

答案 0 :(得分:0)

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

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

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

 "GraphScopes": "Mail.Send"

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