Send with

Send email with Flask

Flask has no built-in mailer, and you do not need one: one HTTPS call sends the email.

Setup

pip install flask requests
export ROBUSTEMAIL_API_KEY="rb_test_..."

A helper

# email_client.py
import os

import requests

API = "https://robustemail.com/api/v2/emails"
session = requests.Session()


def send_email(email, idempotency_key=None):
    headers = {"Authorization": f"Bearer {os.environ['ROBUSTEMAIL_API_KEY']}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key

    res = session.post(API, json=email, headers=headers, timeout=15)
    body = res.json()
    if not res.ok:
        raise RuntimeError(f"{body['name']}: {body['message']}")
    return body["id"]

Send from a route

Render the HTML with a Jinja template. Templates ending in .html escape variables automatically.

# app.py
from flask import Flask, jsonify, render_template, request

from email_client import send_email

app = Flask(__name__)


@app.post("/signup")
def signup():
    data = request.get_json()
    user = create_user(data["email"], data["name"])  # your own code

    html = render_template("emails/welcome.html", name=user.name)
    email_id = send_email(
        {
            "from": "Acme <hello@acme.com>",
            "to": user.email,
            "subject": "Welcome to Acme",
            "html": html,
        },
        idempotency_key=f"welcome-user-{user.id}",
    )
    return jsonify(ok=True, email_id=email_id), 201
<!-- templates/emails/welcome.html -->
<h1>Welcome, {{ name }}!</h1>
<p>Thanks for signing up. Reply to this email if you need anything.</p>

Tips

  • Use a queue for anything slow. RQ or Celery can send in the background; pass the same idempotency key on every retry.
  • Keep the key on the server. Never send the API key to the browser.
  • Test first with a rb_test_ key or an address at sandbox.robustemail.dev. See Test mode.

Next