Sending email
suggest changePython's standard library has everything you need to send email:
email.message.EmailMessagebuilds the message: headers, plain text and HTML bodies, attachments.smtplibconnects to an SMTP server (your mail provider, a company relay, or a service like Amazon SES, SendGrid, Mailgun or Postmark) and hands the message over.
No third-party packages are required. This article uses the modern EmailMessage API (Python 3.6+). Old tutorials build messages with MIMEMultipart, MIMEText and MIMEBase from email.mime; that still works, but it's more verbose and easier to get wrong.
A local SMTP server for testing
While developing you don't want to send real emails. Install aiosmtpd and run a debugging server that prints every message it receives instead of delivering it:
pip install aiosmtpd
python -m aiosmtpd -n -l localhost:8025
The examples below connect to localhost:8025. In production you replace it with your provider's host, port and credentials.
Sending a plain text email
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "alice@example.com"
msg["To"] = "bob@example.com"
msg["Subject"] = "Hello from Python"
msg.set_content("Hi Bob,\n\nThis email was sent with smtplib.\n\nAlice")
with smtplib.SMTP("localhost", 8025) as smtp:
smtp.send_message(msg)
print("sent")
The debugging server prints the message exactly as it was received:
---------- MESSAGE FOLLOWS ----------
From: alice@example.com
To: bob@example.com
Subject: Hello from Python
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
X-Peer: ('::1', 52423, 0, 0)
Hi Bob,
This email was sent with smtplib.
Alice
------------ END MESSAGE ------------
A few things to notice:
- Headers are set by indexing the message like a dict. Assigning the same header twice adds a second header rather than replacing it. Use
del msg["Subject"]ormsg.replace_header("Subject", "...")to change one. set_content()sets the body and fills inContent-Type,Content-Transfer-EncodingandMIME-Versionfor you.send_message()reads the sender and recipients from theFrom,To,CcandBccheaders.- Using
SMTPas a context manager sendsQUITand closes the connection at the end of the block.
Connecting to a real server: TLS and login
Real mail servers require an encrypted connection and authentication. There are two ways to get encryption:
| Port | Method | smtplib |
|---|---|---|
| 587 | Plain connection upgraded with STARTTLS |
smtplib.SMTP + starttls() |
| 465 | TLS from the first byte ("implicit TLS") | smtplib.SMTP_SSL |
Port 587 with STARTTLS is the most widely supported:
import os
import smtplib
import ssl
from email.message import EmailMessage
SMTP_HOST = os.environ["SMTP_HOST"] # e.g. smtp.gmail.com
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
SMTP_USER = os.environ["SMTP_USER"]
SMTP_PASSWORD = os.environ["SMTP_PASSWORD"]
msg = EmailMessage()
msg["From"] = SMTP_USER
msg["To"] = "bob@example.com"
msg["Subject"] = "Sent over TLS"
msg.set_content("This message was sent over an encrypted connection.")
context = ssl.create_default_context() # verifies the server certificate
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as smtp:
smtp.starttls(context=context)
smtp.login(SMTP_USER, SMTP_PASSWORD)
smtp.send_message(msg)
With implicit TLS on port 465 the connection is encrypted from the start, so there is no starttls() call:
with smtplib.SMTP_SSL(SMTP_HOST, 465, context=context, timeout=30) as smtp:
smtp.login(SMTP_USER, SMTP_PASSWORD)
smtp.send_message(msg)
Tips:
- Always pass
context=ssl.create_default_context(). It checks the certificate and host name, so nobody can intercept your password. - Always set a
timeout. Without one a stuck server can block your program forever. - Never hard-code passwords. Read them from environment variables or a secrets manager.
- Gmail and Outlook.com don't accept your normal account password over SMTP. With Gmail you enable 2-step verification and create an app password. Transactional email services give you an SMTP user name and an API key to use as the password.
- Call
smtp.set_debuglevel(1)before sending to print the whole SMTP conversation. It's the fastest way to see why a server rejects you.
Names and non-ASCII text
You can put a display name in an address header as a string, but email.headerregistry.Address builds it correctly and handles quoting:
from email.headerregistry import Address
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = Address("Zoë Müller", "zoe", "example.com")
msg["To"] = [Address("Bob", addr_spec="bob@example.com"), "carol@example.com"]
msg["Subject"] = "Grüße aus Python"
msg.set_content("Ünïcödé in the body works too.")
print(msg["From"])
print(msg["To"])
print(msg.as_string().split("\n\n")[0])
Output:
Zoë Müller <zoe@example.com>
Bob <bob@example.com>, carol@example.com
From: =?utf-8?q?Zo=C3=AB_M=C3=BCller?= <zoe@example.com>
To: Bob <bob@example.com>, carol@example.com
Subject: =?utf-8?q?Gr=C3=BC=C3=9Fe?= aus Python
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64
MIME-Version: 1.0
Non-ASCII headers are automatically encoded (RFC 2047) when the message is serialized, and the body is sent as UTF-8 (here base64-encoded, because it contains non-ASCII characters). You never need to encode anything by hand.
HTML email with a plain text fallback
Always send a plain text version alongside HTML. Some clients show only text, and spam filters penalize HTML-only messages. Call set_content() for the text and then add_alternative() for the HTML:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "shop@example.com"
msg["To"] = "bob@example.com"
msg["Subject"] = "Your order has shipped"
msg.set_content("""\
Hi Bob,
Your order #1234 has shipped.
Track it here: https://example.com/track/1234
""")
msg.add_alternative("""\
<html>
<body>
<p>Hi Bob,</p>
<p>Your order <b>#1234</b> has shipped.</p>
<p><a href="https://example.com/track/1234">Track your package</a></p>
</body>
</html>
""", subtype="html")
for part in msg.walk():
print(part.get_content_type())
with smtplib.SMTP("localhost", 8025) as smtp:
smtp.send_message(msg)
Output:
multipart/alternative
text/plain
text/html
add_alternative() turns the message into multipart/alternative, and the email client picks the last part it can display, which is the HTML one. Email clients support only a limited subset of HTML and CSS: use tables for layout and inline style="..." attributes, not external stylesheets or JavaScript.
If you build HTML from user data, escape it with html.escape() or use a template engine such as Jinja2 with auto-escaping enabled.
Attachments
add_attachment() adds a file. For binary data you have to pass the MIME type; mimetypes.guess_type() works it out from the file name:
import mimetypes
import smtplib
from email.message import EmailMessage
from pathlib import Path
def attach_file(msg: EmailMessage, path: Path) -> None:
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# unknown or compressed (e.g. .tar.gz): send as generic binary
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
msg.add_attachment(path.read_bytes(), maintype=maintype,
subtype=subtype, filename=path.name)
msg = EmailMessage()
msg["From"] = "reports@example.com"
msg["To"] = "bob@example.com"
msg["Subject"] = "Monthly report"
msg.set_content("The monthly report is attached.")
attach_file(msg, Path("report.csv"))
attach_file(msg, Path("chart.png"))
for part in msg.walk():
print(part.get_content_type(), part.get_filename() or "")
with smtplib.SMTP("localhost", 8025) as smtp:
smtp.send_message(msg)
Output:
multipart/mixed
text/plain
text/csv report.csv
image/png chart.png
The attachment is base64-encoded and gets a Content-Disposition: attachment; filename="report.csv" header. You can attach data generated in memory the same way, without writing a file first: pass any bytes object plus a filename.
Most servers limit message size (often 10 to 25 MB), and base64 makes attachments about 33% bigger. For large files, upload them somewhere and send a link.
Inline images
To show an image inside the HTML body (a logo, a chart) instead of as a separate attachment, add it as a related part of the HTML and reference it by its Content-ID:
from email.message import EmailMessage
from email.utils import make_msgid
from pathlib import Path
msg = EmailMessage()
msg["From"] = "reports@example.com"
msg["To"] = "bob@example.com"
msg["Subject"] = "Sales chart"
msg.set_content("Your email client doesn't display HTML. The chart is attached.")
chart_cid = make_msgid(domain="example.com") # '<...@example.com>'
msg.add_alternative(f"""\
<html><body>
<p>This week's sales:</p>
<img src="cid:{chart_cid[1:-1]}" alt="sales chart">
</body></html>
""", subtype="html")
html_part = msg.get_payload()[1]
html_part.add_related(Path("chart.png").read_bytes(),
maintype="image", subtype="png", cid=chart_cid)
for part in msg.walk():
print(part.get_content_type())
Output:
multipart/alternative
text/plain
multipart/related
text/html
image/png
make_msgid() returns an ID wrapped in angle brackets. The Content-ID header keeps the brackets, but the cid: URL in the HTML must not have them, hence chart_cid[1:-1].
Multiple recipients, Cc and Bcc
To and Cc accept comma-separated strings or lists. send_message() delivers to everyone in To, Cc and Bcc, and removes the Bcc header from the transmitted copy so recipients can't see it:
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "reports@example.com"
msg["To"] = ["bob@example.com", "dave@example.com"]
msg["Cc"] = "carol@example.com"
msg["Bcc"] = "audit@example.com"
msg["Subject"] = "Team update"
msg.set_content("...")
with smtplib.SMTP("localhost", 8025) as smtp:
smtp.send_message(msg)
The server is told to deliver to all 4 addresses, but the received message has only To and Cc headers.
The addresses in the headers and the envelope (who the server actually delivers to) are separate things. To control the envelope explicitly, for example to send a copy to an archive address that isn't in any header, pass from_addr and to_addrs:
smtp.send_message(msg, from_addr="bounces@example.com",
to_addrs=["bob@example.com", "archive@example.com"])
from_addr becomes the return path: bounces for undeliverable addresses go there.
Don't put hundreds of people in To for a newsletter: everyone sees everyone else's address. Send one message per recipient instead.
Sending many emails over one connection
Opening a connection, negotiating TLS and logging in takes time. When sending a batch, reuse one connection:
import smtplib
from email.message import EmailMessage
users = [("Bob", "bob@example.com"), ("Carol", "carol@example.com")]
with smtplib.SMTP("localhost", 8025) as smtp:
for name, addr in users:
msg = EmailMessage()
msg["From"] = "news@example.com"
msg["To"] = addr
msg["Subject"] = "Weekly newsletter"
msg.set_content(f"Hi {name}, here is what's new this week.")
smtp.send_message(msg)
print("sent to", addr)
Output:
sent to bob@example.com
sent to carol@example.com
Providers limit how many messages per minute or per day you may send. For large volumes, add rate limiting and retries, or use a transactional email service.
Handling errors
send_message() returns a dict of recipients the server refused. It raises an exception only if all recipients were refused or something else went wrong:
import smtplib
from email.message import EmailMessage
def send(msg: EmailMessage, host: str, port: int) -> None:
try:
with smtplib.SMTP(host, port, timeout=10) as smtp:
refused = smtp.send_message(msg)
except smtplib.SMTPAuthenticationError as e:
print("bad credentials:", e.smtp_code, e.smtp_error.decode())
except smtplib.SMTPRecipientsRefused as e:
print("all recipients refused:", e.recipients)
except smtplib.SMTPException as e:
print("SMTP error:", type(e).__name__, e)
except OSError as e: # connection refused, DNS failure, timeout
print("network error:", type(e).__name__, e)
else:
if refused:
print("some recipients refused:", refused)
else:
print("delivered to server")
msg = EmailMessage()
msg["From"] = "alice@example.com"
msg["Subject"] = "Test"
msg.set_content("Hello")
msg["To"] = "bob@example.com, nobody@bad.example.com"
send(msg, "localhost", 8025)
msg.replace_header("To", "nobody@bad.example.com")
send(msg, "localhost", 8025)
send(msg, "localhost", 9999) # nothing listens here
Output, with a server that rejects addresses at bad.example.com:
some recipients refused: {'nobody@bad.example.com': (550, b'5.1.1 No such user')}
all recipients refused: {'nobody@bad.example.com': (550, b'5.1.1 No such user')}
network error: ConnectionRefusedError [Errno 111] Connection refused
The order of the except clauses matters: SMTPAuthenticationError and SMTPRecipientsRefused are subclasses of SMTPException, and TimeoutError and ConnectionRefusedError are subclasses of OSError.
"Delivered to server" only means your SMTP server accepted the message. The final delivery can still fail later, and you'll find out from a bounce email sent to the return path.
Sending email asynchronously
smtplib is blocking. In an asyncio application (FastAPI, aiohttp, a bot) use aiosmtplib (pip install aiosmtplib), which takes the same EmailMessage objects:
import asyncio
from email.message import EmailMessage
import aiosmtplib
def make_message(to: str) -> EmailMessage:
msg = EmailMessage()
msg["From"] = "alice@example.com"
msg["To"] = to
msg["Subject"] = "Async hello"
msg.set_content(f"Hi {to}!")
return msg
async def main() -> None:
recipients = ["bob@example.com", "carol@example.com", "dave@example.com"]
results = await asyncio.gather(*(
aiosmtplib.send(make_message(r), hostname="localhost", port=8025)
for r in recipients
))
for r, (errors, response) in zip(recipients, results):
print(r, "->", response)
asyncio.run(main())
Output:
bob@example.com -> OK
carol@example.com -> OK
dave@example.com -> OK
For a real server pass username=, password= and start_tls=True (port 587) or use_tls=True (port 465).
In a web application, don't send email inside the request handler. SMTP servers can be slow, and a failure shouldn't break the request. Put the job on a task queue (Celery, RQ, arq) or at least run it as a background task.
Saving and loading messages
A message can be written to an .eml file, which any email client can open. This is handy for previewing generated emails:
from email import message_from_bytes
from email.message import EmailMessage
from email.policy import default
from pathlib import Path
msg = EmailMessage()
msg["From"] = "alice@example.com"
msg["To"] = "bob@example.com"
msg["Subject"] = "Draft"
msg.set_content("Saved as .eml")
Path("draft.eml").write_bytes(msg.as_bytes())
loaded = message_from_bytes(Path("draft.eml").read_bytes(), policy=default)
print(loaded["Subject"])
print(loaded.get_content())
Output:
Draft
Saved as .eml
Pass policy=default when parsing. Without it you get the legacy Message class, which lacks get_content() and doesn't decode headers.
Testing code that sends email
In tests, run an aiosmtpd server in a background thread and check what it received:
import smtplib
import socket
from email import message_from_bytes
from email.message import EmailMessage
from email.policy import default
import pytest
from aiosmtpd.controller import Controller
class CollectingHandler:
def __init__(self):
self.messages = []
async def handle_DATA(self, server, session, envelope):
msg = message_from_bytes(envelope.content, policy=default)
self.messages.append((envelope.rcpt_tos, msg))
return "250 OK"
def free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
@pytest.fixture
def smtp_server():
handler = CollectingHandler()
controller = Controller(handler, hostname="127.0.0.1", port=free_port())
controller.start()
yield controller, handler
controller.stop()
def send_welcome(host: str, port: int, to: str) -> None:
msg = EmailMessage()
msg["From"] = "noreply@example.com"
msg["To"] = to
msg["Subject"] = "Welcome!"
msg.set_content("Thanks for signing up.")
with smtplib.SMTP(host, port) as smtp:
smtp.send_message(msg)
def test_send_welcome(smtp_server):
controller, handler = smtp_server
send_welcome(controller.hostname, controller.port, "bob@example.com")
[(rcpt, msg)] = handler.messages
assert rcpt == ["bob@example.com"]
assert msg["Subject"] == "Welcome!"
assert "Thanks for signing up." in msg.get_content()
This tests the real SMTP conversation without sending anything over the internet. If your code receives its mailer as a parameter, you can also substitute a fake in unit tests; see Dependency injection.
Deliverability
Code that sends successfully isn't the same as email that lands in the inbox. If your messages end up in spam:
- Send from a domain you control, through a server that is allowed to send for it. Set up SPF, DKIM and DMARC DNS records. Transactional email services walk you through this.
- Make the
Fromaddress match the domain you authenticate as. - Include a plain text part, a meaningful
Subject, and for bulk mail an unsubscribe link and aList-Unsubscribeheader. - Don't send from a home IP address. Many ISPs block outgoing port 25, and most receivers distrust residential IPs.