Last modified: Jun 11, 2025 By Alexander Williams
Install Flask-Mail in Python - Quick Guide
Flask-Mail is a Flask extension for sending emails. It integrates easily with Flask applications. This guide will show you how to install and use it.
Prerequisites
Before installing Flask-Mail, ensure you have Python and Flask installed. If not, install them first.
You can check Python installation with:
python --version
For Flask, check our other guides like How to Install PyNaCl in Python for related setups.
Install Flask-Mail
Use pip to install Flask-Mail. Run this command:
pip install Flask-Mail
This will download and install the latest version. Verify the installation with:
pip show Flask-Mail
Basic Flask-Mail Setup
Here's a simple Flask application with Flask-Mail configured:
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
# Configure mail
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your-email@example.com'
app.config['MAIL_PASSWORD'] = 'your-password'
mail = Mail(app)
@app.route('/')
def send_mail():
msg = Message('Hello', sender='your-email@example.com', recipients=['recipient@example.com'])
msg.body = "This is a test email from Flask-Mail"
mail.send(msg)
return "Email sent!"
if __name__ == '__main__':
app.run(debug=True)
The Message
class creates an email. The mail.send
method sends it.
Configuration Options
Flask-Mail supports several configuration options:
- MAIL_SERVER: SMTP server address
- MAIL_PORT: SMTP server port
- MAIL_USE_TLS: Enable TLS security
- MAIL_USERNAME: Your email username
- MAIL_PASSWORD: Your email password
Sending HTML Emails
You can send HTML emails by setting the html
attribute:
msg = Message('Hello', sender='your-email@example.com', recipients=['recipient@example.com'])
msg.html = "Welcome
This is HTML content
"
mail.send(msg)
Adding Attachments
To add attachments, use the attach
method:
with app.open_resource("document.pdf") as fp:
msg.attach("document.pdf", "application/pdf", fp.read())
Error Handling
Always handle email sending errors:
try:
mail.send(msg)
except Exception as e:
print(f"Error sending email: {e}")
Testing with Python's SMTP Server
For testing, use Python's built-in SMTP server:
python -m smtpd -n -c DebuggingServer localhost:1025
Then configure Flask-Mail to use this server:
app.config['MAIL_SERVER'] = 'localhost'
app.config['MAIL_PORT'] = 1025
Conclusion
Flask-Mail makes email sending in Flask applications easy. With proper configuration, you can send both text and HTML emails with attachments.
For more Python guides, check our articles like Install PyCryptodome in Python or How to Install dnspython.