加载、查看和解析 MSG 文件

本主题解释如何加载 Microsoft Outlook 消息文件 (*.msg)。 MapiMessage 该类用于加载 MSG 文件,并提供多种静态加载函数以适应不同场景。以下代码片段展示如何从文件或流中加载 MSG 文件。

加载 MSG 文件

以下代码片段展示如何加载 MSG 文件。

from aspose.email.mapi import MapiMessage

# Create an instance of MapiMessage from file
msg = MapiMessage.from_file("message.msg")

# Get subject
print("Subject: " + msg.subject)

# Get from address
print("From: " + msg.sender_email_address)

# Get body
print("Body: " + msg.body)

# Get recipients information
recipients = ", ".join([r.email_address for r in msg.recipients])
print("Recipients: " + recipients)

# Get attachments
for att in msg.attachments:
    print(att.file_name)
    print(att.display_name)

从流加载

以下代码片段展示如何从流中加载文件。

from aspose.email.mapi import MapiMessage
import io

# Read the file into a byte array
file_path = dir_path + "message.msg"
with open(file_path, "rb") as file:
    bytes_data = file.read()

# Create a memory stream from the byte array
stream = io.BytesIO(bytes_data)
stream.seek(0)

# Create an instance of MapiMessage from the stream
msg = MapiMessage.from_stream(stream)

# Get subject
print("Subject: " + msg.subject)

# Get from address
print("From: " + msg.sender_email_address)

# Get body
print("Body: " + msg.body)

将 EML 转换为 MSG 并保留嵌入的 EML 格式

EML 文件可以加载到 MapiMessage 类,通过实例化一个 MailMessage 对象并将其传递给 MapiMessage.from_mail_message 方法。如果 EML 文件包含嵌入的 EML 文件,请使用 MapiConversionOptions.PreserveEmbeddedMessageFormat 来保留嵌入 EML 文件的格式。下面的代码片段展示如何在保留嵌入 EML 文件格式的情况下将 EML 文件加载到 MapiMessage 中。

from aspose.email import MailMessage, EmlLoadOptions
from aspose.email.mapi import MapiMessage, MapiConversionOptions, OutlookMessageFormat

eml_file = dir_path + "message.eml"

# Load the EML file
eml_options = EmlLoadOptions()
eml = MailMessage.load(eml_file, eml_options)

# Create MapiConversionOptions
conversion_options = MapiConversionOptions()
conversion_options.format = OutlookMessageFormat.UNICODE

# Preserve Embedded Message Format
conversion_options.preserve_embedded_message_format = True

# Convert EML to MSG with options
msg = MapiMessage.from_mail_message(eml, conversion_options)