Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 72 ยท Structure and Configuration

Sending Email with Flask-Mail

Send email from Flask with Flask-Mail. Configure SMTP, build plain and HTML messages, add attachments, send in the background, test with record_messages and avoid header injection.

Sooner or later every web app has to send email: a welcome message, a password-reset link, an order receipt, a weekly digest. Flask-Mail is a small extension that wraps Python's smtplib and email modules so that building and sending a message takes a few lines and fits into Flask's configuration and testing.

In this lesson you will configure an SMTP server, send plain-text and HTML messages, attach files, send without blocking the request, and (most importantly) test email code without ever sending a real message.

How email leaves your app

flowchart LR
    A["Your Flask view"] --> B["Flask-Mail<br/>Message + Mail.send()"]
    B --> C["SMTP server<br/>(your provider)"]
    C --> D["Recipient's<br/>mail server"]
    D --> E["Inbox"]

Your app only talks SMTP to one server. Delivery to the recipient is that server's job.

Your app does not deliver email itself. It hands each message to an SMTP server: a transactional-email provider (Amazon SES, Postmark, Mailgun, SendGrid, Brevo and similar), your company's mail server, or for development a local catcher such as MailHog or Mailpit that shows messages in a web page and never delivers them. Home-made delivery from your own web server usually lands in spam, so use a real provider in production.

Installing and configuring

TEXT
pip install flask-mail

All options live in app.config. Load the secret ones from the environment (see Configuration); never commit a password.

Key Meaning Typical value
MAIL_SERVER SMTP host smtp.example.com
MAIL_PORT SMTP port 587 (STARTTLS) or 465 (SSL)
MAIL_USE_TLS upgrade with STARTTLS True with port 587
MAIL_USE_SSL TLS from the first byte True with port 465
MAIL_USERNAME, MAIL_PASSWORD credentials from the environment
MAIL_DEFAULT_SENDER the From address if a message has none ("Shop", "[email protected]")
MAIL_SUPPRESS_SEND do not really send (tests) True when TESTING is on

Use either MAIL_USE_TLS or MAIL_USE_SSL, never both, and never send passwords over an unencrypted connection.

Python
import os
from flask import Flask
from flask_mail import Mail

mail = Mail()                       # created once, bound later with init_app

def create_app():
    app = Flask(__name__)
    app.config.update(
        MAIL_SERVER=os.environ.get("MAIL_SERVER", "localhost"),
        MAIL_PORT=int(os.environ.get("MAIL_PORT", 1025)),   # Mailpit/MailHog default
        MAIL_USE_TLS=os.environ.get("MAIL_USE_TLS") == "1",
        MAIL_USERNAME=os.environ.get("MAIL_USERNAME"),
        MAIL_PASSWORD=os.environ.get("MAIL_PASSWORD"),
        MAIL_DEFAULT_SENDER=("Shop", "[email protected]"),
    )
    mail.init_app(app)
    return app

Creating Mail() without the app and calling init_app is the same pattern as for every extension in the application factory.

A message and a send

A Message has a subject, recipients, a plain-text body and optionally an HTML version in html. Email clients that can show HTML use it; others fall back to the text. Always provide both.

The example below runs without a mail server. app.testing = True (which sets MAIL_SUPPRESS_SEND) stops delivery, and mail.record_messages() captures what would have been sent so you can inspect it.

Python Build and send a message (captured, not delivered)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two things to notice. The sender came from MAIL_DEFAULT_SENDER, so views never repeat it. And the second message shows that Jinja's autoescape (render_template_string escapes values in HTML templates) protects an HTML email from injected markup, just as it does for web pages. In a real project keep the templates in templates/email/welcome.txt and welcome.html and call render_template(...).

Never put user-supplied text into the subject, recipients or other headers without checking it for newlines. A value such as x\nBcc: [email protected] can inject extra headers (header injection). Flask-Mail rejects line breaks in the common fields, but validate email addresses on input anyway (see validation).

Attachments

msg.attach(filename, content_type, data) adds a file. The data must be bytes; build them in memory or read a file with app.open_resource. Keep attachments small: many providers cap a message at 10 to 25 MB, and for large files a download link is kinder.

Python Attach a generated CSV

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Do not make the visitor wait

Talking to an SMTP server can take a second or more, and it can fail. A view that sends mail directly makes the user wait and shows an error if the provider hiccups. Three common remedies:

  1. A background thread. Easy, fine for low volume, but if the process dies the email is lost. Remember to pass a real app object and push a context inside the thread:
Python
from threading import Thread

def send_async(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email(msg):
    app = current_app._get_current_object()   # the real app, not the proxy
    Thread(target=send_async, args=(app, msg)).start()
  1. A task queue such as Celery, RQ or Huey, which retries failures and survives restarts. This is the right choice for anything important (see Async Views and Background Tasks).
  2. A provider's HTTP API (SES, Postmark and others) through its own library, which is often faster than SMTP. Flask-Mail is only one option.

Bulk sending is cheaper over one connection: with mail.connect() as conn: for msg in messages: conn.send(msg).

Testing email code

Because MAIL_SUPPRESS_SEND is on while TESTING is on, tests never send anything. Use record_messages() to assert on the content, as in the examples above:

Python
def test_welcome_email(app, client):
    with mail.record_messages() as outbox:
        client.post("/register", data={"email": "[email protected]", "password": "long-secret"})
        assert len(outbox) == 1
        assert outbox[0].recipients == ["[email protected]"]
        assert "confirm" in outbox[0].body.lower()

For manual checks, run Mailpit or MailHog locally, point MAIL_SERVER=localhost and MAIL_PORT=1025 at it, and read the messages in its browser UI. More on this style in Testing Flask Apps.

Good email hygiene

  • Send from a domain you own and set up SPF, DKIM and DMARC DNS records, or messages land in spam.
  • Send transactional mail (receipts, resets) and marketing mail from different addresses or providers.
  • Put an unsubscribe link in anything that is not strictly transactional.
  • Password-reset and confirmation links must contain single-use, expiring tokens, never the user id (see password hashing and web security).
  • Do not log whole messages: they may contain tokens and personal data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Flask app send mail to?

    Flask-Mail speaks SMTP to the server in MAIL_SERVER. That server is responsible for delivery.
  2. 2. Which pair of settings should you NOT enable at the same time?

    STARTTLS (port 587) and implicit SSL (port 465) are two different ways to encrypt. Use the one your provider documents.
  3. 3. How can a test check that a view sent an email without sending it?

    With TESTING on, nothing is delivered. record_messages() is a context manager that collects every Message that would have been sent.
  4. 4. Why should sending email usually not happen directly in the request?

    Move the send to a worker or queue and return the response immediately; use retries for important messages.

Summary

  • Flask-Mail builds Message objects and sends them to an SMTP server configured with MAIL_* keys; credentials come from the environment.
  • Provide both a text body and an html version, render them from templates, and rely on autoescape for user data.
  • msg.attach(name, mimetype, bytes) adds files; keep them small.
  • Send in the background (thread for small apps, a task queue for important mail).
  • Test with TESTING = True and mail.record_messages(); use Mailpit or MailHog for manual checks.
  • Set up SPF, DKIM and DMARC, and use single-use expiring tokens in links.

Next: let non-developers manage data and add more languages with Flask-Admin and Flask-Babel.