如何使用带有python的microsoft graph API根据接收日期过滤电子邮件

3yhwsihp  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(118)

我正在写一个python脚本来检索基于receiveddatetime的电子邮件。当我运行我的脚本时,我得到下面的错误。

以下是我的整个脚本。

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)

我试着像下面这样修改API调用,但是我仍然得到同样的错误。我在这里做错了什么?

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

wgeznvg71#

当你想在$filter=(ReceivedDateTime ge '{}')中按ReceivedDateTime过滤消息时,不要使用单引号。括号也不是强制性的。
这应该行得通:

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

相关问题