การโหลด ดู และแยกไฟล์ MSG

หัวข้อนี้อธิบายวิธีโหลดไฟล์ข้อความ Microsoft Outlook (*.msg). The 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 เข้าไปใน MapiMessage พร้อมรักษารูปแบบของไฟล์ EML ฝัง.

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)