How to Create MSG Files in Python

How to Create MSG Files in Python

aspose-email-foss for Python lets you create Outlook MSG files programmatically without Microsoft Office.

Step-by-Step Guide

Step 1: Install the Package

pip install aspose-email-foss

Step 2: Create a Message

from aspose.email_foss.msg.message import MapiMessage

msg = MapiMessage.create("Meeting Notes", "Please review the attached notes.")

Step 3: Add Recipients

msg.add_recipient("alice@example.com", "Alice Smith", "to")
msg.add_recipient("bob@example.com", "Bob Jones", "cc")

Supported recipient types: "to", "cc", "bcc".


Step 4: Add Attachments

with open("notes.pdf", "rb") as f:
    msg.add_attachment("notes.pdf", f.read(), "application/pdf")

To embed another MSG message:

inner = MapiMessage.create("Forwarded", "Original message body")
msg.add_embedded_message_attachment(inner, "forwarded.msg", "application/vnd.ms-outlook")

Step 5: Save the MSG File

msg.save("output.msg")

Or get bytes for streaming:

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.