Tải và Phân tích Tệp MSG
Phần này giải thích cách tải và phân tích các tệp tin nhắn Microsoft Outlook (.msg). API Aspose.Email cung cấp một MapiMessage lớp để tải các tệp MSG với một số hàm tải tĩnh cho các kịch bản khác nhau. Các đoạn mã sau minh họa cách tải 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 một Tệp MSG từ Đĩa
Đoạn mã dưới đây cho bạn thấy cách tải tệp MSG từ đĩa:
from aspose.email.mapi import MapiMessage
# Create an instance of MapiMessage from file
msg = MapiMessage.load("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 một Tệp MSG từ Luồng
Đoạn mã dưới đây cho bạn thấy cách tải tệp MSG từ luồng:
from aspose.email.mapi import MapiMessage
import io
# Read the file into a byte array
file_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.load(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ó tới MapiMessage.from_mail_message phương thức. Nếu tệp EML chứa các tệp nhúng, hãy sử dụng MapiConversionOptions.preserve_embedded_message_format để giữ nguyên định dạng của các tệp 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 giữ nguyên định dạng của các tệp EML nhúng.
Đoạn mã dưới đây minh họa cách chuyển đổi tệp EML sang tệp MSG trong khi giữ nguyên định dạng tin nhắn nhúng:
from aspose.email import MailMessage, EmlLoadOptions
from aspose.email.mapi import MapiMessage, MapiConversionOptions, OutlookMessageFormat
eml_file = "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)