מבוא

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. אתה יכול לעבור על היררכיות האחסון, לחלץ נתוני זרם גולמיים, לבנות מכולות חדשות מאפס, ולסדר אותן חזרה לבייטים. שניהם CFBError ו MsgError מספקים טיפול מובנה בחריגות עבור קלט פגום.

פוסט זה מוביל דרך כל יכולת עם דוגמאות קוד מאומתות שנלקחו ישירות ממערכת הבדיקות והסקריפטים לדוגמה של הספרייה.


מה כלול

גישה למאפייני MAPI

כל קובץ MSG נבנה על בסיס מאפייני MAPI. MapiMessage מחשף set_property() ו get_property() לעבודה עם מאפיינים לפי PropertyId ערך enum. השתמש ב 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’s email.message.EmailMessage. השתמש to_email_message() לייצר אובייקט MIME תואם לתקנים, או from_email_message() לייבא קיים EmailMessage לתוך פורמט MSG. שיטות נוחות to_email_bytes() ו to_email_string() serialize ישירות לבייטים או לטקסט.

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

בנה ו-serialize מכולות Compound File Binary באופן עצמאי משכבת ה-MSG. CFBDocument.from_file() טוען מכולה קיימת למודל מסמך ניתן לשינוי עם CFBStorage ו CFBStream צמתים. CFBWriter.write_file() serialize את המסמך חזרה לדיסק באופן דטרמיניסטי.

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 property שמחזירה טופל של מחרוזות אזהרה ללא העלאת חריגה, ומאפשרת לך להחליט כמה בקפדנות לטפל בקבצים שאינם תואמים.

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 License. אתה יכול להשתמש בו בפרויקטים אישיים, פנימיים ומסחריים ללא הגבלה. קוד המקור זמין ב GitHub.


התחלה