On this page
  1. email
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Multipart Plain-Text + HTML Message with Attachment
  7. 2. Parsing Raw RFC 5322 Bytes with policy.default
  8. Gotchas & Boundaries
  9. Common Functions

email

Prev: doctest | Up: stdlib_module | Next: encodings
Rel: json, mailbox, mimetypes, base64, binascii
Ref: docs.python.org — email
Tags: #public #python3 #stdlib


Import

import email

Overview

Full MIME and RFC 5322 email message parser and builder (email.message.EmailMessage, email.parser, email.policy.default). Always use the modern EmailMessage class with policy=email.policy.default (rather than legacy MIMEText/MIMEMultipart) for clean UTF-8 headers, HTML alternatives, and attachments.

Quick Start

from email.message import EmailMessage

msg = EmailMessage()
msg["Subject"] = "Release v0.1.0"
msg["From"] = "releases@example.org"
msg["To"] = "team@example.org"
msg.set_content("Plain-text summary of the release.")

assert msg["Subject"] == "Release v0.1.0"
assert "Plain-text summary" in msg.get_content()

Implementation Walkthrough

1. Multipart Plain-Text + HTML Message with Attachment

from email.message import EmailMessage

msg = EmailMessage()
msg["Subject"] = "Weekly Report"
msg["From"] = "bot@example.org"
msg["To"] = "ada@example.org"
msg.set_content("See the attached CSV report.")
msg.add_alternative("<p>See the attached <b>CSV</b> report.</p>", subtype="html")
msg.add_attachment(b"name,score\nAda,98\n", maintype="text", subtype="csv", filename="report.csv")
assert msg.is_multipart()

2. Parsing Raw RFC 5322 Bytes with policy.default

import email
from email import policy

raw = b"From: ada@example.org\r\nSubject: Hello\r\n\r\nBody text.\r\n"
parsed = email.message_from_bytes(raw, policy=policy.default)
assert parsed["Subject"] == "Hello"
assert parsed.get_body(preferencelist=("plain",)).get_content().strip() == "Body text."

Gotchas & Boundaries

Common Functions

Linked from

Related notes