How to Create MSG Files in Python
This guide shows how to create Outlook MSG files from scratch in Python using MapiMessage.create(), add recipients and attachments, and save the result — without requiring Microsoft Office.
Step-by-Step Guide
Step 1: Install the Package
Install the Aspose.Email FOSS package from PyPI using the pip command below:
pip install aspose-email-fossStep 2: Create a Message
Call MapiMessage.create() with a subject string and body text to instantiate a new message object:
from aspose.email_foss.msg import MapiMessage, RECIPIENT_TYPE_CC
msg = MapiMessage.create("Meeting Notes", "Please review the attached notes.")Step 3: Add Recipients
Call add_recipient() with an email address, optional display name, and recipient type constant (RECIPIENT_TYPE_TO, RECIPIENT_TYPE_CC, or RECIPIENT_TYPE_BCC):
msg.add_recipient("alice@example.com", display_name="Alice Smith")
msg.add_recipient("bob@example.com", display_name="Bob Jones", recipient_type=RECIPIENT_TYPE_CC)Use the integer constants RECIPIENT_TYPE_TO (1), RECIPIENT_TYPE_CC (2), or RECIPIENT_TYPE_BCC (3) from aspose.email_foss.msg.
Step 4: Add Attachments
Call add_attachment() with the filename, binary file contents, and the MIME type to attach a file to the message:
with open("notes.pdf", "rb") as f:
msg.add_attachment("notes.pdf", f.read(), mime_type="application/pdf")To embed another MSG as a nested attachment, use add_embedded_message_attachment():
inner = MapiMessage.create("Forwarded", "Original message body")
msg.add_embedded_message_attachment(inner, filename="forwarded.msg", mime_type="application/vnd.ms-outlook")Step 5: Save the MSG File
Call msg.save() with a file path to write the message to disk as a .msg file:
msg.save("output.msg")To get the serialized bytes for in-memory use or streaming without writing a file, call to_bytes() instead:
data = msg.to_bytes()Common Issues and Fixes
Empty recipients in saved file
Ensure you call add_recipient() before save(). Recipients are written during serialization.
Attachment not showing in Outlook
Verify the MIME type is correct. Use "application/octet-stream" as a fallback for unknown file types.
Frequently Asked Questions (FAQ)
Can I set HTML body?
Yes. Use msg.body_html = "value" to set the HTML body after creation.
Can I convert the MSG to EML format?
Yes. Call msg.to_email_string() to get the RFC 5322 representation.
Maximum message size?
There is no hard limit. CFB v3 supports files up to 2 GB; v4 supports larger files.