Home > Software engineering >  How to filter emails based on received date using microsoft graph api with python
How to filter emails based on received date using microsoft graph api with python

Time:01-23

I'm working on a python script to retrieve emails based on receiveddatetime. When i run my script i get the error below.

enter image description here

Below is my whole script.

import msal
import json
import requests

def get_access_token():
    tenantID = 'yyy'
    authority = 'https://login.microsoftonline.com/'   tenantID
    clientID = 'xxx'
    clientSecret = 'xxx'
    scope = ['https://graph.microsoft.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
# received 2023-01-22T21:13:24Z
date_received = '2023-01-22T21:13:24Z'
mail_subject = 'Test Mail'
mail_sender = '[email protected]'
mailuser = '[email protected]'

# Construct the URL for the Microsoft Graph API
url = "https://graph.microsoft.com/v1.0/users/{}/Messages?$filter=(ReceivedDateTime ge '{}')&$select=subject,from".format(mailuser, date_received)

# 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)

I tried to modify the api call like below, but still i get the same error. What am i doing wrong here?

url = "https://graph.microsoft.com/v1.0/users/{}/Messages?$filter=ReceivedDateTime ge '{}'&$select=subject,from".format(mailuser, date_received)

CodePudding user response:

Don't use single quotes when you want to filter messages by ReceivedDateTime in $filter=(ReceivedDateTime ge '{}'). Also parenthesis are not mandatory.

This should work:

url = "https://graph.microsoft.com/v1.0/users/{}/Messages?$filter=ReceivedDateTime ge {}&$select=subject,from".format(mailuser, date_received)
  • Related