Microsoft Graph API 是一个 RESTful web API,它允许开发者访问 Microsoft 365 服务中的数据。通过这个API,开发者可以读取、写入和管理电子邮件、日历、联系人等信息。
以下是一个使用 Python 和 Microsoft Graph API 检索电子邮件的示例代码:
import requests
import json
# 设置你的应用程序凭据
client_id = 'your-client-id'
client_secret = 'your-client-secret'
tenant_id = 'your-tenant-id'
# 获取访问令牌
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
token_data = {
'client_id': client_id,
'scope': 'https://graph.microsoft.com/.default',
'client_secret': client_secret,
'grant_type': 'client_credentials'
}
response = requests.post(token_url, data=token_data)
access_token = response.json().get('access_token')
# 使用访问令牌检索电子邮件
email_url = 'https://graph.microsoft.com/v1.0/me/messages?$filter=from/emailAddress/address eq \'example@example.com\''
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
response = requests.get(email_url, headers=headers)
emails = response.json().get('value')
# 打印电子邮件信息
for email in emails:
print(f"Subject: {email['subject']}")
print(f"From: {email['from']['emailAddress']['name']} <{email['from']['emailAddress']['address']}>")
print(f"Body: {email['body']['content']}")
print('-' * 80)
通过以上信息,你应该能够理解如何使用 Microsoft Graph API 检索电子邮件,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云