Вступ

Aspose.Email FOSS for Python is now available on PyPI: a free, MIT-licensed library for creating, reading, and converting Outlook .msg файли повністю у Python, без залежності від Microsoft Office чи будь-якого рідного розширення. Встановіть його за допомогою pip install aspose-email-foss>=26.3 і одразу починайте працювати з контейнерами MSG та CFB.

Бібліотека орієнтована на Python 3.10 і новіші. Вона реалізує формат Compound File Binary (CFB) та формат повідомлень MSG з нуля, надаючи вам детермінований контроль над тим, як електронні листи серіалізуються та читаються. Оскільки реалізація є чисто Python, вона працює однаково на Windows, macOS, Linux та в контейнеризованих середовищах.

Aspose.Email FOSS is designed for developers building email processing pipelines, compliance archival tools, forensic analysis workflows, or any application that needs to create or inspect Outlook-compatible message files without a running Exchange or Outlook installation.


Ключові особливості

Створення MSG‑файлів

Створюйте сумісні з Outlook .msg файли з нуля, використовуючи MapiMessage.create(). Встановлюйте стандартні властивості MAPI, такі як тема, відправник, час доставки та поля відображення, через PropertyId перелічення. Додавайте одержувачів за допомогою add_recipient() та вкладення файлів за допомогою add_attachment(), а потім збережіть результат на диск.

from aspose.email_foss import msg

message = msg.MapiMessage.create(
    "Quarterly status update and rollout plan",
    "Hello team,\n\nPlease find the latest rollout summary attached.\n\nRegards,\nEngineering",
)

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.INTERNET_MESSAGE_ID, "<example-001@example.com>")

message.add_recipient("alice@example.com", display_name="Alice Example")
message.add_recipient("bob@example.com", display_name="Bob Example")
message.add_recipient(
    "carol@example.com",
    display_name="Carol Example",
    recipient_type=msg.RECIPIENT_TYPE_CC,
)

message.add_attachment("hello.txt", b"sample attachment\n", mime_type="text/plain")
message.save("example-message.msg")

Читання та конвертація MSG у EML

Завантажте існуючий .msg файл з MapiMessage.from_file() і перетворіть його на стандартний Python EmailMessage об’єкт за допомогою to_email_message(). Звідти серіалізуйте у байти EML для зберігання або пересилання через SMTP.

from aspose.email_foss import msg

with msg.MapiMessage.from_file("example-message.msg") as loaded:
    email_message = loaded.to_email_message()
    eml_bytes = email_message.as_bytes()

with open("example-message.eml", "wb") as f:
    f.write(eml_bytes)

Перегляд внутрішньої структури MSG

Використовуйте MsgReader і його базовий CFBReader для аналізу бінарної структури файлу MSG. Доступ до метаданих CFB (версія, розмір сектора, кількість записів у каталозі) та ітерація по записах властивостей MAPI на бінарному рівні.

from aspose.email_foss import msg

reader = msg.MsgReader.from_file("example-message.msg")
cfb = reader.cfb_reader

print(f"CFB major_version={cfb.major_version}")
print(f"sector_size={cfb.sector_size}")
print(f"directory_entries={cfb.directory_entry_count}")

for entry in reader.iter_top_level_fixed_length_properties():
    tag = entry.property_tag
    print(f"tag=0x{tag:08X} flags=0x{entry.flags:08X} value={entry.value.hex()}")

reader.close()

Низькорівневий доступ до CFB

Читати та обходити будь-який контейнер Compound File Binary, використовуючи CFBReader. Перераховувати сховища та потоки, визначати шляхи за назвою та витягувати необроблені дані потоку для користувацької обробки.

from aspose.email_foss.cfb import CFBReader

reader = CFBReader.from_file("example-message.msg")

for entry in reader.iter_storages():
    print(f"Storage: {entry.name}")

for entry in reader.iter_streams():
    data = reader.get_stream_data(entry.stream_id)
    print(f"Stream: {entry.name} size={len(data)}")

reader.close()

Швидкий старт

Встановіть бібліотеку та створіть ваш перший MSG‑файл за менш ніж десять рядків:

pip install aspose-email-foss>=26.3
from aspose.email_foss import msg

message = msg.MapiMessage.create("Hello from Python", "This is a test message.")
message.set_property(msg.PropertyId.SENDER_EMAIL_ADDRESS, "sender@example.com")
message.add_recipient("recipient@example.com", display_name="Recipient")
message.save("hello.msg")

with msg.MapiMessage.from_file("hello.msg") as loaded:
    eml = loaded.to_email_message()
    print(eml["Subject"])

Підтримувані формати

ФорматІмпортЕкспорт
MSGТакТак
CFBТакТак

Відкритий код та ліцензування

Aspose.Email FOSS for Python is released under the MIT License. Ви можете використовувати його у особистих, внутрішніх та комерційних проектах без обмежень. Вихідний код доступний на GitHub.


Початок роботи