Read Email from Microsoft 365 via Microsoft Graph API

Raymond Raymond event 2021-10-18 visibility 13,851 comment 5
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

More from Kontext
comment Comments
M Manish Thakur

Manish access_time 16 days ago link more_vert

yes it was there 

Raymond Raymond

Raymond access_time 15 days ago link more_vert

Can you check if your client details are configured properly on Azure? For example, API permissions should include Email read permission. 20241205230302-image.png


Choose a Microsoft Graph authentication provider - Microsoft Graph | Microsoft Learn

M Manish Thakur

Manish access_time 16 days ago link more_vert

yes it was there 

M Manish Thakur

Manish access_time 18 days ago link more_vert

getting below error .. access token created successfully but when tryimng to read the mail from then its throwing exception all permission set correctly


{'error': {'code': 'OrganizationFromTenantGuidNotFound', 'message': "The tenant for tenant guid 'ce0215a9-53fd-47c2-8b2d-8aeb16e17519' does not exist.", 'innerError': {'oAuthEventOperationId': '229d0355-c6a1-46fe-b474-5e73ef36c000', 'oAuthEventcV': '2DG9qhTbCVYc4MS25GEWcw.1.1', 'errorUrl': 'https://aka.ms/autherrors#error-InvalidTenant', 'requestId': '4f846122-503a-4360-9c00-2ebdaff6f2f6', 'date': '2024-12-03T13:14:21'}}}

Administrator Administrator

Administrator access_time 16 days ago link more_vert

Did you check if the tenant id exist in Azure AD?

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts