如何在 Python 中创建 MSG 文件
aspose-email-foss for Python 让您能够在没有 Microsoft Office 的情况下以编程方式创建 Outlook MSG 文件。
分步指南
步骤 1:安装软件包
pip install aspose-email-foss步骤 2:创建消息
from aspose.email_foss.msg import MapiMessage, RECIPIENT_TYPE_CC
msg = MapiMessage.create("Meeting Notes", "Please review the attached notes.")步骤 3:添加收件人
msg.add_recipient("alice@example.com", display_name="Alice Smith")
msg.add_recipient("bob@example.com", display_name="Bob Jones", recipient_type=RECIPIENT_TYPE_CC)使用整数常量 RECIPIENT_TYPE_TO (1)、RECIPIENT_TYPE_CC (2) 或 RECIPIENT_TYPE_BCC (3) 来自 aspose.email_foss.msg。
步骤 4:添加附件
with open("notes.pdf", "rb") as f:
msg.add_attachment("notes.pdf", f.read(), mime_type="application/pdf")嵌入另一个 MSG 消息:
inner = MapiMessage.create("Forwarded", "Original message body")
msg.add_embedded_message_attachment(inner, filename="forwarded.msg", mime_type="application/vnd.ms-outlook")步骤 5:保存 MSG 文件
msg.save("output.msg")或者获取用于流式传输的字节:
data = msg.to_bytes()常见问题及解决方案
已保存文件中的收件人为空
确保在调用 save() 之前调用 add_recipient()。收件人在序列化期间被写入。
Outlook 中未显示附件
验证 MIME 类型是否正确。对于未知文件类型,请使用 "application/octet-stream" 作为回退。
常见问题 (FAQ)
我可以设置 HTML 正文吗?
是的。使用 msg.body_html = "value" 在创建后设置 HTML 正文。
我可以将 MSG 转换为 EML 格式吗?
是的。调用 msg.to_email_string() 以获取 RFC 5322 表示。
最大消息大小?
没有硬性限制。CFB v3 支持文件最高 2 GB;v4 支持更大的文件。