Read Email from Microsoft 365 via Microsoft Graph API

visibility 3,588 access_time 11 months ago languageEnglish
more_vert
Read Email from Microsoft 365 via Microsoft Graph API

In article Python: Send Email via Microsoft Graph API, I provided detailed steps to send email through msal package. In this article, I am going to show you how to read emails from Microsoft 365 via Microsoft Graph API. 

Setup permission

We need to add permissions for reading emails: Mail.ReadBasic.All or Mail.Read or Mail.ReadWrite (from least to most privileged). This permission allows you to send emails as any user. I will use Mail.Read permission so that we can read the mail body.

20211018121410-image.png

After adding the permission, make sure you also provide consent for the application.

20211018121505-image.png

Create the script to read emails

With user token and users ready, we can now use them to read emails in a Python client application.

Add a python script with the following content:

import msal
import requests
client_id = '***'
client_secret = '***'
tenant_id = '***'
authority = f"https://login.microsoftonline.com/{tenant_id}"
app = msal.ConfidentialClientApplication(
    client_id=client_id,
    client_credential=client_secret,
    authority=authority)
scopes = ["https://graph.microsoft.com/.default"]
result = None
result = app.acquire_token_silent(scopes, account=None)
if not result:
    print(
        "No suitable token exists in cache. Let's get a new one from Azure Active Directory.")
    result = app.acquire_token_for_client(scopes=scopes)
# if "access_token" in result:
# print("Access token is " + result["access_token"])
if "access_token" in result:
    userId = "***"
    endpoint = f'https://graph.microsoft.com/v1.0/users/{userId}/messages?$select=sender,subject'
    r = requests.get(endpoint,
                     headers={'Authorization': 'Bearer ' + result['access_token']})
    if r.ok:
        print('Retrieved emails successfully')
        data = r.json()
        for email in data['value']:
            print(email['subject'] + ' (' + email['sender']
                  ['emailAddress']['name'] + ')')
    else:
        print(r.json())
else:
    print(result.get("error"))
    print(result.get("error_description"))
    print(result.get("correlation_id"))

Remember to replace the highlighted variables accordingly. For user ID of email account, you can find it in Azure Active Directory or Microsoft 365 admin center. The script also adds a filter to return sender and subject properties only.

Run the script and you will see the output like the following screenshot:

20211018124319-image.png

References

Python: Send Email via Microsoft Graph API

List messages

copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts