Frameworks

How to send email with Python

Short answer

Python can send email with only the standard library. Use smtplib with email.message.EmailMessage to talk to an SMTP server, adding an HTML alternative and attachments as needed, or post JSON to an email API with urllib.request (or requests). The API is simpler for app email and gives you delivery events. Either way, send from a domain with SPF, DKIM and DMARC so mail reaches the inbox.

Last checked 16 November 2026

Python ships everything you need to send email. smtplib talks to an SMTP server and email.message.EmailMessage builds the message, including HTML and attachments. If you would rather skip SMTP, an email API takes one JSON request, which urllib.request can make with no extra packages.

Option 1: an email API (standard library only)

This sends one email with urllib.request. It uses Mailcandor’s REST API; most JSON email APIs look much the same.

import json
import os
import urllib.error
import urllib.request

payload = {
    "from": "Acme <hello@acme.com>",
    "to": "sam@example.com",
    "subject": "Your login code",
    "html": "<p>Your code is <b>481 203</b></p>",
    "text": "Your code is 481 203",
}

req = urllib.request.Request(
    "https://api.mailcandor.com/v1/emails",
    data=json.dumps(payload).encode(),
    headers={
        "Authorization": f"Bearer {os.environ['MAILCANDOR_KEY']}",
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    with urllib.request.urlopen(req, timeout=10) as resp:
        print("queued", json.load(resp)["id"])
except urllib.error.HTTPError as e:
    error = json.load(e)["error"]
    raise RuntimeError(f"{error['type']}: {error['message']}") from e

The API answers 202 with an id as soon as the email is queued. Delivery, bounces and complaints arrive later as webhooks.

If you already use requests, the same call is shorter:

import os
import requests

resp = requests.post(
    "https://api.mailcandor.com/v1/emails",
    headers={"Authorization": f"Bearer {os.environ['MAILCANDOR_KEY']}"},
    json={
        "from": "Acme <hello@acme.com>",
        "to": ["sam@example.com"],
        "subject": "Your login code",
        "text": "Your code is 481 203",
    },
    timeout=10,
)
if not resp.ok:
    raise RuntimeError(resp.json()["error"]["message"])
print(resp.json()["id"])

Attachments through the API

Attachments go in the JSON as base64 strings:

import base64

with open("invoice-1042.pdf", "rb") as f:
    pdf = base64.b64encode(f.read()).decode()

payload["attachments"] = [
    {"filename": "invoice-1042.pdf", "content": pdf, "content_type": "application/pdf"}
]

Safe retries

Add an Idempotency-Key header with a value unique to the email, such as order-1042-receipt. If your code retries after a timeout, the API returns the first response instead of sending a second copy.

Option 2: smtplib and EmailMessage

EmailMessage builds a correct multipart message for you. Set the text body first, then add the HTML version and any attachments:

import os
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg["From"] = "Acme <hello@acme.com>"
msg["To"] = "sam@example.com"
msg["Subject"] = "Invoice 1042"

msg.set_content("Your invoice is attached.")
msg.add_alternative("<p>Your invoice is <b>attached</b>.</p>", subtype="html")

with open("invoice-1042.pdf", "rb") as f:
    msg.add_attachment(
        f.read(), maintype="application", subtype="pdf", filename="invoice-1042.pdf"
    )

with smtplib.SMTP_SSL("smtp.mailcandor.com", 465, timeout=10) as smtp:
    smtp.login("mailcandor", os.environ["MAILCANDOR_KEY"])
    smtp.send_message(msg)

send_message() reads the sender and recipients from the headers, including any Cc and Bcc, and strips Bcc before sending.

Port 587 with STARTTLS

If port 465 is blocked on your network, use port 587 and upgrade the connection before logging in:

import ssl

with smtplib.SMTP("smtp.mailcandor.com", 587, timeout=10) as smtp:
    smtp.starttls(context=ssl.create_default_context())
    smtp.login("mailcandor", os.environ["MAILCANDOR_KEY"])
    smtp.send_message(msg)

Never call login() before starttls() on port 587, or your password crosses the network unencrypted. The SMTP ports guide explains 25, 465 and 587.

Sending many emails over one connection

Opening a new SMTP connection per email is slow. Inside one with block you can call send_message() repeatedly, which reuses the login. Keep batches modest and handle smtplib.SMTPException per message so one bad address does not stop the rest.

Using a framework?

Django, Flask and FastAPI each wrap these same two options in their own way:

  • Django: built-in send_mail() with SMTP settings.
  • Flask: the Flask-Mail extension, or a plain API call.
  • FastAPI: an async API call with httpx in a background task.

Testing without sending real email

During development, point smtplib at a local mail catcher instead of a real server. Mailpit, for example, listens for SMTP on port 1025 and shows every message in a web inbox:

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

No login or TLS is needed for a local catcher. Switch host, port and credentials with environment variables so the same code sends for real in production.

Sending with Gmail from Python

For a personal script, smtplib.SMTP_SSL("smtp.gmail.com", 465) works with your Gmail address as the username and an app password, which Google only offers on accounts with 2-Step Verification. Your normal password is rejected. Gmail caps daily sending, so use a transactional provider once real users depend on the mail.

Common errors and what they mean

Error Usual cause Fix
SMTPAuthenticationError (535) Wrong username or password Check the credentials; with Mailcandor the username is mailcandor and the password is the API key
ssl.SSLError: WRONG_VERSION_NUMBER Port and TLS mode do not match SMTP_SSL on 465, SMTP plus starttls() on 587
TimeoutError or connection refused Your network or host blocks the SMTP port Try the other port, or use the API over port 443
SMTPSenderRefused The from address is not allowed Send from an address on your verified domain
HTTPError 4xx from the API Bad key or a field the API rejected Read error.message and error.field in the response

Always set a timeout on both smtplib and urlopen. Without one, a stalled connection blocks your program indefinitely.

Which should you choose?

Email API smtplib
Packages None (urllib) or requests None
Message building JSON fields EmailMessage and MIME parts
Safe retries Idempotency keys Not built in
Delivery events Webhooks per email id Usually none
Best for App email, scripts in the cloud Tools that must speak SMTP, internal relays

Before you send: verify your domain

Receiving servers check that the domain in your From header has SPF, DKIM and DMARC records. Without them, mail goes to spam or is rejected, no matter how you send it. Add your domain with your provider and publish the DNS records it gives you; the SPF, DKIM and DMARC guide explains each one.

Questions

What is smtplib?

smtplib is Python's built-in SMTP client. It opens a connection to a mail server, logs in and hands over a message. You build the message itself with the email package, usually email.message.EmailMessage.

How do I send an HTML email with an attachment in Python?

Create an EmailMessage, call set_content() with the text version, add_alternative(html, subtype="html") for the HTML, and add_attachment() with the file bytes, then send it with smtplib.

Should I use SMTP_SSL or starttls()?

Use smtplib.SMTP_SSL on port 465, where TLS starts immediately. Use smtplib.SMTP on port 587 and call starttls() before login. Both encrypt the connection.

Can I send email from Python with Gmail?

Yes, through smtp.gmail.com with an app password on an account with 2-Step Verification. It suits scripts and testing, not app email at volume.

Is there an email API for Python that needs no SDK?

Yes. Any JSON email API works with urllib.request from the standard library or with requests. You send one POST with the sender, recipient, subject and body.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.