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.
After adding the permission, make sure you also provide consent for the application.
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:
References
Python: Send Email via Microsoft Graph API
Can you check if your client details are configured properly on Azure? For example, API permissions should include Email read permission.
Choose a Microsoft Graph authentication provider - Microsoft Graph | Microsoft Learn
yes it was there
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'}}}
Did you check if the tenant id exist in Azure AD?
yes it was there