简体   繁体   中英

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.

在此处输入图像描述

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 = 'bernardberbell@gmail.com'
mailuser = 'bernardmwanza@bernardcomms.onmicrosoft.com'

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM