要将电子邮件附件从Microsoft Graph输出到磁盘上的文件中,你需要使用Microsoft Graph API来获取附件数据,并将其保存到本地文件系统中。以下是实现这一功能的基础概念、步骤和相关代码示例。
以下是一个使用Python和requests
库的示例代码:
import requests
import os
# 替换为你的客户端ID、客户端密钥和租户ID
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 = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': 'https://graph.microsoft.com/.default'
}
response = requests.post(token_url, data=token_data)
access_token = response.json().get('access_token')
if not access_token:
raise Exception("Failed to get access token")
# 获取邮件附件
email_id = 'your-email-id' # 替换为你的邮件ID
attachments_url = f'https://graph.microsoft.com/v1.0/me/messages/{email_id}/attachments'
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
response = requests.get(attachments_url, headers=headers)
attachments = response.json().get('value')
if not attachments:
raise Exception("No attachments found")
# 保存附件到磁盘
for attachment in attachments:
attachment_id = attachment['id']
attachment_name = attachment['name']
attachment_content_url = f'https://graph.microsoft.com/v1.0/me/messages/{email_id}/attachments/{attachment_id}/$value'
attachment_response = requests.get(attachment_content_url, headers=headers)
if attachment_response.status_code == 200:
with open(attachment_name, 'wb') as file:
file.write(attachment_response.content)
print(f'Saved {attachment_name} to disk')
else:
print(f'Failed to download {attachment_name}')
通过以上步骤和代码示例,你可以成功地将电子邮件附件从Microsoft Graph输出到磁盘上的文件中。