Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 149 ยท Data and the Web

Email with smtplib and email

Send email from Python. Build messages with EmailMessage, add HTML and attachments, connect securely with smtplib and test with a local debug server.

Almost every application eventually sends email: sign-up confirmations, password resets, invoices, nightly reports. Python's standard library covers all of it with two cooperating modules. The email package builds a message (headers, text, HTML, attachments) and smtplib delivers it to a mail server using SMTP, the Simple Mail Transfer Protocol.

Keeping those two jobs apart makes email easy to test: you can build and inspect a message with no network at all, and only the final "hand it to a server" step needs a real or fake mail server. In this lesson you'll build plain, HTML and multipart messages, add attachments, learn the secure ways to connect, and test safely without sending anything to real people. You'll also learn what to use in production instead of a hand-rolled script.

Note: The runnable examples below only build and inspect messages, because the in-browser Python has no network access. The code that connects to a server is shown in read-only blocks so you can copy it into a real project.

sequenceDiagram
    participant App as Your program
    participant Srv as SMTP server
    participant Box as Recipient's mailbox
    App->>Srv: connect (TLS)
    App->>Srv: login (username, password)
    App->>Srv: MAIL FROM / RCPT TO / message
    Srv-->>App: 250 accepted
    Srv->>Box: deliver

Your program talks to an SMTP server, which relays the message onward. Success means "accepted", not "read".

Building a message with EmailMessage

email.message.EmailMessage is the modern class. It behaves like a dictionary for headers and has methods for content:

Python A plain-text message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

set_content() fills in the body and sets sensible headers (Content-Type, Content-Transfer-Encoding) for you. Headers are case-insensitive. Assigning a header twice adds a second copy, so delete the old one (del msg["To"]) before replacing it. Always set a Subject, a From and at least one recipient.

Non-ASCII text just works, because EmailMessage chooses a suitable encoding (UTF-8, quoted-printable or base64) by itself:

Python Unicode in subject and body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

HTML emails and attachments

Most mail clients can show HTML, but some people read plain text only, and spam filters like a text version. The standard solution is multipart/alternative: a text body plus an HTML alternative. Call set_content() first, then add_alternative():

Python Text + HTML alternative

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Attachments use add_attachment(). You give it the data and the MIME type, split into maintype and subtype (for example text and csv; mimetypes.guess_type() can guess them from a file name), plus a file name:

Python Adding attachments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

flowchart TB
    M["multipart/mixed"] --> A["multipart/alternative"]
    M --> F1["attachment: sales.csv"]
    M --> F2["attachment: report.pdf"]
    A --> T["text/plain"]
    A --> H["text/html"]

A message with text, HTML and attachments is a tree of MIME parts. EmailMessage builds the wrapper parts for you.

To read a file from disk, use Path("report.pdf").read_bytes(). Never build an email by pasting raw user input into headers: a newline in a "name" field can inject extra headers. EmailMessage raises ValueError for headers containing line breaks, which protects you, but it is a good reason to use the modern class rather than hand-written strings.

Sending with smtplib

To deliver a message you connect to an SMTP server, authenticate and call send_message(). There are two ways to secure the connection:

  • Implicit TLS (smtplib.SMTP_SSL, usually port 465): the connection is encrypted from the first byte.
  • STARTTLS (smtplib.SMTP, usually port 587): connect in plain text, then upgrade with starttls() before sending the password.
Python
import os
import smtplib
import ssl
from email.message import EmailMessage

msg = EmailMessage()
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "Hello"
msg.set_content("Sent from Python.")

context = ssl.create_default_context()          # verifies the server certificate

# Option 1: STARTTLS on port 587
with smtplib.SMTP("smtp.example.com", 587, timeout=10) as server:
    server.starttls(context=context)
    server.login(os.environ["SMTP_USER"], os.environ["SMTP_PASSWORD"])
    server.send_message(msg)

# Option 2: implicit TLS on port 465
with smtplib.SMTP_SSL("smtp.example.com", 465, context=context, timeout=10) as server:
    server.login(os.environ["SMTP_USER"], os.environ["SMTP_PASSWORD"])
    server.send_message(msg)

Three habits matter here. Read credentials from environment variables or a secrets manager, never from source code. Always pass a timeout so a dead server doesn't hang your program. And use ssl.create_default_context() so the certificate is checked. Skipping verification means anyone on the network can read your mail and your password.

send_message() returns a dictionary of recipients the server refused (empty if all were accepted) and raises exceptions such as SMTPAuthenticationError, SMTPRecipientsRefused or SMTPServerDisconnected. Catch smtplib.SMTPException for any of them. Many providers (Gmail, Outlook and others) no longer accept your normal account password for scripts; they need an app password or OAuth.

Testing without sending real mail

Never test email code by mailing real addresses. There are three comfortable options.

1. Test the message, not the transport. Put message creation in its own function and assert on it. This needs no server at all:

Python Test message building

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Passing the server in as a parameter (dependency injection) lets you swap the real smtplib.SMTP for a fake like this one, or for unittest.mock. See Testing for more.

2. Run a local debug server. Python's old smtpd module was removed in Python 3.12. Today you use a small third-party server such as aiosmtpd, or an app like Mailpit that also gives you a web inbox. Both accept mail on a local port and never deliver it anywhere:

Terminal
pip install aiosmtpd
python -m aiosmtpd -n -l localhost:1025     # prints each message it receives

Then point your code at localhost:1025 without TLS or login:

Python
import smtplib

with smtplib.SMTP("localhost", 1025) as server:
    server.send_message(msg)

3. Use a sandbox service. Many email providers offer a test inbox that captures mail from your staging environment.

Production advice

A script is fine for notifications to yourself. For real user-facing mail, use a transactional email service (through its API or SMTP relay) and configure SPF, DKIM and DMARC records for your domain. Without them, big providers send your messages to spam. Send slowly and in a background job, since SMTP can take seconds per message. See Networking and Logging and Warnings for the surrounding skills, and your web framework's mail integration if you use one, such as the one in Web Development.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which standard-library class is the modern way to build an email?

    EmailMessage handles headers, encoding and attachments. smtplib only delivers messages; it doesn't build them.
  2. 2. How do you send both a plain-text and an HTML version of the same message?

    This creates a multipart/alternative message, and mail clients choose the best part they can show.
  3. 3. What must happen before you send a password over a STARTTLS connection?

    STARTTLS upgrades a plain connection to an encrypted one. Logging in before upgrading would send the password unencrypted.
  4. 4. Why is a fake SMTP object useful in tests?

    A fake records what was passed to send_message(), so tests are quick, offline and never email real people.

Summary

  • Use email.message.EmailMessage to build messages and smtplib to deliver them.
  • set_content() sets the body, add_alternative() adds HTML, and add_attachment() attaches files.
  • Connect with SMTP_SSL (port 465) or SMTP plus starttls() (port 587), with a default SSL context and a timeout.
  • Keep credentials in environment variables and prefer app passwords or API keys.
  • Test by inspecting messages, injecting a fake sender or running a local debug server; use a transactional email service and SPF/DKIM/DMARC in production.

Next: Project: Rock, Paper, Scissors, your first complete program.