Flask-Mail (Sending Emails)
Many apps need email:
- password reset
- email verification
- notifications
Flask-Mail is a popular extension.
Install
bash
pip install Flask-Mailbash
pip install Flask-MailBasic configuration
python
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"),
)python
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:
python
from flask_mail import Mail
mail = Mail(app)python
from flask_mail import Mail
mail = Mail(app)Sending an email
python
from flask_mail import Message
msg = Message(
subject="Welcome",
sender="noreply@example.com",
recipients=["user@example.com"],
body="Hello from Flask!",
)
mail.send(msg)python
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
