Outlook API: Cannot access inbox. Status 401, although successfully authenticated

Uwe Weinreich 0 Reputation points
2024-01-08T16:28:39.7266667+00:00

I need a tiny script that reads my inbox. I have set up a Python script using the Outlook API. General authentication works fine with my user ID and the client secret of the app. A token is generated successfully.

But when trying to read the inbox I receive status code 401. Something must be wrong with the URL I use to try to access the folder, I suppose:

url = f"https://graph.microsoft.com/v1.0/users/{my User ID}/mailfolders/inbox/messages?$select=id,subject,from,toRecipients,receivedDateTime&$top=25&$orderby=receivedDateTime desc"
headers = { "Authorization": f"Bearer {token}", "Accept": "application/json", "Content-Type": "application/json" }
response = requests.get(url, headers=headers)

{my user ID} is the same that was also used as authority value when authenticating with msal.ConfidentialClientApplication. There it works fine

  • Do I need to modify the URL? And if so, how?
  • Or do I need to modify settings in my user account?
  • Or are there specific app setting I should look at in Entra Admin Center?
Outlook | Windows | Classic Outlook for Windows | For business
Microsoft Security | Microsoft Graph
{count} votes

2 answers

Sort by: Most helpful
  1. Vasil Michev 124.1K Reputation points MVP Volunteer Moderator
    2024-01-08T17:34:46.34+00:00

    Confidential clients authenticate via the client credentials flow (i.e. client secret or certificate), user IDs are not involved. If you are indeed authenticating via client credentials, and thus running in the application context, you need additional permissions in order to access any given mailbox. In particular, the Mail.Read or Mail.ReadBasic application permission would do.

    The URL seems fine, assuming you're passing the correct user ID. This should be the UPN of your user or its GUID. You cannot use other values, such as any of the email addresses assigned, unless it matches the UPN.

    1 person found this answer helpful.

  2. Uwe Weinreich 0 Reputation points
    2024-01-15T08:50:43.27+00:00

    The issue was solved. Additionally, I needed to set the App's access rules correctly. There was a major mistake. Thanks a lot, Vasil!


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.