Home > Software engineering >  How to retrieve email based on sender, sent date and subject using graph api with python3
How to retrieve email based on sender, sent date and subject using graph api with python3

Time:01-23

I'm working on a simple python script to help me retrieve email in office365 user mailbox based on the following parameters, sentdatetime, sender or from address and subject.

As of current, am able to get the access token using msal, however the email api call does not work. I get an error 401. From graph explorer the query works however in the script it's not working.

My app registration is assigned application permission for mail, i selected everything under mail permissions. see below permissions enter image description here

Below is my script so far, what am i doing wrong.

import msal
import json
import requests

def get_access_token():
    tenantID = '9a13fbbcb90fa2'
    authority = 'https://login.microsoftonline.com/'   tenantID
    clientID = 'xxx'
    clientSecret = 'yyy'
    scope = ['https://outlook.office365.com/.default']
    app = msal.ConfidentialClientApplication(clientID, authority=authority, client_credential = clientSecret)
    access_token = app.acquire_token_for_client(scopes=scope)
    return access_token

# token block
access_token = get_access_token()
token = access_token['access_token']


# Set the parameters for the email search
date_sent = "2023-01-22T21:13:24Z"
mail_subject = "Test Mail"
sender = "[email protected]"
mailuser = "[email protected]"

# Construct the URL for the Microsoft Graph API
url = "https://graph.microsoft.com/v1.0/users/{}/mailFolders/Inbox/Messages?$select=id,sentDateTime,subject,from&$filter=contains(subject, '{}') and from/emailAddress/address eq '{}' and SentDateTime gt '{}'".format(mailuser, mail_subject, sender, date_sent)

# Set the headers for the API call
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

# Send the API request and get the response
response = requests.get(url, headers=headers)

print(response)

# # Parse the response as JSON
# data = json.loads(response.text)

# print(data)


Below is the error enter image description here

CodePudding user response:

Your scope is wrong for the Graph API this

scope = ['https://outlook.office365.com/.default']

Will give you a token that has an audience of outlook.office365.com which is okay for IMAP4 but not for the Graph which requires the audience to be https://graph.microsoft.com

so your scope for the graph should be

scope = ['https://graph.microsoft.com/.default']

You can check your token use jwt.io and verify it.

  • Related