通过 OAuth2 获取 Outlook 邮箱收件箱的步骤如下。我们将使用 Microsoft Graph API,它是访问 Microsoft 365 服务(包括 Outlook 邮箱)的推荐方法。
1. 创建 Azure 应用程序
在 Azure 门户中,创建一个应用以获取必要的 OAuth2 凭据。
- 登录 Azure Portal。
- 注册应用程序:
- 转到 Azure Active Directory > 应用注册 > 新注册。
- 设置应用名称,例如
OutlookEmailReader
。 - 重定向 URI 使用
http://localhost
(本地开发测试)。
- API 权限:
- 添加 Microsoft Graph 的权限:
- 委托权限(Delegated permissions):
Mail.Read
。 - 如果需要访问用户数据而无需用户登录,还需配置 应用程序权限(Application permissions)。
- 委托权限(Delegated permissions):
- 添加 Microsoft Graph 的权限:
- 获取客户端 ID 和密钥:
- 记录应用的 客户端 ID。
- 在 证书和机密 中创建新的客户端密钥,并记录值。
2. 配置 Python 项目
安装必要库:
pip install requests msal
必要配置
将以下信息替换为你在 Azure 中的实际值:
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"
TENANT_ID = "your_tenant_id"
SCOPES = ["https://graph.microsoft.com/.default"] # 使用 Graph API 范围
REDIRECT_URI = "http://localhost"
3. 使用 MSAL 获取令牌
Microsoft 提供 MSAL(Microsoft Authentication Library)简化 OAuth2 流程。以下示例获取令牌并访问邮箱。
import requests
from msal import ConfidentialClientApplication
# 配置 OAuth2 客户端
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"
TENANT_ID = "your_tenant_id"
SCOPES = ["https://graph.microsoft.com/.default"]
# 初始化 MSAL 客户端
app = ConfidentialClientApplication(
CLIENT_ID,
authority=f"https://login.microsoftonline.com/{TENANT_ID}",
client_credential=CLIENT_SECRET,
)
# 获取访问令牌
token_response = app.acquire_token_for_client(scopes=SCOPES)
access_token = token_response.get("access_token")
if not access_token:
print("获取令牌失败!")
print(token_response.get("error_description"))
else:
print("成功获取令牌!")
4. 使用 Graph API 获取收件箱邮件
获取邮件列表:
# Graph API 基本 URL
GRAPH_API_URL = "https://graph.microsoft.com/v1.0"
# 设置请求头
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
# 获取收件箱邮件
response = requests.get(f"{GRAPH_API_URL}/me/mailFolders/inbox/messages", headers=headers)
if response.status_code == 200:
emails = response.json().get("value", [])
for email in emails:
print(f"Subject: {email['subject']}")
print(f"From: {email['from']['emailAddress']['address']}")
print(f"Received: {email['receivedDateTime']}")
else:
print(f"请求失败: {response.status_code}")
print(response.json())
5. 运行与测试
- 确保已在 Azure 中分配了正确的 API 权限。
- 运行脚本获取访问令牌和邮箱数据。
- 验证权限设置是否允许访问目标用户的邮箱。
6. 常见问题
403 错误
- 确保管理员授予了所需权限。
- 如果使用的是 委托权限,请确保使用的用户账户有相应权限。
令牌过期
- 默认令牌有效期较短(约 1 小时)。使用 刷新令牌 或重新获取令牌。
无法访问其他用户邮箱
- 需要使用 应用程序权限(
Mail.ReadBasic.All
或Mail.Read.All
)并由管理员授权。
发布者:myrgd,转载请注明出处:https://www.object-c.cn/4488