email (standalone)
raw JSON → 4.0.2 verified Fri May 01 auth: no python
Standalone email package version 4.0.2. Originally part of Python's stdlib, now available as a standalone backport with improvements for modern Python. Provides classes for parsing, generating, and sending email messages, including MIME support. Release cadence is low (latest 4.0.2 from 2024).
pip install email Common errors
error AttributeError: 'str' object has no attribute 'as_string' ↓
cause Calling as_string() on a string (the message body) instead of the EmailMessage object.
fix
msg = EmailMessage(); msg.set_content('body'); print(msg.as_string())
error ImportError: cannot import name 'EmailMessage' from 'email' ↓
cause Using an old Python version (pre-3.6) where EmailMessage does not exist in stdlib.
fix
Use Python 3.6+ or install the 'email' backport and use 'from email.message import EmailMessage'.
error TypeError: expected string or bytes-like object ↓
cause Passing a non-string value to an email header (e.g., integer).
fix
Convert header values to strings before assignment.
Warnings
breaking In Python 3.6+, the 'email' stdlib module changed significantly. The standalone 'email' package (backport) may conflict with stdlib imports. Prefer using stdlib unless you need features from the backport. ↓
fix If you are using Python 3.6+, avoid installing the standalone 'email' package unless necessary, as it can shadow the stdlib module.
deprecated The old 'email.Message' class is deprecated. Use 'email.message.EmailMessage' instead. ↓
fix Replace 'from email.Message import Message' with 'from email.message import EmailMessage'.
gotcha When setting email headers, do not use the 'Message.__setitem__' method directly for multiple headers of the same name (e.g., 'Received'). Use 'Message.add_header' to add multiple values. ↓
fix Use msg.add_header('Received', 'from localhost') for repeated headers.
gotcha When attaching binary files, ensure you handle encoding correctly. For Python 3, use 'email.mime.base.MIMEBase' with 'Content-Transfer-Encoding: base64'. ↓
fix Example: part = MIMEBase('application', 'octet-stream'); part.set_payload(data); encode_base64(part).
Imports
- Message wrong
from email import Messagecorrectfrom email.message import EmailMessage - MIMEText wrong
from email import MIMETextcorrectfrom email.mime.text import MIMEText
Quickstart
from email.message import EmailMessage
msg = EmailMessage()
msg.set_content('Hello, world!')
msg['Subject'] = 'Test'
msg['From'] = 'you@example.com'
msg['To'] = 'recipient@example.com'
print(msg.as_string())