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 import MapiMessage, RECIPIENT_TYPE_CC

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

Step 3: Add Recipients

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

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

To embed another MSG message:

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

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.

 English