Share via

Java: Get mail as an app

WuWanning 0 Reputation points
2025-03-28T08:15:56.4666667+00:00
While using the msgraph-sdk-java to access mailbox by application only .
I can list all users.
When I try to list all mail by the below method ,


public static MessageCollectionResponse listMail(String userId) throws Exception {
    // /users/{id | userPrincipalName}/messages/{id}/attachments/{id}/$value
    if (_appClient == null) {
        throw new Exception("Graph has not been initialized for app-only auth");
    }
    //GET /users/{id | userPrincipalName}/messages
    return _appClient.users().byUserId(userId).messages().get(requestConfiguration -> {
        requestConfiguration.queryParameters.select = new String []{"sender", "subject"};
    });
}


 it response 401 .

Does this need to access with a user?


<dependency>
    <groupId>com.microsoft.graph</groupId>
    <artifactId>microsoft-graph</artifactId>
    <version>6.33.0</version>
</dependency>

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.11.0</version>
</dependency>


Microsoft Security | Microsoft Graph
0 comments No comments

1 answer

Sort by: Most helpful
  1. CarlZhao-MSFT 46,456 Reputation points
    2025-03-28T09:51:09.9766667+00:00

    Hi @WuWanning

    Please check the following:

    • Make sure the calling app has been assigned one of the Mail.ReadBasic.All, Mail.ReadWrite and Mail.Read application permissions and has been consented by the administrator.
    • Make sure you are requesting the access token in the context of the application only (client credentials flow).
    • Make sure the target user has a valid Microsoft 365 license and is not a guest user.
    • Make sure your administrator has not restricted the application permissions to specific Exchange Online mailboxes.

    Hope this helps.

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

    Was this answer helpful?


Your answer

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