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

如何用Python将Outlook邮件(.msg)另存为.html或.pdf格式

解决Outlook邮件保存为HTML/PDF乱码问题

直接修改文件后缀名无法让Outlook正确生成HTML或PDF文件,必须在调用SaveAs方法时指定对应的文件格式常量。以下是具体实现方案:

核心说明

Outlook的SaveAs方法需要第二个参数指定文件类型,常用格式对应的常量值:

  • olMSG(MSG格式):3
  • olHTML(HTML格式):5

直接改后缀会让Outlook仍按MSG格式保存,导致文件解析乱码。

1. 保存为HTML格式

先清理邮件主题中的非法文件名字符(比如<>:"/\|?*),再指定olHTML格式保存:

from pathlib import Path
import win32com.client as win32
import os

def clean_filename(filename):
    # 替换文件名中的非法字符
    invalid_chars = '<>:"/\\|?*'
    for char in invalid_chars:
        filename = filename.replace(char, '_')
    return filename

# 创建输出目录
output_dir = Path.cwd()
output_dir.mkdir(parents=True, exist_ok=True)

# 连接Outlook已发送邮件文件夹
outlook = win32.Dispatch('outlook.application').GetNamespace("MAPI")
sent_items = outlook.GetDefaultFolder(5)  # 5对应已发送邮件文件夹

# 获取最后一封邮件
message = sent_items.items.GetLast()
subject = str(message.subject)
clean_subject = clean_filename(subject)

# 保存为HTML
html_path = os.path.join(output_dir, f"{clean_subject}.html")
message.SaveAs(html_path, 5)  # 5对应olHTML格式
print(f"HTML文件已保存至: {html_path}")

2. 保存为PDF格式

Outlook原生SaveAs不支持直接保存PDF,提供两种实现方式:

方式一:通过HTML转PDF(需额外依赖)

先保存为HTML,再用pdfkit转换为PDF:

  1. 安装依赖:pip install pdfkit
  2. 下载wkhtmltopdf并添加到系统环境变量(或在代码中指定路径)
import pdfkit

# 先执行上面的HTML保存代码
html_path = os.path.join(output_dir, f"{clean_subject}.html")
message.SaveAs(html_path, 5)

# 转换为PDF
pdf_path = os.path.join(output_dir, f"{clean_subject}.pdf")
# 若wkhtmltopdf未在环境变量,需指定路径:
# config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
# pdfkit.from_file(html_path, pdf_path, configuration=config)
pdfkit.from_file(html_path, pdf_path)
print(f"PDF文件已保存至: {pdf_path}")

方式二:利用Outlook打印功能转PDF(无额外依赖)

通过Windows自带的「Microsoft Print to PDF」虚拟打印机直接打印邮件为PDF:

# 保存为PDF
pdf_path = os.path.join(output_dir, f"{clean_subject}.pdf")
# 打印到PDF虚拟打印机
message.PrintOut(
    Background=False,
    Printer="Microsoft Print to PDF",
    OutputFileName=pdf_path
)
print(f"PDF文件已保存至: {pdf_path}")

注意事项

  • 必须确保Outlook客户端处于运行状态,否则win32com无法连接。
  • 邮件主题中的特殊字符必须清理,否则会触发文件保存错误。
  • 使用打印转PDF时,需确保系统已安装「Microsoft Print to PDF」打印机(Windows 10及以上默认自带)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:10:36