In a UWP application, I am trying to send an email via an HTTP REST call to Microsoft.Graph, at the URL “https://graph.microsoft.com/v1.0/me/sendMail”.
For this application, I have Mail.Send permission (Send mail as a user). For the call, we C# code is:
using (HttpClient client = new HttpClient())
{
client. DefaultRequestHeaders.Add(“Authorization”, "Bearer " + token);
HttpResponseMessage response = await client. PostAsync(url, content);
}
According to the documentation (https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=http), the JSON sent is:
{
“Body”: {
“Content”: “My message”,
“ContentType”: “HTML”
},
“Subject”: “simple message”,
“From”: {
“EmailAddress”: {
“Address”: [Redacted]@[Redacted]
}
},
“ToRecipients”: [{
“EmailAddress”: {
“Address”: [Redacted]@[Redacted]
}
}],
“HasAttachments”: false,
“Importance”: “Low”
}
The response received is:
StatusCode: 400, ReasonPhrase: ‘Bad Request’
I tried removing the “From” from the JSON and that doesn’t fix the problem.
It’s surprising that this doesn’t work, because in the same environment going through the Microsoft.Graph Nuget package and through the code:
await graphClient.Me.SendMail(message, true). Request(). PostAsync();
Sending emails works perfectly!
I tried the URL "https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/sendMail" but it doesn't work any better!
Surprisingly, in the same environment I tried to use the Microsoft.Graph nuget package and do:
Microsoft.Graph.Me.SendMail.SendMailPostRequestBody SMPRB = new Microsoft.Graph.Me.SendMail.SendMailPostRequestBody();
await graphClient.Me.SendMail.PostAsync(SMPRB);
And it works perfectly!
Best regards.
I was hoping emailing worked!
That's right ! The right solution is to add "message" and not put a "from" sender!
Sample :
{
"message": {
"body": {
"content": "my message",
"contentType": "HTML"
},
"subject": "my subject",
"toRecipients": [{
"emailAddress": {
"address": "recipient@outlook.com"
}
}],
"hasAttachments": false,
"importance": "Normal"
}
}