Almost every web app needs to send email: account verification, password resets, order notifications. If you call mail.send(msg) directly in a view, the request sits waiting for the SMTP server to reply — a few seconds is normal, and it times out completely if the mail server is slow. The fix: use Flask-Mail for the configuration, and do the actual sending in a background thread with an app context, so the request returns immediately. This pattern applies whenever an email is triggered by a request.
The problem
What many Flask beginners do is send the email right inside the view function. The code is correct, but the entire request freezes until the SMTP server replies. With Gmail, one send usually takes 2–10 seconds; on a flaky network the request can hang until the timeout and the user gets a 500 error — even though the email eventually went out, meaning you don’t know whether to retry.
from flask import Flask, request, jsonifyfrom flask_mail import Mail, Messageapp = Flask(__name__)app.config.update( MAIL_SERVER="smtp.gmail.com", MAIL_PORT=587, MAIL_USE_TLS=True, MAIL_USERNAME="you@gmail.com", MAIL_PASSWORD="mat-khau-ung-dung", # app password, not the regular password MAIL_DEFAULT_SENDER="you@gmail.com",)mail = Mail(app)@app.post("/register")def register(): # ... create user in the database ... msg = Message( subject="Xac minh tai khoan", recipients=[request.json["email"]], body="Nhan link sau de xac minh tai khoan cua ban...", ) mail.send(msg) # request stands still here for seconds, or times out return jsonify({"ok": True}), 201
The solution
Move the email sending into a background thread. The request returns right away while the email goes out quietly in the background. One thing to remember: the new thread doesn’t have Flask’s app context, but mail.send() reads its configuration from current_app — so you must create the app context manually inside the thread.
from threading import Threadfrom flask import current_appdef send_async_email(app, msg): with app.app_context(): # create an app context for the background thread mail.send(msg)def send_email(to, subject, body): msg = Message(subject=subject, recipients=[to], body=body) Thread( target=send_async_email, args=(current_app._get_current_object(), msg), ).start()@app.post("/register")def register(): # ... create user in the database ... send_email(request.json["email"], "Xac minh tai khoan", "Nhan link sau de xac minh tai khoan cua ban...") return jsonify({"ok": True}), 201 # returns immediately, email sent in the background
A few important configuration notes:
- Don’t enable TLS and SSL at the same time. Use
MAIL_USE_TLS=Truewith port 587 (STARTTLS, like Gmail), orMAIL_USE_SSL=Truewith port 465. Enabling both causes connection errors. - Gmail requires an app password. The account must have 2FA enabled, then create an “app password” in Google’s Security settings — SMTP login with the regular password is always rejected.
- Why
current_app._get_current_object()? In the background thread, thecurrent_appproxy is no longer attached to any request. Pass the real app object into the thread soapp_context()works correctly and contexts don’t leak between threads. - When testing, don’t spam a real inbox: set
MAIL_SUPPRESS_SEND=Truein the test environment config —mail.send()is skipped, but the rest of your code still runs normally.
Apply it to your project
Use this send_email() helper for every email triggered by a request: email verification, password resets, invoices, order notifications. Store all MAIL_* settings in environment variables per environment (dev/staging/prod) instead of hardcoding them. When email volume grows to a few thousand a day, upgrade from a thread to a real queue like Celery or RQ without changing the calling API — because your views call send_email() from exactly one place.
Related posts
- Flask: Using the Application Factory (create_app) so your app is easy to test and easy to extend from day one
- Flask: Managing config per environment (dev/staging/prod) — no more hardcoding SECRET_KEY
- Flask: Managing login with Flask-Login — login_required and remember me in 5 minutes
Frequently asked questions
Is a background thread safe when deploying with multiple workers?
Safe enough for small to medium volume. The downside: the thread lives inside the worker process, so if the server restarts exactly while an email is being sent, that email is lost. For important emails (account verification, password resets), switch to Celery or RQ when scaling, to get retries and a durable queue.
How do I detect an email failure inside the thread?
mail.send() raises an SMTPException when sending fails. Inside send_async_email, wrap it in try/except and log the error, or store the email status (pending / sent / failed) in the database so you have somewhere to look it up and resend.
Gmail reports an SMTP login error — how do I fix it?
It’s almost always the regular account password. Google has turned off “less secure apps” — you must enable two-step verification, then create a 16-character “app password” and use it for MAIL_PASSWORD.
What’s the difference between MAIL_USE_TLS and MAIL_USE_SSL?
MAIL_USE_TLS=True uses port 587: the connection starts in plaintext and is upgraded to encrypted via the STARTTLS command. MAIL_USE_SSL=True uses port 465: the connection is encrypted from the start. Pick the right port pair — a mismatched port is the most common connection error when setting up for the first time.
How do I test email sending without spamming a real inbox?
Set MAIL_SUPPRESS_SEND=True in the test environment config. mail.send() is skipped entirely, but your full message-building and calling logic still runs normally, so the test still has value.
References
- Flask-Mail documentation: pythonhosted.org/Flask-Mail
- Flask-Mail on PyPI: pypi.org/project/Flask-Mail
