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

如何使用Python将Outlook指定日期的邮件保存到本地文件夹

Python实现Outlook指定时段邮件批量导出到本地

前置依赖

仅支持Windows环境,调用本地Outlook客户端的COM接口实现,无需对接云端API:

  • 安装依赖库:pip install pywin32
  • 运行前请确保本地Outlook客户端已打开并登录目标邮箱账号

完整实现代码

import win32com.client
import os
from datetime import datetime, date

def save_outlook_emails(save_path, target_date=None):
    """
    导出Outlook邮件到本地
    :param save_path: 本地存储文件夹路径,不存在会自动创建
    :param target_date: 可选参数,指定要导出的日期(格式:datetime.date对象),如果不传则默认导出当日零点到当前运行时间的邮件
    """
    # 初始化Outlook客户端
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    # 如需指定邮箱账号,替换为下方写法填入你的完整邮箱地址即可
    # inbox = outlook.Folders.Item("your_email@example.com").Folders.Item("收件箱")
    inbox = outlook.GetDefaultFolder(6) # 6为Outlook收件箱的默认索引
    messages = inbox.Items
    # 按接收时间倒序排序,减少无效遍历
    messages.Sort("[ReceivedTime]", True)

    # 构造时间筛选范围
    if target_date:
        start_time = datetime.combine(target_date, datetime.min.time())
        end_time = datetime.combine(target_date, datetime.max.time())
    else:
        start_time = datetime.combine(date.today(), datetime.min.time())
        end_time = datetime.now()

    # 自动创建存储路径
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    count = 0
    for message in messages:
        # 跳过非邮件类对象(会议邀请、日历提醒等)
        if message.Class != 43:
            continue
        received_time = message.ReceivedTime.replace(tzinfo=None)
        # 已按时间倒序排列,早于起始时间即可终止遍历
        if received_time < start_time:
            break
        if received_time <= end_time:
            # 处理邮件标题特殊字符,避免保存报错
            subject = message.Subject.replace("/", "_").replace("\\", "_").replace(":", "_").replace("*", "_").replace("?", "_").replace('"', "_").replace("<", "_").replace(">", "_").replace("|", "_")
            # 文件名增加时间前缀避免重名
            file_name = f"{received_time.strftime('%Y%m%d_%H%M%S')}_{subject}.msg"
            save_full_path = os.path.join(save_path, file_name)
            # 保存完整邮件
            message.SaveAs(save_full_path)
            count += 1
            print(f"已保存:{file_name}")
    print(f"导出完成,共保存{count}封邮件到{save_path}")

if __name__ == "__main__":
    # 用法1:导出指定日期(示例为2024年5月20日)的所有邮件
    # save_outlook_emails(save_path=r"C:\OutlookEmails\20240520", target_date=date(2024,5,20))
    # 用法2:导出当日零点到程序运行时间的所有邮件
    save_outlook_emails(save_path=r"C:\OutlookEmails\今日邮件")

补充说明

  • 导出的.msg格式文件包含完整的邮件内容、附件、发件人/收件人、Header等全量信息,可直接双击用Outlook打开
  • 如需单独导出邮件附件,可在保存邮件的逻辑处新增遍历message.Attachments的代码,调用附件的SaveAsFile方法即可单独存储附件
  • 如需导出已发送邮件、草稿箱等其他文件夹的内容,修改GetDefaultFolder的参数即可:已发送邮件对应索引5,发件箱对应3,草稿对应16

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:36:04