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"));
// client.DefaultRequestHeaders.Add("ContentType", "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
};
// var requestContent = new StringContent(JsonConvert.SerializeObject(email), Encoding.UTF8, "application/json");
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;