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

如何用Python提取Outlook邮件中.msg附件内的CSV文件?

解决Outlook内嵌.msg附件中CSV文件的提取问题

你的代码目前只能处理邮件的直接外层附件,要提取.msg附件里的CSV,需要把.msg文件当作独立的Outlook邮件对象来解析。以下是修改后的代码:

import win32com.client
from pathlib import Path

outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)

# 定义保存目录,用Path类管理路径更安全规范
save_dir = Path(r"C:/Users/el/Documents")
save_dir.mkdir(exist_ok=True)

for msg in list(messages):
    if "Hello" in str(msg.Subject):
        for att in msg.Attachments:
            att_path = save_dir / att.FileName
            att.SaveAsFile(str(att_path))
            
            # 检查是否是.msg格式附件,需进一步解析内嵌内容
            if att.FileName.lower().endswith(".msg"):
                # 打开保存的.msg文件作为Outlook邮件项
                embedded_msg = outlook.OpenSharedItem(str(att_path))
                # 遍历内嵌邮件的附件,提取CSV文件
                for embedded_att in embedded_msg.Attachments:
                    if embedded_att.FileName.lower().endswith(".csv"):
                        csv_path = save_dir / embedded_att.FileName
                        embedded_att.SaveAsFile(str(csv_path))
                        print(f"已保存内嵌CSV文件: {csv_path}")
                # 可选:若不需要保留外层.msg文件,处理完后删除
                # att_path.unlink()

关键逻辑说明:

  • 使用Path类管理文件路径,避免手动拼接字符串导致的路径错误
  • 保存外层附件后,判断附件是否为.msg格式
  • 通过outlook.OpenSharedItem()方法打开.msg文件,获取内嵌的邮件对象
  • 遍历内嵌邮件的附件列表,筛选出.csv格式文件并保存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:45:34