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

Python提取Outlook邮件仅能获取最近1年数据,如何调整获取全量历史邮件

解决方案:Python提取Outlook全量历史邮件

问题原因

该问题由Outlook默认的缓存Exchange模式导致:默认仅同步最近12个月的邮件到本地缓存文件,win32com读取本地缓存时自然无法获取更早的历史邮件。

解决方法

方法1:调整Outlook本地同步配置(无需修改代码)

  • 打开Outlook,进入「文件」>「账户设置」>「账户设置」
  • 双击目标Exchange邮箱账户,找到「离线设置」区域
  • 将「使用缓存Exchange模式」下的同步时间滑块拖动到最右端,选择「所有」,保存设置后重启Outlook,等待全量邮件同步完成后再运行原代码即可获取所有邮件。

方法2:代码适配服务端查询(无需修改Outlook配置)

如果无法修改邮箱配置,可以通过排序+服务端筛选的方式获取指定时间范围的邮件,修改后代码如下:

import win32com.client 
import codecs
import datetime

name = input('Enter your first name: ')
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
corpus = codecs.open(f'{name}_email_corpus.txt', 'w', 'utf-8')
messages = inbox.Items
# 按接收时间排序,确保能遍历到所有时间范围的邮件
messages.Sort("[ReceivedTime]", True)
# 可选:按需求筛选1年以前的邮件,可自行调整时间阈值
one_year_ago = datetime.datetime.now() - datetime.timedelta(days=365)
filter_str = f"[ReceivedTime] <= '{one_year_ago.strftime('%m/%d/%Y %H:%M %p')}'"
filtered_messages = messages.Restrict(filter_str)

# 新增异常处理,避免特殊类型邮件(如会议邀请)导致运行中断
for message in filtered_messages:
    try:
        subject = str(message.Subject) if message.Subject else "无主题"
        body = str(message.Body) if message.Body else "无正文"
        corpus.write(subject + '\n')
        corpus.write(body + '\n' + '='*50 + '\n')
    except Exception as e:
        print(f"跳过异常邮件:{e}")
        continue

corpus.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:54:03