Sending an email via an HTTP REST call to Microsoft.Graph comes out with an error

COM-ADD 5 Reputation points
2023-11-13T16:55:54.43+00:00

Hello,

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!

Best regards.

Microsoft Security | Microsoft Graph
{count} votes

2 answers

Sort by: Most helpful
  1. COM-ADD 5 Reputation points
    2023-11-26T16:44:29.56+00:00

    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": "******@outlook.com"
                }
            }],
            "hasAttachments": false,
            "importance": "Normal"
        }
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. Nadim Akhtar-MSFT 0 Reputation points Microsoft External Staff
    2023-11-28T22:40:41.02+00:00

    Hi @COM-ADD

    Yes, you are correct, the right solution is not to use 'from' within message.
    None of the examples in the official docs has this attribute-https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=http

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment"

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.