如何使用图形API和python3根据发件人、发送日期和主题检索电子邮件

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

我正在编写一个简单的python脚本,它可以帮助我根据以下参数sentdatetime, sender or from address and subject检索office365用户邮箱中的电子邮件。
到目前为止,我可以使用msal获得访问令牌,但是email API调用不起作用。我得到了一个error 401。从图形资源管理器中查询起作用,但是在脚本中它不起作用。
我的应用程序注册被分配了邮件的应用程序权限,我选择了邮件权限下的所有内容。
以下是我目前的剧本,我做错了什么。

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

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

下面是错误

b0zn9rqh

b0zn9rqh1#

您的作用域不适用于此Graph API

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

将为您提供一个受众为www.example.com的令牌outlook.office365.com,该令牌适用于IMAP4,但不适用于Graph,因为Graph要求受众为https://graph.microsoft.com
所以图表的作用域应该是

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

您可以使用www.example.com检查令牌jwt.io并进行验证。

相关问题