Guide · Python
How to send email with Python
Send email from Python with the requests library and the Stack Emails API, or with the standard library's smtplib over SMTP.
Last reviewed November 2026
1. Set up
You need a Stack Emails API key (create one free) and a verified sending domain.
pip install requests
export STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Send your first email
import os
import requests
res = requests.post(
"https://stackemails.com/v1/emails",
headers={"Authorization": f"Bearer {os.environ['STACKEMAILS_API_KEY']}"},
json={
"from": "Acme <hello@mail.acme.com>",
"to": "ada@example.com",
"subject": "Welcome to Acme",
"html": "<p>Thanks for signing up!</p>",
},
timeout=10,
)
res.raise_for_status()
print("Queued", res.json()["id"])
A successful request returns 202 with the message id, for example { "id": "msg_5b1f0c6c2a8e4e0f", "status": "queued" }. Errors return a JSON body with error.code and error.message (see errors).
3. Or send over SMTP with smtplib
import os
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "Acme <hello@mail.acme.com>"
msg["To"] = "ada@example.com"
msg["Subject"] = "Welcome to Acme"
msg.set_content("Thanks for signing up!")
msg.add_alternative("<p>Thanks for signing up!</p>", subtype="html")
with smtplib.SMTP_SSL("smtp.stackemails.com", 465) as smtp:
smtp.login("stackemails", os.environ["STACKEMAILS_API_KEY"])
smtp.send_message(msg)
Sending an attachment
import base64
with open("invoice.pdf", "rb") as f:
pdf = base64.b64encode(f.read()).decode()
payload["attachments"] = [{"filename": "invoice.pdf", "content": pdf}]
Production checklist
- Keep the API key in an environment variable or secret manager, never in client-side code.
- Add an
Idempotency-Keyheader to retries so a timeout never sends twice (idempotency). - Subscribe to webhooks for bounces and complaints.
- Check your domain's SPF, DKIM and DMARC records.
- Start from a tested email template for password resets, receipts and invites.