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 = "[email protected]"
}
}
},
ccRecipients = new List<object> {
new {
emailAddress = new {
address = "[email protected]"
}
}
}
},
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
accessToken. This will shed light on which permission scopes are actually getting applied. - Marc LaFleur