Frameworks

How to send email with Flask

Short answer

Flask has no built-in mail support. Install Flask-Mail, set MAIL_SERVER, MAIL_PORT, MAIL_USE_TLS or MAIL_USE_SSL, MAIL_USERNAME, MAIL_PASSWORD and MAIL_DEFAULT_SENDER, then build a Message and call mail.send(). Or skip the extension and post JSON to an email API with requests from your view. Render HTML with render_template and verify your sending domain with SPF, DKIM and DMARC.

Last checked 16 November 2026

Flask does not include email sending. You have two straightforward choices: add the Flask-Mail extension and send over SMTP, or call an email API from your view with requests. Both use Jinja templates for HTML, the same way you render pages.

Option 1: an email API with requests

No extension is needed. Put the call in a helper so every view sends the same way:

# app/email.py
import os
import requests
from flask import render_template

def send_email(to, subject, template, idempotency_key=None, **context):
    headers = {"Authorization": f"Bearer {os.environ['MAILCANDOR_KEY']}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key

    resp = requests.post(
        "https://api.mailcandor.com/v1/emails",
        headers=headers,
        json={
            "from": "Acme <hello@acme.com>",
            "to": to,
            "subject": subject,
            "html": render_template(f"emails/{template}.html", **context),
            "text": render_template(f"emails/{template}.txt", **context),
        },
        timeout=10,
    )
    if not resp.ok:
        error = resp.json()["error"]
        raise RuntimeError(f"{error['type']}: {error['message']}")
    return resp.json()["id"]

Then call it from a view:

# app/views.py
from flask import Blueprint, request, abort
from .email import send_email

bp = Blueprint("account", __name__)

@bp.post("/signup")
def signup():
    email = request.form.get("email", "")
    if "@" not in email:
        abort(400)
    # ... create the user ...
    send_email(email, "Welcome to Acme", "welcome", name=request.form.get("name"))
    return {"ok": True}

render_template needs an application context, which you have inside a view. The API returns 202 with an email id straight away; bounces and deliveries come later by webhook, which you can receive on another Flask route.

Option 2: Flask-Mail over SMTP

pip install Flask-Mail

Configuration

# app/__init__.py
import os
from flask import Flask
from flask_mail import Mail

mail = Mail()

def create_app():
    app = Flask(__name__)
    app.config.update(
        MAIL_SERVER="smtp.mailcandor.com",
        MAIL_PORT=587,
        MAIL_USE_TLS=True,
        MAIL_USE_SSL=False,
        MAIL_USERNAME="mailcandor",
        MAIL_PASSWORD=os.environ["MAILCANDOR_KEY"],
        MAIL_DEFAULT_SENDER=("Acme", "hello@acme.com"),
    )
    mail.init_app(app)
    return app

Set the config before calling init_app(): Flask-Mail reads it at that point. For port 465, use MAIL_PORT=465, MAIL_USE_SSL=True and MAIL_USE_TLS=False. The SMTP ports guide explains the difference.

Send a message

from flask import render_template
from flask_mail import Message
from . import mail

def send_welcome(user):
    msg = Message(
        subject="Welcome to Acme",
        recipients=[user.email],
        body=render_template("emails/welcome.txt", user=user),
    )
    msg.html = render_template("emails/welcome.html", user=user)
    mail.send(msg)

sender is optional when MAIL_DEFAULT_SENDER is set. A tuple such as ("Acme", "hello@acme.com") becomes Acme <hello@acme.com>.

Attachments

with open(invoice_path, "rb") as f:
    msg.attach("invoice-1042.pdf", "application/pdf", f.read())

Testing

During tests, set MAIL_SUPPRESS_SEND = True (Flask-Mail turns this on automatically when app.testing is true) and use mail.record_messages() to assert what would have been sent:

with mail.record_messages() as outbox:
    send_welcome(user)
    assert outbox[0].subject == "Welcome to Acme"

A contact form in Flask

For a public form, send to your own inbox and put the visitor’s address in reply-to:

@bp.post("/contact")
def contact():
    email = request.form.get("email", "")
    message = request.form.get("message", "")
    if "@" not in email or not message:
        abort(400)
    msg = Message(
        subject=f"Contact form: {email}",
        recipients=["team@acme.com"],
        reply_to=email,
        body=message,
    )
    mail.send(msg)
    return {"ok": True}

Keep user input in the text body; if you put it into HTML, Jinja’s autoescaping protects you only when you render it through a template. Add rate limiting (for example with Flask-Limiter) before the form goes live.

Do not block the request for bulk mail

Both options wait for a network round trip. That is fine for one email. For newsletters or reports to many users, hand the work to a queue such as Celery or RQ and return straight away.

Testing locally without sending

Point Flask-Mail at a local mail catcher during development by changing config only. Mailpit, for example, accepts SMTP on port 1025 and shows each message in a browser inbox:

app.config.update(MAIL_SERVER="localhost", MAIL_PORT=1025, MAIL_USE_TLS=False, MAIL_USERNAME=None, MAIL_PASSWORD=None)

Load the values from environment variables so development, staging and production differ only in their environment, not in code.

Sending from a CLI command or scheduled job

Flask commands registered with @app.cli.command() run inside an application context, so both render_template and mail.send work there. That makes a command a simple way to send a daily report from cron: flask send-report. For anything larger, a task queue gives you retries and a record of failures.

Common problems

  • SMTPAuthenticationError: the username or password is wrong. With Mailcandor the username is mailcandor and the password is your API key.
  • Timeouts on connect: your host blocks outbound SMTP ports. Try port 465 instead of 587, or switch to the API over port 443.
  • RuntimeError: Working outside of application context: you called render_template or mail.send from a thread or script with no app context. Wrap the call in with app.app_context():.
  • Emails from a background thread never send: the same app context issue. Push a context in the thread, or use a task queue that does it for you.
  • Mail lands in spam: check that the sender in MAIL_DEFAULT_SENDER is on a domain with SPF, DKIM and DMARC (see below).

Which should you choose?

Email API (requests) Flask-Mail (SMTP)
Packages requests Flask-Mail
Test helpers Mock the HTTP call record_messages() built in
Safe retries Idempotency keys Not built in
Delivery events Webhooks per email id Usually none
Best for New apps, serverless hosts Existing SMTP setups, simple sites

Both connect to the same account: the API uses your key as a bearer token, and the SMTP relay uses it as the password. The plain Python versions are in the Python email guide.

Before you send: verify your domain

Mail from a domain without SPF, DKIM and DMARC is likely to land in spam. Add your domain with your provider and publish the DNS records it gives you. The SPF, DKIM and DMARC guide explains what each record does.

Questions

What is Flask-Mail?

Flask-Mail is an extension that adds SMTP sending to Flask. It reads mail settings from app.config and gives you a Mail object and a Message class.

Should I use MAIL_USE_TLS or MAIL_USE_SSL?

MAIL_USE_TLS with port 587, which upgrades the connection with STARTTLS. MAIL_USE_SSL with port 465, which is encrypted from the start. Turn on only one.

Do I need Flask-Mail to send email from Flask?

No. You can call an email API with requests, or use Python's smtplib directly. Flask-Mail just makes SMTP configuration and testing tidier.

How do I send HTML email with a Jinja template in Flask?

Call render_template("emails/welcome.html", **context) and set the result as msg.html, or as the html field in an API request.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.