Flask-Mail (Sending Emails)
Many apps need email:
- password reset
- email verification
- notifications
Flask-Mail is a popular extension.
Install
pip install Flask-Mailpip install Flask-MailBasic 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 coffeeWas this page helpful?
Let us know how we did
