sendEmail gives 405 error when used with application permission.

Copper Contributor

I'm making a Java application to send Mail as any user in a Microsoft tenant, with Graph APIs, so I'm using the client credentials flow (no login, automatic send). I've registered an app in Azure AD giving the following application permissions (not delegated), checking out the admin consent for every item:

Mail.Send
Mail.ReadWrite
User.Read.All

This is my code in Java:

String user = "/users/<my user id or my user principal name>";
   
    UserRequestBuilder defaultUser = new UserRequestBuilder(graphClient.getServiceRoot() + user, graphClient, null);
   
    //graphClient.me()
    defaultUser
        .sendMail(UserSendMailParameterSet
            .newBuilder()
            .withMessage(message)
            .withSaveToSentItems(saveToSentItems)
            .build())
        .buildRequest()
        .post();
I can't use the "me" target (me() method) because this is client credentials flow, so there isn't a logged user. I need to specify the sender in this way: /users/{id | userPrincipalName}/sendMail.

This is how the call in Postman is composed:

Method: POST

URL:

.https://graph.microsoft.com/v1.0/users/{my user id or my user principal name}/sendMail
AUTHORIZATION:

Bearer Token (my access token)
HEADERS:

Content-Type: application/json
BODY(JSON):

    {
      "message": {
        "subject": "Meet for lunch?",
        "body": {
          "contentType": "Text",
          "content": "The new cafeteria is open."
        },
        "toRecipients": [
          {
            "emailAddress": {
              "address": "email address removed for privacy reasons"
            }
          }
        ]
      }
    }
That's the response from the server (in both Postman and Java app):

STATUS: 405: Method Not Allowed

BODY:

{
    "error": {
        "code": "Request_BadRequest",
        "message": "Specified HTTP method is not allowed for the request target.",
        "innerError": {
            "date": "2022-08-05T07:17:34",
            "request-id": "XXXXXXXX-6075-4d13-83ed-XXXXXXXXXXXX",
            "client-request-id": "XXXXXXXX-6075-4d13-83ed-XXXXXXXXXXXX"
        }
    }
} 

0 Replies