How to filter emails based on received date using microsoft graph api with python


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 = '' + tenantID
    clientID = 'xxx'
    clientSecret = 'xxx'
    scope = ['']
    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 = "{}/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)


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


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

url = "{}/Messages?$filter=ReceivedDateTime ge '{}'&$select=subject,from".format(mailuser, date_received)
Asked By: Bernietechy



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 = "{}/Messages?$filter=ReceivedDateTime ge {}&$select=subject,from".format(mailuser, date_received)
Answered By: user2250152