How to Send Email in Python: smtplib, Django and API
Pranav Patel
Co-founderยท12 min read
On this page

Send email from Python with smtplib, Django, FastAPI or Flask, or with an email API. Copy-paste examples for HTML email, attachments, background sending and retries without duplicates.
Python can send email with the built-in smtplib module, no install needed. For anything in production, send through a provider: either over SMTP with smtplib or your framework's mail settings, or over HTTPS with an email API SDK.
This guide covers plain smtplib, the Reloop Python SDK, Django, FastAPI and Flask, then the production details: attachments, background sending and safe retries.
Working in JavaScript? See how to send email in Node.js.
Which approach should you use?
smtplib / framework SMTPpip install reloop-emailEmailMessage, MIME partshtml, text, attachmentsSMTPException subclassessend_mailIf you are wiring up Django's built-in auth emails or a third-party package, use SMTP settings. If you are writing the send call yourself, use the API.
Prerequisites
- Python 3.9 or later
- A verified sending domain with SPF, DKIM and DMARC
- An API key from the Reloop dashboard. Keys start with
rl_, and the same key works for the API and SMTP.
export RELOOP_API_KEY=rl_your_api_keyKeep the key in the environment or a secrets manager, never in your code or git.
Method 1: Send email with smtplib
Use EmailMessage from the standard library. It handles encoding, headers and multipart bodies for you, so you do not need the older MIMEMultipart and MIMEText classes.
1import os2import smtplib3from email.message import EmailMessage4
5msg = EmailMessage()6msg["From"] = "Acme <hello@mail.acme.com>"7msg["To"] = "user@example.com"8msg["Subject"] = "Welcome to Acme"9
10# Plain-text body first, then the HTML alternative11msg.set_content("Welcome! Thanks for signing up.")12msg.add_alternative(13 "<h1>Welcome!</h1><p>Thanks for signing up.</p>",14 subtype="html",15)16
17with smtplib.SMTP("smtp.reloop.sh", 587, timeout=30) as server:18 server.starttls()19 server.login("reloop", os.environ["RELOOP_API_KEY"])20 server.send_message(msg)The username can be any string. The password is your API key.
When port 587 is blocked
Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the port number changes:
1with smtplib.SMTP("smtp.reloop.sh", 2587, timeout=30) as server:2 server.starttls()3 server.login("reloop", os.environ["RELOOP_API_KEY"])4 server.send_message(msg)Reloop does not offer implicit TLS on port 465, so do not use smtplib.SMTP_SSL with it. If the connection hangs or times out, see SMTP ports explained.
Handle SMTP errors
1try:2 with smtplib.SMTP("smtp.reloop.sh", 587, timeout=30) as server:3 server.starttls()4 server.login("reloop", os.environ["RELOOP_API_KEY"])5 server.send_message(msg)6except smtplib.SMTPAuthenticationError:7 print("Wrong API key")8except smtplib.SMTPRecipientsRefused as e:9 print("Rejected recipients:", e.recipients)10except (smtplib.SMTPException, OSError) as e:11 print("Send failed:", e)Can I send with Gmail from Python?
For a personal script, yes: use smtp.gmail.com on port 587 with an App Password. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.
Method 2: Send email with the Python SDK
Install
pip install reloop-emailSend an email
1import os2from reloop_email import Reloop3
4reloop = Reloop(api_key=os.environ["RELOOP_API_KEY"])5
6result = reloop.mail.send({7 "from": "Acme <hello@mail.acme.com>",8 "to": "user@example.com",9 "subject": "Welcome to Acme",10 "html": "<h1>Welcome!</h1><p>Thanks for signing up.</p>",11 "text": "Welcome! Thanks for signing up.",12})13
14if result.email_error:15 print("Failed:", result.email_error.status, result.email_error)16else:17 print("Sent:", result.response["id"])The SDK returns errors instead of raising them. Every call gives you a result with either response or email_error. Network failures come back with status 0. If you prefer exceptions, raise result.email_error: it is an Exception subclass.
Create the client once at startup and reuse it. It keeps an HTTP connection pool open. Call reloop.close() on shutdown, or use it as a context manager in scripts:
with Reloop(api_key=os.environ["RELOOP_API_KEY"]) as reloop: reloop.mail.send({...})Send to several recipients
1reloop.mail.send({2 "from": "Acme <hello@mail.acme.com>",3 "to": ["ada@example.com", "grace@example.com"],4 "cc": "team@acme.com",5 "reply_to": "support@acme.com",6 "subject": "Your weekly report",7 "text": "Here is your report.",8 "tags": [{"name": "type", "value": "weekly_report"}],9})Every address in to sees the others. For personalised mail, send one message per recipient.
Send a stored template
Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:
1reloop.mail.send({2 "from": "Acme <hello@mail.acme.com>",3 "to": "user@example.com",4 "subject": "Welcome to Acme",5 "template": {6 "id": "tmpl_welcome",7 "variables": {"first_name": "Ada", "plan": "Pro"},8 },9})See templates for variables and defaults.
Django
Django's mail functions work with any SMTP provider. Add these settings and send_mail, password reset emails and admin error emails all go through Reloop:
1import os2
3EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"4EMAIL_HOST = "smtp.reloop.sh"5EMAIL_PORT = 5876EMAIL_USE_TLS = True7EMAIL_HOST_USER = "reloop"8EMAIL_HOST_PASSWORD = os.environ["RELOOP_API_KEY"]9DEFAULT_FROM_EMAIL = "Acme <hello@mail.acme.com>"10SERVER_EMAIL = "errors@mail.acme.com"Keep EMAIL_USE_SSL off: Reloop uses STARTTLS, not implicit TLS. If 587 is blocked, set EMAIL_PORT = 2587.
1from django.core.mail import EmailMultiAlternatives2
3message = EmailMultiAlternatives(4 subject="Welcome to Acme",5 body="Welcome! Thanks for signing up.",6 to=["user@example.com"],7)8message.attach_alternative("<h1>Welcome!</h1>", "text/html")9message.send()In development, set EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" to print emails to the terminal instead of sending them. Full example: Django guide.
FastAPI
The SDK is synchronous. Declare the route with def, not async def, and FastAPI runs it in a thread pool so it does not block the event loop:
1import os2from fastapi import FastAPI, HTTPException3from pydantic import BaseModel, EmailStr4from reloop_email import Reloop5
6app = FastAPI()7reloop = Reloop(api_key=os.environ["RELOOP_API_KEY"])8
9class Contact(BaseModel):10 email: EmailStr11 message: str12
13@app.post("/contact")14def contact(body: Contact):15 result = reloop.mail.send({16 "from": "Acme Website <contact@mail.acme.com>",17 "to": "support@acme.com",18 "reply_to": body.email,19 "subject": f"New message from {body.email}",20 "text": body.message,21 })22 if result.email_error:23 raise HTTPException(status_code=502, detail="Could not send message")24 return {"id": result.response["id"]}The visitor's address goes in reply_to, never in from. You can only send from your verified domain, and putting someone else's domain in from fails DMARC.
To return before the email is sent, use BackgroundTasks:
1from fastapi import BackgroundTasks2
3@app.post("/signup")4def signup(email: EmailStr, tasks: BackgroundTasks):5 # ... create the user ...6 tasks.add_task(reloop.mail.send, {7 "from": "Acme <hello@mail.acme.com>",8 "to": email,9 "subject": "Welcome to Acme",10 "text": "Thanks for signing up.",11 })12 return {"ok": True}BackgroundTasks is lost if the process restarts. For emails that must arrive, use a real queue (see below). Full example: FastAPI guide.
Flask
1import os2from flask import Flask, request, jsonify3from reloop_email import Reloop4
5app = Flask(__name__)6reloop = Reloop(api_key=os.environ["RELOOP_API_KEY"])7
8@app.post("/contact")9def contact():10 data = request.get_json()11 result = reloop.mail.send({12 "from": "Acme Website <contact@mail.acme.com>",13 "to": "support@acme.com",14 "reply_to": data["email"],15 "subject": "New contact form message",16 "text": data["message"],17 })18 if result.email_error:19 return jsonify(error="Could not send message"), 50220 return jsonify(id=result.response["id"])Prefer SMTP with Flask-Mail? Use the same host, port and credentials as the Django settings above. Full example: Flask guide.
Attachments
With the SDK, pass base64 content:
1import base642from pathlib import Path3
4pdf = Path("invoice-1042.pdf").read_bytes()5
6reloop.mail.send({7 "from": "Acme Billing <billing@mail.acme.com>",8 "to": "user@example.com",9 "subject": "Your invoice #1042",10 "text": "Your invoice is attached.",11 "attachments": [{12 "filename": "invoice-1042.pdf",13 "content": base64.b64encode(pdf).decode(),14 "content_type": "application/pdf",15 }],16})With smtplib, use add_attachment:
1msg.add_attachment(2 pdf,3 maintype="application",4 subtype="pdf",5 filename="invoice-1042.pdf",6)Keep attachments small. Many inboxes reject messages over 25 MB, and large files hurt deliverability. For big files, send a signed download link.
Send in the background with Celery
Sending inside a web request adds latency and fails the request when the provider is slow. Move it to a worker and let the queue handle retries:
1import os2from celery import Celery3from reloop_email import Reloop4
5app = Celery("tasks", broker=os.environ["REDIS_URL"])6reloop = Reloop(api_key=os.environ["RELOOP_API_KEY"])7
8class RetryableSendError(Exception):9 pass10
11@app.task(12 autoretry_for=(RetryableSendError,),13 retry_backoff=True,14 max_retries=5,15)16def send_welcome(email: str) -> str:17 result = reloop.mail.send({18 "from": "Acme <hello@mail.acme.com>",19 "to": email,20 "subject": "Welcome to Acme",21 "text": "Thanks for signing up.",22 })23 if result.email_error:24 status = result.email_error.status25 if status == 0 or status == 429 or status >= 500:26 raise RetryableSendError(str(result.email_error))27 raise result.email_error # 4xx: do not retry28 return result.response["id"]Retry network errors (status 0), 429 and 5xx. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time.
Retries without duplicate emails
A request times out and your task retries. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original result instead of sending again.
The SDK does not set this header yet, so call the endpoint with httpx (already installed with the SDK):
1import os2import httpx3
4def send_receipt(order_id: str, to: str) -> dict:5 res = httpx.post(6 "https://reloop.sh/api/mail/v1/send",7 headers={8 "x-api-key": os.environ["RELOOP_API_KEY"],9 "Idempotency-Key": f"receipt-{order_id}",10 },11 json={12 "from": "Acme <orders@mail.acme.com>",13 "to": to,14 "subject": f"Receipt for order {order_id}",15 "text": "Thanks for your order.",16 },17 timeout=30,18 )19 res.raise_for_status()20 return res.json()Base the key on the business event (receipt-{order_id}), not a new UUID per attempt, so retries from any worker are safe.
Testing without sending real email
- Django: the test runner swaps in the
locmembackend automatically. Assert ondjango.core.mail.outbox. - Anything else: mock the client in unit tests, and send to test addresses in staging so you do not hurt your sender reputation with bounces.
- Local SMTP: run Mailpit with
docker run -p 1025:1025 -p 8025:8025 axllent/mailpitand pointsmtplib.SMTP("localhost", 1025)at it, withoutstarttls()orlogin(). Openhttp://localhost:8025to see the messages.
Production checklist
- API key in an environment variable or secrets manager
- Sending domain verified with SPF, DKIM and DMARC
-
fromon your verified domain; user addresses inreply_to - Both HTML and plain-text bodies
- One shared client, created at startup
- Sending in a worker (Celery, RQ, Dramatiq), not the request
- Retries only on network errors,
429and5xx - Idempotency keys on anything that retries
- Webhooks for bounces and complaints
- Disposable addresses blocked at signup (how)
FAQ
Build an EmailMessage, call set_content with the plain-text version, then add_alternative with your HTML and subtype="html". With the Reloop SDK, pass html and text keys in the send dict.
SMTP connects in plain text and you call starttls() to upgrade, which is what port 587 expects. SMTP_SSL starts TLS immediately, which is what port 465 expects. Using the wrong one for the port makes the connection hang or fail with an SSL error.
The Reloop Python SDK is synchronous. In FastAPI, declare routes with def so they run in the thread pool, or call the HTTP API directly with httpx.AsyncClient from async code.
Usually the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and always include a plain-text body.
Yes. Set the SMTP settings shown above and every email Django sends, including password resets and admin error reports, goes through Reloop with no code changes.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


