Guide · Python
How to send email with Flask
Send email from a Flask route by calling the Stack Emails API with requests.
Last reviewed November 2026
1. Set up
You need a Stack Emails API key (create one free) and a verified sending domain.
pip install flask requests
export STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Send your first email
import os
import requests
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.post("/signup")
def signup():
email = request.json.get("email")
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": email,
"subject": "Confirm your email",
"html": "<p>Click the link to confirm your account.</p>",
},
timeout=10,
)
if not res.ok:
return jsonify(error=res.json()["error"]["message"]), 502
return jsonify(ok=True)
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).
Prefer SMTP? Flask-Mail works with MAIL_SERVER = "smtp.stackemails.com", MAIL_PORT = 465, MAIL_USE_SSL = True, MAIL_USERNAME = "stackemails" and your API key as MAIL_PASSWORD.
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.