I am trying to send an email using the Microsoft Graph API, and getting the following response:
StatusCode: 401, ReasonPhrase: 'Unauthorized'...
I'm trying to find out if there's something wrong with my code, or if the user account is lacking permissions.
Here is the code below:
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;
I would appreciate some help getting my code to send emails through the graph api
If you are using the MVC, you can check the scope in the following code(Web.Config file)
<add key="ida:GraphScopes" value="Mail.Send"/>
If you are using the NETCore, you can check the scope in the following code(appsettings.json)
"GraphScopes": "Mail.Send"
We suggest you start the mail send sample: https://github.com/microsoftgraph/aspnet-connect-rest-sample
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.