介绍

Aspose.Email FOSS for Python goes beyond basic message creation. The library exposes the full depth of the MAPI property model, letting you read, write, and query individual properties by ID and type. It handles recipients, attachments, and embedded messages as first-class objects, and provides bidirectional conversion between the MSG binary format and Python’s standard email.message.EmailMessage.

在容器层面,CFB 读取器和写入器为您提供对 Compound File Binary 文档的确定性控制。您可以遍历存储层次结构,提取原始流数据,从头构建新容器,并将其序列化回字节。两者 CFBErrorMsgError 提供针对错误输入的结构化异常处理。.

本文逐一演示每项功能,配以直接取自库自身测试套件和示例脚本的验证代码示例。.


包含内容

MAPI 属性访问

每个 MSG 文件都基于 MAPI 属性构建。. MapiMessage 公开 set_property()get_property() 用于通过它们的 PropertyId 枚举值。使用 iter_properties() 来枚举消息上的所有属性,或 get_property_value() 用于直接获取值,并可选进行类型解码。.

from aspose.email_foss import msg

message = msg.MapiMessage.create("Status report", "Weekly update attached.")

message.set_property(msg.PropertyId.SENDER_NAME, "Build Agent")
message.set_property(msg.PropertyId.SENDER_EMAIL_ADDRESS, "build.agent@example.com")
message.set_property(msg.PropertyId.DISPLAY_TO, "Alice Example; Bob Example")
message.set_property(msg.PropertyId.DISPLAY_CC, "Carol Example")
message.set_property(msg.PropertyId.DISPLAY_BCC, "Ops Archive")
message.set_property(
    msg.PropertyId.TRANSPORT_MESSAGE_HEADERS,
    "X-Environment: production\nX-Workflow: weekly-report\n",
)
message.save("report.msg")

从现有文件读取属性::

from aspose.email_foss import msg

with msg.MapiMessage.from_file("report.msg") as loaded:
    print(f"Subject: {loaded.subject}")
    print(f"Body: {loaded.body}")

    for prop in loaded.iter_properties():
        print(f"tag=0x{prop.property_tag:08X}")

收件人和附件

使用 add_recipient(),,指定显示名称和收件人类型(To、CC 或 BCC)。使用 add_attachment() 使用原始字节和 MIME 类型。对于嵌套消息,, add_embedded_message_attachment() 嵌入一个完整的 MapiMessage 作为父对象内部的子对象。.

from aspose.email_foss import msg

message = msg.MapiMessage.create("Team update", "See attached notes.")

message.add_recipient("alice@example.com", display_name="Alice Example")
message.add_recipient(
    "carol@example.com",
    display_name="Carol Example",
    recipient_type=msg.RECIPIENT_TYPE_CC,
)
message.add_recipient(
    "archive@example.com",
    display_name="Ops Archive",
    recipient_type=msg.RECIPIENT_TYPE_BCC,
)

message.add_attachment("notes.txt", b"Meeting notes content\n", mime_type="text/plain")
message.add_attachment("data.bin", b"\x00\x01\x02\x03", mime_type="application/octet-stream")
message.save("team-update.msg")

检查现有消息的附件::

from aspose.email_foss import msg

with msg.MapiMessage.from_file("team-update.msg") as loaded:
    for att in loaded.iter_attachments_info():
        print(f"name={att.filename} mime={att.mime_type} size={len(att.data)}")
        print(f"  embedded={att.is_embedded_message} storage={att.storage_name}")

MSG 到 EmailMessage 转换

该库在 MSG 与 Python 之间进行双向转换 email.message.EmailMessage.使用 to_email_message() 生成符合标准的 MIME 对象,或 from_email_message() 导入现有的 EmailMessage 为 MSG 格式。便利方法 to_email_bytes()to_email_string() 直接序列化为字节或文本。.

from aspose.email_foss import msg

with msg.MapiMessage.from_file("example.msg") as loaded:
    email_msg = loaded.to_email_message()

    print(f"content_type: {email_msg.get_content_type()}")
    print(f"is_multipart: {email_msg.is_multipart()}")
    print(f"headers: {len(email_msg)}")

    for key, value in email_msg.items():
        print(f"  {key}: {value}")

    body_part = email_msg.get_body(preferencelist=("plain", "html"))
    if body_part is not None:
        print(f"body: {body_part.get_content()[:200]}")

CFB 容器往返

在不依赖 MSG 层的情况下构建并序列化复合文件二进制容器。. CFBDocument.from_file() 将现有容器加载到可变文档模型中,带有 CFBStorageCFBStream 节点。. CFBWriter.write_file() 以确定性的方式将文档序列化回磁盘。.

from aspose.email_foss.cfb import CFBDocument, CFBReader, CFBWriter

reader = CFBReader.from_file("container.cfb")
document = CFBDocument.from_reader(reader)
reader.close()

output = CFBWriter.to_bytes(document)
print(f"Serialized {len(output)} bytes")

错误处理

该库会抛出 CFBError 针对损坏的 CFB 内容以及 MsgError 针对无效的 MSG 结构。. MapiMessage 还公开了一个 validation_issues 属性返回一个包含警告字符串的元组,而不会抛出异常,让您自行决定如何严格处理不符合规范的文件。.

from aspose.email_foss.cfb import CFBReader, CFBError
from aspose.email_foss.msg import MsgReader, MsgError

try:
    reader = CFBReader.from_file("corrupted.cfb")
except CFBError as e:
    print(f"CFB parse error: {e}")

try:
    reader = MsgReader.from_file("malformed.msg")
except MsgError as e:
    print(f"MSG parse error: {e}")

快速入门

pip install aspose-email-foss>=26.3

加载现有 MSG,读取其元数据,并列出附件::

from aspose.email_foss import msg

with msg.MapiMessage.from_file("inbox-message.msg") as message:
    print(f"Subject: {message.subject}")
    print(f"Body preview: {message.body[:200] if message.body else '(empty)'}")

    for att in message.iter_attachments_info():
        print(f"Attachment: {att.filename} ({att.mime_type}, {len(att.data)} bytes)")

    issues = message.validation_issues
    if issues:
        print(f"Warnings: {issues}")

支持的格式

格式导入导出
MSG
CFB

开源与许可

Aspose.Email FOSS for Python is released under the MIT 许可证. 您可以在个人、内部和商业项目中无限制地使用它。源代码可在 GitHub.


入门指南