Compose Email Messages without Sending
Core idea
EmailMessage builds structured messages with headers, text bodies and attachments. MIME content types describe how parts should be interpreted. set_content sets a text body; add_attachment creates an attachment part. as_bytes serializes the message; SMTP delivery is a separate operation and is not used here.
from email.message import EmailMessagem = EmailMessage()m['From']='sender@example.test'm['To']='reader@example.test'm['Subject']='Daily inventory'm.set_content('Ready')print(m['Subject'])print(m.get_content().strip())print(m.get_content_type())Headers and body can be inspected without delivery.
Add a binary attachment
from email.message import EmailMessagem = EmailMessage()m.set_content('Report attached')m.add_attachment(b'abc', maintype='application', subtype='octet-stream', filename='report.bin')part = next(m.iter_attachments())print(m.is_multipart(), part.get_filename())print(part.get_content())The attachment preserves its decoded binary payload and filename metadata.
Common mistake
Composition is not delivery. Do not construct raw headers by joining untrusted text; validate addresses and use message APIs. Attachment filenames are metadata, not trusted filesystem paths.
Practice
Build a message with Persian body text and verify get_content returns the text; inspect the serialized bytes without sending them.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Email message composition
Check your understanding of email message composition.
What is printed?
from email.message import EmailMessagem=EmailMessage();m.set_content('ok')print(m.get_content_type())What is printed?
from email.message import EmailMessagem=EmailMessage();m['Subject']='Update'print(m['Subject'])What does as_bytes do?
Which method adds a file part?