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

如何用Python读取指定Outlook邮件并保存为Excel/CSV文件

Hey there, let's get your daily Outlook report reading task sorted out properly. Based on what you described, here's a polished solution that addresses your needs accurately:

自动读取每日Creation Report邮件的Python实现

需求回顾

  • 每日接收主题格式为 Creation Report - DD/MM/YYYY 的邮件(日期随当日变化)
  • 邮件内容包含表格数据
  • 需要自动化读取该邮件的表格内容

完善后的代码方案

Your original code was a good start, but using GetLast might not reliably grab the right email. Instead, we'll filter by the exact daily subject and parse the table properly:

import win32com.client
import datetime
from bs4 import BeautifulSoup

def fetch_daily_creation_report():
    # 连接到Outlook客户端
    outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
    inbox = outlook.GetDefaultFolder(6)  # 6是Outlook默认收件箱的索引
    messages = inbox.Items

    # 生成今日的邮件主题模板
    today_date = datetime.datetime.now().strftime("%d/%m/%Y")
    target_subject = f"Creation Report - {today_date}"

    # 按接收时间倒序排列邮件,优先检查最新的
    messages.Sort("[ReceivedTime]", True)
    target_email = None

    # 遍历邮件找到匹配主题的那封
    for msg in messages:
        if msg.Subject == target_subject:
            target_email = msg
            break

    if not target_email:
        print(f"Oops, couldn't find today's ({today_date}) Creation Report email.")
        return None

    # 解析邮件中的表格(处理HTML格式的邮件,Outlook最常用的格式)
    if target_email.BodyFormat == 2:  # 2代表HTML格式
        html_content = target_email.HTMLBody
        soup = BeautifulSoup(html_content, "html.parser")
        
        # 提取所有表格,假设第一个表格就是我们需要的报告
        report_tables = soup.find_all("table")
        if report_tables:
            print("Found the report table! Here's the content:")
            # 遍历表格行和单元格,输出内容
            for row in report_tables[0].find_all("tr"):
                cells = row.find_all(["td", "th"])
                row_data = [cell.get_text(strip=True) for cell in cells]
                print(row_data)
            return report_tables[0]
        else:
            print("No tables found in the email body.")
            return None
    else:
        print("The email isn't in HTML format—you'll need to adjust the code to parse plain text tables.")
        return None

# 执行函数
fetch_daily_creation_report()

关键细节说明

  • 精准邮件筛选:通过匹配当日日期的主题,避免误读其他邮件;按接收时间倒序,确保优先获取最新的邮件(防止同一天多封同名邮件)
  • 表格解析:用BeautifulSoup处理HTML格式的邮件正文,这是Outlook邮件的主流格式;如果你的邮件是纯文本表格,需要修改代码用字符串分割的方式处理
  • 依赖安装:运行前需要安装两个必要库,执行命令:
    pip install pywin32 beautifulsoup4
    

注意事项

  • 确保运行代码时Outlook客户端已打开并登录了正确的账号
  • 如果你的目标邮件不在默认收件箱,可通过outlook.Folders定位到对应的邮箱文件夹
  • 若邮件主题的日期格式是MM/DD/YYYY,把strftime("%d/%m/%Y")改成strftime("%m/%d/%Y")即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:35:16