Created
April 9, 2024 20:33
-
-
Save mvelazc0/02ee652da8b994fd9a4a032ac5a772a0 to your computer and use it in GitHub Desktop.
Read M365 emails using the Microsoft Grapi API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
tenant_id = '' | |
client_id = '' | |
client_secret = '' | |
scope = 'https://graph.microsoft.com/.default' | |
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token' | |
token_data = { | |
'grant_type': 'client_credentials', | |
'client_id': client_id, | |
'client_secret': client_secret, | |
'scope': scope | |
} | |
token_r = requests.post(token_url, data=token_data) | |
token = token_r.json().get('access_token') | |
user_email = '[email protected]' # The email address of the user whose emails you want to read | |
graph_endpoint = f'https://graph.microsoft.com/v1.0/users/{user_email}/mailFolders/Inbox/messages' | |
headers = { | |
'Authorization': f'Bearer {token}', | |
'Content-Type': 'application/json' | |
} | |
response = requests.get(graph_endpoint, headers=headers) | |
if response.status_code == 200: | |
messages = response.json().get('value', []) | |
for message in messages: | |
print(message.get('subject'), message.get('from')) | |
body_content = message.get('body', {}).get('content', '') | |
#print("Body:", body_content) | |
else: | |
print(f'Error: {response.status_code}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment