Tải, Xem và Phân tích tệp MSG
Chủ đề này giải thích cách tải tệp tin Microsoft Outlook (*.msg). The MapiMessage lớp được sử dụng để tải các tệp MSG, và cung cấp một số hàm tải tĩnh cho các kịch bản khác nhau. Đoạn mã sau cho bạn thấy cách tải các tệp MSG từ tệp hoặc từ luồng.
Try it out!
Phân tích tệp email trực tuyến miễn phí Ứng dụng Phân tích Aspose.Email.
Tải các Tệp MSG
Đoạn mã sau đây cho bạn thấy cách tải các tệp 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)
Tải từ Luồng
Đoạn mã sau cho bạn thấy cách tải tệp từ luồng.
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)
Chuyển đổi EML sang MSG giữ định dạng EML nhúng
Các tệp EML có thể được tải vào MapiMessage lớp bằng cách khởi tạo một MailMessage đối tượng và truyền nó vào phương pháp MapiMessage.from_mail_message. Nếu tệp EML chứa các tệp EML nhúng, sử dụng MapiConversionOptions.PreserveEmbeddedMessageFormat để giữ lại định dạng của các tệp EML nhúng. Đoạn mã dưới đây cho thấy cách tải các tệp EML vào MapiMessage trong khi bảo tồn định dạng của các tệp EML nhúng.
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)