Skip to content

Flask-Mail (Sending Emails)

Many apps need email:

  • password reset
  • email verification
  • notifications

Flask-Mail is a popular extension.

Install

pip install Flask-Mail
pip install Flask-Mail

Basic configuration

app.config.update(
    MAIL_SERVER="smtp.gmail.com",
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USERNAME=os.environ.get("MAIL_USERNAME"),
    MAIL_PASSWORD=os.environ.get("MAIL_PASSWORD"),
)
app.config.update(
    MAIL_SERVER="smtp.gmail.com",
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USERNAME=os.environ.get("MAIL_USERNAME"),
    MAIL_PASSWORD=os.environ.get("MAIL_PASSWORD"),
)

Then:

from flask_mail import Mail
 
mail = Mail(app)
from flask_mail import Mail
 
mail = Mail(app)

Sending an email

from flask_mail import Message
 
msg = Message(
    subject="Welcome",
    sender="noreply@example.com",
    recipients=["user@example.com"],
    body="Hello from Flask!",
)
mail.send(msg)
from flask_mail import Message
 
msg = Message(
    subject="Welcome",
    sender="noreply@example.com",
    recipients=["user@example.com"],
    body="Hello from Flask!",
)
mail.send(msg)

Production tips

  • Don’t send emails synchronously inside web requests (slow)
  • Use background jobs (Celery/RQ) for sending
  • Use environment variables for credentials
  • Prefer transactional email providers (SendGrid/Mailgun)

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did