Introduction

Aspose.Email FOSS for Python is a free, MIT-licensed library for creating, reading, and конвертування файлів повідомлень, сумісних з Outlook на чистому Python. Доступний в PyPI як aspose-email-foss, він працює на Windows, macOS, Linux, Docker та безсерверних середовищах. без залежності від Microsoft Office і без власного часу виконання.

Бібліотека охоплює дві основні області: рівень MAPI високого рівня (MapiMessage) для роботи з суб’єктами повідомлень, тіла, одержувачі та додатки; і структурний рівень низького рівня шар (MsgReader, CFBReader, CFBStorage, CFBStream) що викриває сирове сполучення. Файли Бінарні контейнери, що лежать в основі кожного файлу. .msg файл.

Ця стаття проходить через ключові функції, поставлені в версії 26.3, засновані на підтвердженої поверхні API.


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

Створення повідомлень високого рівня з MapiMessage

MapiMessage є основною точкою входу для створення повідомлення з Outlook, які сумісні з Позвони. MapiMessage.create() з предметом і тілом, додати одержувачів та прикріплення, а потім зберігати безпосередньо на .msg файл.

from aspose.email_foss import msg

message = msg.MapiMessage.create(
    "Quarterly status update",
    "Hello team,\n\nPlease review the attached summary.\n\nRegards,\nEngineering",
)

message.set_property(msg.PropertyId.SENDER_NAME, "Build Agent")
message.set_property(msg.PropertyId.SENDER_EMAIL_ADDRESS, "agent@example.com")

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_attachment("report.txt", b"Summary content here.\n", mime_type="text/plain")
message.save("output.msg")

Читання та перевірка файлів MSG

MsgReader забезпечує структурований доступ до існуючого .msg файл без повної завантаження в MapiMessage.Він розкриває записи про власність верхнього рівня, зберігання одержувачів та прикріплений зберігання окремо, що робить його практичним для великої інспекції файлів і трубопровідники для валідації.

with msg.MsgReader.from_file(“output.msg”) as reader: header = reader.top_level_header print(f"Recipients : {header.recipient_count}") print(f"Attachments: {header.attachment_count}")

for entry in reader.iter_recipient_storages():
    _, props = reader.parse_subobject_property_stream(entry.stream_id)
    print(f"  Recipient storage {entry.name}: {len(props)} property entries")

### Повернення та повернення: завантажити, змінити і зберегти.

Because `MapiMessage` підставки `from_file()` для завантаження та `save()` для написання, повний Цикл читання-зміни-запису вимагає лише декількох рядків. Названі властивості, вписані енуми та Упрацювання струнних кодів в Unicode доступно через: `set_property`, `PropertyId`, і `MapiNamedProperty`.

with msg.MapiMessage.from_file("original.msg") as message:
    message.set_property(msg.PropertyId.SUBJECT, "Updated Subject")
    message.save("updated.msg")

EML / RFC 5322 Перевершення

MapiMessage.to_email_message() перетворює завантажений MSG в стандартний Python. email.message.EmailMessage об’єкт, що дозволяє експорт до RFC 5322 .eml формат з використанням стандартна бібліотека.MapiMessage.from_email_message()) конструкції а) MapiMessage з 1 січня EmailMessage.

from pathlib import Path
from aspose.email_foss import msg

with msg.MapiMessage.from_file("message.msg") as message:
    eml_bytes = message.to_email_bytes()
    Path("message.eml").write_bytes(eml_bytes)

# Reverse: load EML into MapiMessage
import email
raw_eml = Path("message.eml").read_bytes()
email_obj = email.message_from_bytes(raw_eml)
mapi = msg.MapiMessage.from_email_message(email_obj)
mapi.save("from_eml.msg")

Прохід контейнера CFB

Every .msg файл є контейнером Compound File Binary (CFB). CFBReader передбачає: Читання тільки доступ до дерева каталогів, дозволяючи вам перерахувати зберігання та потоки, ходити по ієрархію, а також витягувати нерозроблені байти потоку без покладатися на MsgReader.

from aspose.email_foss.cfb import CFBReader

with CFBReader.from_file("message.msg") as reader:
    print(f"CFB version  : {reader.major_version}")
    print(f"Sector size  : {reader.sector_size}")

    for depth, entry in reader.iter_tree():
        indent = "  " * depth
        size = entry.stream_size if entry.is_stream() else "-"
        print(f"{indent}{entry.name}  [size={size}]")

Виконання прикріплення

Додатки додаються через: MapiMessage.add_attachment() (для двоякісних даних) або MapiMessage.add_embedded_message_attachment() (для вкладених повідомлень MSG). прийняти ім’я файлу, сировини байтів та необхідний тип MIME.

message = msg.MapiMessage.create(“Attachment demo”, “See files below.”) message.add_attachment(“data.csv”, b"id,value\n1,100\n", mime_type=“text/csv”)

inner = msg.MapiMessage.create(“Nested message”, “This is embedded.”) message.add_embedded_message_attachment(inner, “nested.msg”) message.save(“with_attachments.msg”)


---

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

```bash
pip install aspose-email-foss>=26.3

Create and save a minimal MSG

message = msg.MapiMessage.create(“Hello World”, “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”)

Load it back and convert to EML

with msg.MapiMessage.from_file(“hello.msg”) as loaded: print(loaded.get_property_value(msg.PropertyId.SUBJECT)) eml = loaded.to_email_bytes() open(“hello.eml”, “wb”).write(eml)


---

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

| Format                        | Extension | Read | Write |
| ----------------------------- | --------- | ---- | ----- |
| Бінарний файл з компонуванням | `.cfb`    | ✓    | ✓     |
| Повідомлення Outlook          | `.msg`    | ✓    | ✓     |
| EML / RFC 5322                | `.eml`    | ✓    | ✓     |

---

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

Aspose.Email FOSS for Python is released under the MIT License. The source repository is доступний на: [github.com/aspose-email-foss (загальнення)](https://github.com/aspose-email-foss) і Пакет опублікований на PyPI як: `aspose-email-foss`.Коммерчне використання, модифікація та перерозподіл дозволений за умовами MIT.

---

## Починати з

- [Починати з](https://docs.aspose.org/email/python/getting-started/)
- [Посібник розробника](https://docs.aspose.org/email/python/developer-guide/)
- [Статті Бази знань](https://kb.aspose.org/email/python/)
- [Довідник API](https://reference.aspose.org/email/python/)