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

Python导出Outlook邮件内容至Excel生成空文件问题求助

问题

需求:通过Python自动抓取Outlook收件箱中每日收到的LYTX同步错误报告邮件内容,导出至Excel文件。当前脚本可抓取符合条件的邮件并在终端打印内容,但导出的CSV/TXT文件为空,尝试xlsxwriter和pandas DataFrame导出均未成功。

用户提供代码:

# Importing modules/libraries
import pandas as pd
import numpy as np
import win32com.client
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell

# Variables
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)  # 6 corresponds to the inbox folder

 # For loop to loop through Outlook inbox to find the report. It will print the most recent email in your inbox that matches the criteria.
for message in inbox.Items:
    if 'LYTX Sync errors' in message.Subject and 'The following vehicle adds/edits Failed in LYTX:' in message.body:
        latest = (f"Date: {message.senton.date()}	Sender: {message.Sender}	Trade Idea: {message.body}")
        with open("test.csv", "w") as new_file:
            new_file.write(latest[-1])

print (latest)

终端打印的邮件内容示例:

1116496 UPDATE ErrorCode:3-SerialNumber is invalid or ER group does not match with the Vehicle Group.
3311958 UPDATE ErrorCode:3-SerialNumber is invalid or ER group does not match with the Vehicle Group.
2217477 UPDATE ErrorCode:3-SerialNumber is invalid or ER group does not match with the Vehicle Group.
2218862 UPDATE ErrorCode:3-SerialNumber is invalid or ER group does not match with the Vehicle Group.
9922174 UPDATE ErrorCode:3-SerialNumber is invalid or ER group does not match with the Vehicle Group.
9922196 UPDATE ErrorCode:3-ER already has a vehicle attached.

问题排查与修复

核心问题点

  • 写入内容错误:代码中new_file.write(latest[-1])仅取latest字符串的最后一个字符,而非完整邮件内容,导致文件仅写入单个字符,视觉上呈现为空。
  • 未筛选最新邮件:Outlook的inbox.Items默认顺序并非按时间倒序,循环遍历所有邮件时,最后一次匹配的不一定是最新邮件,且每次匹配都会重写文件。
  • 未结构化处理内容:直接写入原始邮件body会导致CSV格式混乱,无法生成规范的表格数据。

修复后的代码

以下代码实现:按时间排序获取最新报告、解析错误内容为结构化数据、导出为规范的CSV和Excel文件。

import win32com.client
import pandas as pd

# 初始化Outlook连接
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)

# 按邮件接收时间倒序排序,优先处理最新邮件
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)

# 存储解析后的错误数据
error_records = []
target_email = None

# 遍历找到最新的目标报告邮件
for msg in messages:
    if 'LYTX Sync errors' in msg.Subject and 'The following vehicle adds/edits Failed in LYTX:' in msg.body:
        target_email = msg
        # 拆分邮件内容为行,过滤有效错误行
        body_lines = msg.body.split('\n')
        for line in body_lines:
            line_clean = line.strip()
            # 筛选包含操作类型和错误码的有效行
            if line_clean and ('UPDATE' in line_clean or 'ADD' in line_clean) and 'ErrorCode:' in line_clean:
                # 拆分错误行字段
                id_part, op_part, error_part = line_clean.split(' ', 2)
                code_part, desc_part = error_part.split('-', 1)
                error_records.append({
                    'Error ID': id_part,
                    'Operation': op_part,
                    'Error Code': code_part.replace('ErrorCode:', ''),
                    'Error Description': desc_part.strip(),
                    'Report Date': msg.senton.date(),
                    'Sender': msg.SenderName
                })
        break  # 找到最新邮件后停止遍历

# 导出数据
if error_records:
    df = pd.DataFrame(error_records)
    df.to_csv('LYTX_Sync_Errors.csv', index=False, encoding='utf-8-sig')
    df.to_excel('LYTX_Sync_Errors.xlsx', index=False)
    print("数据导出完成")
else:
    print("未找到符合条件的邮件或无有效错误内容")

关键改进说明

  • 邮件排序:通过messages.Sort("[ReceivedTime]", True)确保优先遍历最新邮件,找到目标后立即终止循环,提升效率。
  • 结构化解析:将每行错误内容拆分为独立字段,保证导出的表格数据清晰规范。
  • 规范导出:使用pandas的内置方法处理格式转换,避免手动写入的格式错误,同时支持CSV和Excel两种格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:43:27