Tutorials7 min read
Sending Emails with Python
Send email from Python with the Emailit SDK or smtplib: a first email, Flask and FastAPI routes, a contact form, attachments, scheduling, safe retries, errors, Django over SMTP and webhooks.
GByGeorge

Python's standard library can already send email: smtplib speaks SMTP and email.message builds the message. What it can't do is deliver well on its own. You still need a server with a good reputation, authenticated domains, bounce handling and somewhere to see what happened to each message. An email service does that part, and with Emailit you can reach it either through its Python SDK or over SMTP.
This guide starts with the official emailit SDK: a first email, sending from Flask and FastAPI, a contact form, attachments, scheduling, retries that can't send twice and error handling. Then it shows the same send over SMTP, from plain smtplib and from Django, for code that already uses them.
Requirements
- Python 3.7 or later
- An Emailit account and an API key (a Sending Only key is enough to send)
- A verified sending domain, for example
acme.com
Until your workspace has production access, Emailit only delivers to the email addresses of your workspace members. Send your tests to yourself.
Install the SDK
pip install emailitThe SDK uses requests for HTTP and has no other dependencies.
Keep the API key out of your code
Set the key in the environment of your app, worker or container:
export EMAILIT_API_KEY=secret_xxxxxxxxxxxxxxxxRead it with os.environ["EMAILIT_API_KEY"], not os.getenv, so a missing key fails at startup instead of at the first send. Locally, python-dotenv can load it from a .env file; add that file to .gitignore.
Send your first email
Create one client and reuse it for every request:
# send.py
import os
from emailit import EmailitClient
client = EmailitClient(os.environ["EMAILIT_API_KEY"])
email = client.emails.send({
"from": "Acme <hello@acme.com>",
"to": "ada@example.com",
"subject": "Welcome to Acme",
"html": "<p>Thanks for signing up.</p>",
"text": "Thanks for signing up.",
})
print(email.id) # em_…Run it with python send.py. The email shows up under Email API > Emails in the dashboard within seconds, with its delivery timeline.
Always send a text part next to the html. Some recipients read plain text, and spam filters like to see both.
Send from a Flask route
In a real app the email is triggered by something a user does. Here's a sign-up route that sends a welcome email from a template:
# app.py
import os
from emailit import EmailitClient
from flask import Flask, request
app = Flask(__name__)
client = EmailitClient(os.environ["EMAILIT_API_KEY"])
@app.post("/signup")
def signup():
data = request.get_json()
# Create the user here, then send the welcome email.
sent = client.emails.send({
"from": "Acme <hello@acme.com>",
"to": data["email"],
"template": "welcome",
"variables": {"name": data.get("name", "")},
})
return {"email_id": sent.id}, 201template takes a template alias or ID, and variables fills in its placeholders. Your team can then change the wording in the dashboard without a deploy. See Templates.
Send a contact form
A contact form sends the message to you, not to the visitor. Put the visitor's address in reply_to, so pressing Reply in your inbox answers them:
@app.post("/contact")
def contact():
email = request.form.get("email", "")
message = request.form.get("message", "")
if "@" not in email or not message:
return "Please fill in your email and a message.", 400
client.emails.send({
"from": "Acme website <website@acme.com>",
"to": "support@acme.com",
"reply_to": email,
"subject": "New contact form message",
"text": f"From: {email}\n\n{message}",
})
return "Thanks, we will get back to you soon."Never put the visitor's address in from. You can only send from your own verified domain, and mailbox providers would reject mail that claims to come from someone else's.
Send from FastAPI
The SDK is synchronous. In an async framework, don't call it inside an async def endpoint, where it would block the event loop. Hand it to a background task instead, which also lets the response return right away:
# main.py
import os
from emailit import EmailitClient
from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel
app = FastAPI()
client = EmailitClient(os.environ["EMAILIT_API_KEY"])
class Signup(BaseModel):
email: str
def send_welcome(address: str) -> None:
client.emails.send({
"from": "Acme <hello@acme.com>",
"to": address,
"template": "welcome",
})
@app.post("/signup", status_code=201)
async def signup(body: Signup, tasks: BackgroundTasks):
# Create the user here.
tasks.add_task(send_welcome, body.email)
return {"ok": True}For bigger volumes, send from a task queue such as Celery or RQ, so a slow request or a retry never holds up your web workers.
Send attachments
Attachments are base64-encoded. Read the file, encode it and set the content type:
import base64
from pathlib import Path
pdf = Path("INV-1042.pdf").read_bytes()
client.emails.send({
"from": "Acme Billing <billing@acme.com>",
"to": "ada@example.com",
"subject": "Invoice INV-1042",
"text": "Your invoice is attached.",
"attachments": [
{
"filename": "INV-1042.pdf",
"content": base64.b64encode(pdf).decode(),
"content_type": "application/pdf",
}
],
})The same works for a PDF you generate in memory: encode its bytes the same way. Limits and inline images are in Attachments.
Schedule an email for later
Set scheduled_at to an ISO 8601 date, and Emailit holds the email until then:
reminder = client.emails.send({
"from": "Acme <reminders@acme.com>",
"to": "ada@example.com",
"subject": "Your appointment is tomorrow",
"text": "See you at 14:00.",
"scheduled_at": "2026-12-10T09:00:00Z",
})
# Plans changed? Move it, or cancel it before it goes out.
client.emails.update(reminder.id, {"scheduled_at": "2026-12-10T15:00:00Z"})
client.emails.cancel(reminder.id)Emailit renders the email and charges its credits when you make the request, so to change the content, cancel it and send a new one. Scheduling covers moving and canceling.
Retry without sending twice
When a request times out you can't tell whether the email went out, and retrying blindly can email your customer twice. Add an Idempotency-Key header, and Emailit answers every repeat of the same key with the first response instead of sending again. The SDK doesn't set this header, so make the call with requests:
import os
import requests
response = requests.post(
"https://api.emailit.com/v2/emails",
headers={
"Authorization": f"Bearer {os.environ['EMAILIT_API_KEY']}",
"Idempotency-Key": "order-1042-receipt",
},
json={
"from": "Acme <orders@acme.com>",
"to": "ada@example.com",
"subject": "Receipt for order 1042",
"text": "Thanks for your order.",
},
timeout=30,
)
response.raise_for_status()Build the key from something that identifies the email, such as the order number. A full retry loop is in Idempotency.
Handle errors
The SDK raises a typed exception for each kind of failure, so you can react to each one:
from emailit import (
ApiErrorException,
AuthenticationException,
RateLimitException,
UnprocessableEntityException,
)
try:
client.emails.send(message)
except RateLimitException:
# 429: wait and retry, for example from your task queue
raise
except AuthenticationException:
# 401: the API key is missing or wrong
raise
except UnprocessableEntityException as e:
# 422: for example, the from domain isn't verified yet
print(e.json_body)
except ApiErrorException as e:
print(e.http_status, e.json_body)All of them inherit from ApiErrorException, which carries the HTTP status in http_status and the parsed response in json_body.
Or send over SMTP
If your code already sends with smtplib, or your framework has an SMTP backend, you don't need the SDK. Point it at the Emailit SMTP relay, with your API key as the password.
With the standard library:
# send_smtp.py
import os
import smtplib
from email.message import EmailMessage
message = EmailMessage()
message["From"] = "Acme <hello@acme.com>"
message["To"] = "ada@example.com"
message["Subject"] = "Welcome to Acme"
message.set_content("Thanks for signing up.")
message.add_alternative("<p>Thanks for signing up.</p>", subtype="html")
with smtplib.SMTP("smtp.emailit.com", 587) as smtp:
smtp.starttls()
smtp.login("emailit", os.environ["EMAILIT_API_KEY"])
smtp.send_message(message)message.add_attachment() adds files the same way. In Django, set the SMTP backend in settings.py and keep using send_mail and EmailMessage as before:
# settings.py
import os
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.emailit.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "emailit"
EMAIL_HOST_PASSWORD = os.environ["EMAILIT_API_KEY"]
DEFAULT_FROM_EMAIL = "Acme <hello@acme.com>"If your network blocks port 587, use 2525 or 2587 with the same settings. Every SMTP setting is in the docs.
Which one should you pick? The SDK is one HTTPS request per email and gives you typed errors, templates and scheduling. SMTP is the quickest switch for code or a framework that already speaks it. Both land in the same dashboard, with the same logs and webhooks.
Know what happened to each email
To react when an email is delivered, bounces or gets a complaint, create a webhook. Emailit signs each request with an HMAC-SHA256 of the timestamp and the raw body, sent in the X-Emailit-Signature and X-Emailit-Timestamp headers, so check the signature against the raw bytes before you parse the JSON. The Python guide has a verification helper and complete routes for Flask and Django.
Get started
Install the SDK and send your first email in a minute:
pip install emailitThe free plan includes 3,000 emails a month, so you can try everything above without paying. The SDK source is on GitHub, and every endpoint is in the API reference.


