To send email from Flask, install Flask-Mail, set the MAIL_SERVER, MAIL_PORT, MAIL_USERNAME and MAIL_PASSWORD configuration values, enable exactly one of MAIL_USE_TLS (port 587, STARTTLS) or MAIL_USE_SSL (port 465, implicit TLS), create a Message and call mail.send(msg). Load credentials from environment variables and send in the background so requests do not wait for the SMTP server.
This guide gives a complete application factory setup, HTML and template messages, attachments, background sending, tests, and a table of the errors you are most likely to meet. If you prefer to use the standard library directly, the same ideas apply to sending email with Python smtplib.
Install and configure
pip install Flask-Mail# config.py
import os
class Config:
MAIL_SERVER = os.environ["MAIL_SERVER"] # for example smtp.example.com
MAIL_PORT = int(os.environ.get("MAIL_PORT", "587"))
MAIL_USE_TLS = os.environ.get("MAIL_USE_TLS", "true").lower() == "true" # STARTTLS, port 587
MAIL_USE_SSL = os.environ.get("MAIL_USE_SSL", "false").lower() == "true" # implicit TLS, port 465
MAIL_USERNAME = os.environ["MAIL_USERNAME"]
MAIL_PASSWORD = os.environ["MAIL_PASSWORD"]
MAIL_DEFAULT_SENDER = ("Example App", "[email protected]")
MAIL_MAX_EMAILS = None
MAIL_SUPPRESS_SEND = False| Setting | Meaning | Notes |
|---|---|---|
| MAIL_SERVER, MAIL_PORT | SMTP host and port | Defaults are localhost and 25, which is rarely what you want |
| MAIL_USE_TLS | Upgrade the connection with STARTTLS | Use with port 587 |
| MAIL_USE_SSL | TLS from the first byte | Use with port 465; never together with MAIL_USE_TLS |
| MAIL_USERNAME, MAIL_PASSWORD | Credentials | Read from the environment |
| MAIL_DEFAULT_SENDER | Used when a message has no sender | A string or a (name, address) tuple |
| MAIL_SUPPRESS_SEND | Do not actually send | Defaults to the app.testing value |
| MAIL_DEBUG | Print the SMTP dialogue | Defaults to the app debug value; keep off in production |
| MAIL_MAX_EMAILS | Messages per connection | Reconnects after this many |
| MAIL_ASCII_ATTACHMENTS | Convert attachment file names to ASCII | Off by default |
Flask-Mail's defaults describe a local server on port 25 without encryption, so a missing setting does not raise an error; it simply fails to connect, or sends unencrypted to the wrong place. Set every value explicitly. Setting both MAIL_USE_TLS and MAIL_USE_SSL to true is a configuration error and produces handshake failures. Choose the port and mode with SMTP settings, ports and authentication in mind, and note that settings available in Flask-Mail can differ between releases, so check the documentation for the version you install.
Use the application factory pattern
# app/extensions.py
from flask_mail import Mail
mail = Mail()
# app/__init__.py
from flask import Flask
from .extensions import mail
from config import Config
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
mail.init_app(app)
return appCreating Mail() without an app and calling init_app() avoids circular imports and lets tests build an app with a different configuration. Flask-Mail needs an application context when it sends; inside a request you already have one.
Send a message
from flask import Blueprint, request, jsonify
from flask_mail import Message
from .extensions import mail
bp = Blueprint("contact", __name__)
@bp.post("/contact")
def contact():
data = request.get_json(force=True)
msg = Message(
subject="New website enquiry",
recipients=["[email protected]"],
reply_to=data["email"],
body=f"From: {data['name']} <{data['email']}>\n\n{data['message']}",
)
mail.send(msg)
return jsonify(ok=True)The visitor's address goes in reply_to, not in the sender: the From address stays on a domain you have authenticated, which keeps SPF, DKIM and DMARC working and avoids looking like spoofing. Validate the input before building the message, and never put unvalidated user input in the subject or addresses; header injection is covered in header injection. Add rate limiting and bot protection to public forms.
HTML, templates and attachments
from flask import render_template, current_app
def send_welcome(user):
msg = Message(subject="Welcome to Example", recipients=[user.email])
msg.body = render_template("email/welcome.txt", user=user)
msg.html = render_template("email/welcome.html", user=user)
with current_app.open_resource("static/guide.pdf") as fp:
msg.attach("guide.pdf", "application/pdf", fp.read())
mail.send(msg)Provide both body and html; the result is a multipart/alternative message, which spam filters and accessibility tools handle better than HTML alone. Jinja escapes variables in the HTML template, which protects against markup injection from user data. Keep email HTML simple, since support for CSS is far narrower than in browsers; see email CSS support. For inline images, msg.attach() accepts a headers argument where you can set a Content-ID, and Flask-Mail documents the form.
Send in the background
from threading import Thread
from flask import current_app
def _send_async(app, msg):
with app.app_context():
try:
mail.send(msg)
except Exception:
app.logger.exception("Email send failed")
def send_email_async(msg):
app = current_app._get_current_object()
Thread(target=_send_async, args=(app, msg), daemon=True).start()A thread is the simplest approach and is acceptable for low volume, but it has no retries, loses messages if the process restarts and cannot be monitored. For anything important, push a job to a queue such as Celery or RQ, and let the worker build and send the message with retries for temporary failures. Pass identifiers (a user id), not full objects, into the job. Queue and retry design is covered in reliable email sending design.
Test without sending
def test_contact_sends_email(app, client):
with mail.record_messages() as outbox:
res = client.post("/contact", json={"name": "Asha", "email": "[email protected]", "message": "Hello"})
assert res.status_code == 200
assert len(outbox) == 1
assert outbox[0].subject == "New website enquiry"
assert outbox[0].reply_to == "[email protected]"When app.testing is true, MAIL_SUPPRESS_SEND defaults to true, so no real connection is made, and record_messages() captures what would have been sent. For manual checks in development, point MAIL_SERVER at a local catch-all server such as Mailpit or MailHog, with TLS and credentials turned off.
Send several messages over one connection
def send_digest(messages):
with mail.connect() as conn: # one connection, one login
for msg in messages:
conn.send(msg)By default mail.send() opens a connection, authenticates, sends and closes. For a batch, mail.connect() returns a context manager that reuses one connection, and MAIL_MAX_EMAILS controls how many messages it carries before reconnecting. This saves a TLS handshake and a login for every message, which matters when you send hundreds. Providers limit the rate and the number of messages per connection, so keep the batch modest, run it from a worker and slow down when the server answers with a temporary 4xx reply. Do not put many unrelated recipients on one message; send one message per recipient so addresses stay private and personalisation works.
Handle errors in a way you can act on
import smtplib
try:
mail.send(msg)
except smtplib.SMTPAuthenticationError:
app.logger.error("SMTP login rejected: check MAIL_USERNAME and MAIL_PASSWORD")
except smtplib.SMTPRecipientsRefused as e:
app.logger.warning("Recipients refused: %s", e.recipients)
except (smtplib.SMTPException, OSError) as e:
app.logger.exception("Mail transport problem: %r", e)Flask-Mail uses the standard library smtplib underneath, so the exceptions are the ones from that module. Authentication failures and refused recipients are not worth retrying blindly: the first needs a configuration fix and the second means the address is bad, so record it and stop mailing it. Connection problems and 4xx replies are temporary and suit a retry with growing delays. Log the outcome and a reference to your own record (such as an order id), never the password or the full message body. Remember that a successful send() means the server accepted the message, not that it reached the inbox; bounces and complaints arrive afterwards and should feed a suppression list.
Security checklist
- Keep
MAIL_PASSWORDout of the repository and out of logs. Use environment variables or a secrets manager and a credential dedicated to this application. - Do not set the sender to user-supplied text. Use a fixed address on your authenticated domain and put the visitor in Reply-To.
- Do not disable certificate verification to work around a TLS error. Use the host name that matches the certificate.
- Rate limit any endpoint that can trigger an email, such as contact forms, invitations and password resets, and verify bots before sending.
- Turn
MAIL_DEBUGoff in production, since the dialogue contains encoded credentials.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| smtplib.SMTPAuthenticationError 535 | Wrong credentials, or an app password or API key is needed | Verify with another client. See error 535 |
| ConnectionRefusedError or TimeoutError | Wrong host or port, firewall or blocked outbound SMTP | Test connectivity from the same host; try 587 and 465 |
| ssl.SSLError: wrong version number | MAIL_USE_TLS and MAIL_USE_SSL do not match the port | TLS on 587, SSL on 465, never both |
| SMTPServerDisconnected: connection unexpectedly closed | TLS mode mismatch, or the server dropped an idle connection | Fix the mode; reduce MAIL_MAX_EMAILS or reconnect |
| RuntimeError: working outside of application context | Sending from a thread or CLI without a context | Use app.app_context() |
| Messages silently not sent | MAIL_SUPPRESS_SEND is true because app.testing is on | Turn testing off in the real environment |
| Request hangs | Slow SMTP server with no timeout | Send in the background and set a socket timeout |
| Sent but in spam | Unauthenticated sending domain | Set up SPF, DKIM and DMARC |
Next steps
Treat email as a dependency that can fail. Keep the code that builds messages separate from the code that sends them, so you can unit test the first and swap the second for a queue worker or an API client later. Review your sending logs after the first week in production, check bounce rates, and confirm that password reset and notification emails arrive within seconds.
Start with one environment-driven configuration and a single test message to a mailbox you control. Then add templates, move sending to a queue, and write tests with record_messages(). Before launch, authenticate the From domain (see authenticating your sending domain) and check the Authentication-Results header on a delivered message. If you send through MigoSMTP, use smtp.migosmtp.com with port 587 and MAIL_USE_TLS, or port 465 and MAIL_USE_SSL, and the credentials from your account. Where outbound SMTP is blocked, an HTTP API is the alternative; compare in SMTP versus API.
Send Flask application mail through a dedicated relay Authenticated SMTP with bounce and complaint events for your app.
References and further reading
Frequently asked questions
How do I send email in Flask?
Install Flask-Mail, set the MAIL_* configuration values, create a Message and call mail.send(msg). Initialise Mail with init_app() in an application factory.
Should I use MAIL_USE_TLS or MAIL_USE_SSL?
Use MAIL_USE_TLS with port 587 for STARTTLS, or MAIL_USE_SSL with port 465 for implicit TLS. Enable only one of them.
How do I attach a file in Flask-Mail?
Call msg.attach(filename, content_type, data) with the file bytes, for example from app.open_resource().
How can I test Flask email without sending?
Use mail.record_messages() in tests, and rely on MAIL_SUPPRESS_SEND, which defaults to true when app.testing is set.
Why do I get an application context error when sending?
Flask-Mail needs an app context. Wrap sending in app.app_context() when sending from a thread, a worker or a CLI command.