You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用MS Graph API标记Outlook邮件为已读?

使用MS Graph API标记Outlook邮件为已读的解决方案

可以通过MS Graph API的PATCH请求将邮件标记为已读,以下是具体实现方案,同时优化你的邮件读取逻辑避免无效数据处理:

一、先过滤读取未读邮件

你的现有代码会获取所有邮件,建议先通过$filter参数只拉取未读邮件,减少数据处理量:

# 构造仅获取未读邮件的请求URL
read_url = f'https://graph.microsoft.com/v1.0/users/{self.userId}/messages?$filter=isRead eq false'

response = requests.get(
    read_url,
    headers={'Authorization': f'Bearer {self.result["access_token"]}'}
)

# 解析未读邮件列表
if response.status_code == 200:
    unread_messages = response.json().get('value', [])
else:
    print(f"获取未读邮件失败: {response.text}")

二、标记单封邮件为已读

对每封未读邮件发送PATCH请求,修改isRead属性为true:

for msg in unread_messages:
    msg_id = msg['id']
    update_url = f'https://graph.microsoft.com/v1.0/users/{self.userId}/messages/{msg_id}'
    
    # 构造修改请求体
    payload = {'isRead': True}
    
    update_response = requests.patch(
        update_url,
        headers={
            'Authorization': f'Bearer {self.result["access_token"]}',
            'Content-Type': 'application/json'
        },
        json=payload
    )
    
    if update_response.status_code == 200:
        print(f"邮件 {msg_id} 已标记为已读")
    else:
        print(f"标记邮件 {msg_id} 失败: {update_response.text}")

三、批量标记多封邮件(推荐)

如果未读邮件数量较多,使用批量请求减少API调用次数:

batch_url = 'https://graph.microsoft.com/v1.0/$batch'

# 构造批量请求条目
batch_requests = []
for idx, msg in enumerate(unread_messages):
    batch_requests.append({
        'id': str(idx+1),
        'method': 'PATCH',
        'url': f'/users/{self.userId}/messages/{msg["id"]}',
        'body': {'isRead': True},
        'headers': {'Content-Type': 'application/json'}
    })

# 发送批量请求
batch_response = requests.post(
    batch_url,
    headers={
        'Authorization': f'Bearer {self.result["access_token"]}',
        'Content-Type': 'application/json'
    },
    json={'requests': batch_requests}
)

if batch_response.status_code == 200:
    batch_results = batch_response.json().get('responses', [])
    for res in batch_results:
        if res['status'] == 200:
            print(f"批量操作成功: 邮件ID {res['id']}")
        else:
            print(f"批量操作失败: {res['id']} - {res['body']}")
else:
    print(f"批量请求失败: {batch_response.text}")

关键注意事项

  • 确保你的应用已申请Mail.ReadWrite权限(仅Mail.Read权限无法修改邮件状态)
  • 处理完邮件后立即执行标记操作,避免重复读取导致CRM生成重复工单
  • 若邮件数量过大,可结合$top参数限制单次请求返回数量,并通过@odata.nextLink实现分页读取

内容的提问来源于stack exchange,提问作者RatheeshTS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:45:39