To send email from Python, build a message with email.message.EmailMessage, open a connection with smtplib.SMTP to your provider on port 587, call starttls() to encrypt it, log in with login() and hand the message to send_message(). Port 465 uses implicit TLS instead, with smtplib.SMTP_SSL. Everything needed is in the standard library, so no packages are required.
This guide gives complete, runnable examples for plain text, HTML with a text fallback, and attachments, then covers timeouts, errors, credentials and sending at volume. The principles are the same for any SMTP server, including the one described in SMTP settings, ports and authentication.
Prerequisites
- An SMTP host, port, username and password from your provider or mail system. Use an app-specific or API-style credential, not your personal password.
- Python 3.6 or newer for
EmailMessagewith the modern policy. Any currently supported Python is fine. - Outbound access to the SMTP port. Many hosting and cloud networks block port 25; use 587 or 465. See which SMTP port to use.
- A From address on a domain you have authenticated with SPF and DKIM, or messages will land in spam. See authenticating your sending domain.
A minimal plain-text email over STARTTLS
import os
import smtplib
import ssl
from email.message import EmailMessage
SMTP_HOST = os.environ["SMTP_HOST"] # for example smtp.example.com
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
SMTP_USER = os.environ["SMTP_USER"]
SMTP_PASS = os.environ["SMTP_PASS"]
msg = EmailMessage()
msg["From"] = "Example App <[email protected]>"
msg["To"] = "[email protected]"
msg["Subject"] = "Your report is ready"
msg.set_content("Hello,\n\nYour report is ready to download.\n")
context = ssl.create_default_context()
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as server:
server.starttls(context=context)
server.login(SMTP_USER, SMTP_PASS)
server.send_message(msg)Points that matter: ssl.create_default_context() verifies the server certificate and host name, which you should never turn off to make an error disappear. The with block calls quit() for you. The client sends EHLO automatically before starttls() and again after it. Credentials come from the environment, not the source file.
Implicit TLS on port 465
context = ssl.create_default_context()
with smtplib.SMTP_SSL(SMTP_HOST, 465, context=context, timeout=30) as server:
server.login(SMTP_USER, SMTP_PASS)
server.send_message(msg)Here the TLS handshake happens immediately on connect, so there is no starttls() call. Calling starttls() on an SMTP_SSL connection, or connecting with plain SMTP to port 465, is the most common cause of hangs and "wrong version number" errors. The trade-offs between the two modes are covered in SMTP submission.
| Port | Class | TLS starts | Calls |
|---|---|---|---|
| 587 | smtplib.SMTP | After connect, through STARTTLS | starttls(), then login() |
| 465 | smtplib.SMTP_SSL | At connect | login() |
| 25 | smtplib.SMTP | Optional | Server to server; often blocked for clients |
HTML email with a plain-text alternative
msg = EmailMessage()
msg["From"] = "Example App <[email protected]>"
msg["To"] = "[email protected]"
msg["Subject"] = "Welcome"
msg.set_content("Welcome! Open this message in an HTML-capable client to see the full version.")
msg.add_alternative("""<html><body>
<h1>Welcome</h1>
<p>Your account is ready. <a href="https://example.com/start">Get started</a></p>
</body></html>""", subtype="html")Always set a text part with set_content() first and add the HTML with add_alternative(). This produces a multipart/alternative message, which spam filters and accessibility tools prefer over HTML only. See plain-text email. For non-ASCII text, EmailMessage chooses a suitable encoding automatically; you do not need to set one.
Adding attachments
from pathlib import Path
import mimetypes
def attach_file(msg, path):
path = Path(path)
ctype, encoding = mimetypes.guess_type(path.name)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
msg.add_attachment(path.read_bytes(),
maintype=maintype, subtype=subtype,
filename=path.name)
attach_file(msg, "invoice-1001.pdf")Attachments are base64 encoded, which makes them roughly a third larger on the wire, and providers cap total message size. Keep attachments small or send a link instead; limits and arithmetic are in email size limits and MIME. Do not use user-supplied file names without sanitising them.
Several recipients, Cc and Bcc
msg["To"] = "[email protected], [email protected]"
msg["Cc"] = "[email protected]"
msg["Bcc"] = "[email protected]"
server.send_message(msg) # uses To, Cc and Bcc, then removes Bcc from the sent copy
# Or be explicit about the envelope recipients:
server.send_message(msg, to_addrs=["[email protected]", "[email protected]"])send_message() reads recipients from the headers and strips Bcc before transmission. If one recipient is refused but others are accepted, send_message() returns a dict of failures instead of raising; check it. If all are refused, it raises SMTPRecipientsRefused. Never put many unrelated customers in one To header; send individual messages.
Handle errors and timeouts
import logging
log = logging.getLogger("mail")
try:
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as server:
server.starttls(context=ssl.create_default_context())
server.login(SMTP_USER, SMTP_PASS)
refused = server.send_message(msg)
if refused:
log.warning("Some recipients refused: %s", refused)
except smtplib.SMTPAuthenticationError as e:
log.error("Auth failed: %s %s", e.smtp_code, e.smtp_error) # 535
except smtplib.SMTPRecipientsRefused as e:
log.error("All recipients refused: %s", e.recipients)
except smtplib.SMTPResponseException as e:
# 4xx is temporary: retry later; 5xx is permanent: do not retry
log.error("SMTP %s: %s", e.smtp_code, e.smtp_error)
except (smtplib.SMTPException, OSError) as e:
log.error("Connection or protocol problem: %r", e)Always pass a timeout; without one a blocked connection can hang a worker indefinitely. Treat 4xx replies as temporary and retry with backoff, and 5xx as permanent. Retry design is covered in rate limits, retries and backoff, and the meaning of each code in SMTP bounce codes explained.
Troubleshooting
| Error or symptom | Likely cause | Fix |
|---|---|---|
| SMTPAuthenticationError 535 | Wrong credentials, or the server needs an app password or API key | Check username and password; see error 535 |
| SMTPServerDisconnected, connection unexpectedly closed | TLS mode mismatch | Use SMTP + starttls() on 587, SMTP_SSL on 465 |
| ssl.SSLError: WRONG_VERSION_NUMBER | Plain connection to an implicit TLS port, or the reverse | Match class to port |
| SSL: CERTIFICATE_VERIFY_FAILED | Host name does not match, or an interception proxy | Connect using the exact host name on the certificate; do not disable verification |
| TimeoutError or ConnectionRefusedError | Port blocked by a firewall or wrong host | Test with openssl s_client; try the other port |
| SMTPNotSupportedError: STARTTLS extension not supported | Server does not offer it on that port | Check you are on the submission port |
| Garbled characters | Header built by hand or wrong charset | Use EmailMessage and set text with set_content() |
| Sent but in spam | Missing SPF, DKIM or DMARC alignment | Authenticate the domain |
Credentials and security practices
- Load secrets from environment variables or a secrets manager. Never commit them. Rotate them if exposed; see key security and rotation.
- Never set
context.check_hostname = Falseorverify_mode = ssl.CERT_NONEin production. - Validate and strip user input that ends up in headers.
EmailMessagerejects embedded newlines in headers, which blocks header injection, but still validate addresses. - Use a distinct credential per application so you can revoke one without affecting others.
- Do not log full messages or credentials.
Sending at volume
The examples open one connection per message, which is fine for occasional mail. For many messages, reuse one connection in a loop and catch SMTPServerDisconnected to reconnect, keep the per-connection message count reasonable and respect your provider's rate limits. Do the sending in a background worker or queue, not inside a web request, so a slow server does not block users. For production systems, queueing, retries and idempotency are discussed in reliable email sending design. If you prefer HTTP, the same message can be posted to an email API instead; compare the two in SMTP versus API.
Debug the conversation
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as server:
server.set_debuglevel(1) # prints the full SMTP dialogue to stderr
server.starttls(context=ssl.create_default_context())
server.login(SMTP_USER, SMTP_PASS)
server.send_message(msg)With debug level 1 you can see the server banner, the extensions it advertises in reply to EHLO, the authentication exchange and the final response, including the queue identifier many servers return after DATA. Quote that identifier when you contact support. The output includes credentials in encoded form, so never paste it into a ticket without removing the AUTH lines. If the dialogue stops before STARTTLS, the problem is network reachability; if it stops during the handshake, the problem is TLS mode or certificates; if the server answers AUTH with 535, the credentials are the problem. Outside Python, you can reproduce the same conversation with the tools in testing an SMTP connection.
Test without sending real mail
During development, point the code at a local debugging server instead of a real provider. The third-party aiosmtpd package provides one that prints every received message to the terminal, and the standard smtpd module that older tutorials mention was removed in Python 3.12. Run it, set the host to localhost and the port to its port, skip starttls() and login(), and check the printed headers and body. Keep the host, port and credentials in configuration so the same code runs unchanged in staging and production, and use a clearly named test recipient list so you never mail real customers from a test run.
Before going live, send a message to a mailbox at one or two large providers and read the original headers. Confirm that SPF, DKIM and DMARC pass for your domain and that the From address matches what you intend. Add a unit test that builds the message object and asserts on headers and parts, since building the message is pure code and does not need a network.
Next steps
Start with the plain-text example against a test mailbox, then add the HTML part, then attachments, checking the raw message each time. Once it works, move credentials out of code, add timeouts and error handling, and authenticate your domain. If you use MigoSMTP, the host is smtp.migosmtp.com with port 587 (STARTTLS) or 465 (implicit TLS), and the examples above work unchanged with your account credentials.
Send your first message from Python Use the MigoSMTP relay with the settings above and track delivery events.
References and further reading
Frequently asked questions
How do I send an email with Python?
Create an EmailMessage, connect with smtplib.SMTP to your provider on port 587, call starttls(), log in and call send_message(). Use SMTP_SSL for port 465.
What is the difference between SMTP and SMTP_SSL in smtplib?
SMTP starts unencrypted and upgrades with starttls(), usually on port 587, while SMTP_SSL encrypts from the first byte, usually on port 465.
How do I send HTML email with Python?
Call set_content() with a plain-text version, then add_alternative() with the HTML and subtype="html". This creates a multipart/alternative message.
How do I attach a file?
Use msg.add_attachment() with the file bytes, a maintype and subtype such as application and pdf, and a filename.
Why do I get a certificate or wrong version error?
Usually the TLS mode does not match the port, or the host name does not match the certificate. Use SMTP with starttls() on 587 and SMTP_SSL on 465, and never disable verification.