Last modified: Jun 01, 2025 By Alexander Williams

Install Flask-Mail in Python

Flask-Mail is a Flask extension for sending emails. It integrates with Flask applications easily. 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 may also need other Flask extensions like Flask-Login for user authentication.

Install Flask-Mail

Use pip to install Flask-Mail. Run this command in your terminal:


pip install Flask-Mail

This will download and install the latest version of Flask-Mail.

Configure Flask-Mail

After installation, configure Flask-Mail in your Flask application. Here's a basic setup:


from flask import Flask
from flask_mail import Mail

app = Flask(__name__)

# Configuration
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)

The Mail class initializes the email functionality. The configuration includes server details and credentials.

Send an Email

Use the send method to send emails. Here's an example:


from flask_mail import Message

@app.route('/send-mail')
def send_mail():
    msg = Message('Hello', sender='your-email@example.com', recipients=['recipient@example.com'])
    msg.body = "This is a test email sent from Flask-Mail"
    mail.send(msg)
    return "Email sent!"

The Message class creates the email. It includes subject, sender, recipients, and body.

Testing the Setup

To test, run your Flask application and visit the '/send-mail' route. Check the recipient's inbox for the email.

For debugging, you can use Python's built-in SMTP server. Set MAIL_SERVER to 'localhost' and port to 1025.

Common Issues

If emails aren't sending, check these:

1. Verify SMTP server settings are correct.

2. Ensure credentials are valid.

3. Check firewall or network restrictions.

For internationalization needs, consider Babel for localized emails.

Advanced Configuration

Flask-Mail supports additional options:


app.config['MAIL_USE_SSL'] = True  # For SSL connections
app.config['MAIL_DEFAULT_SENDER'] = 'default@example.com'  # Default sender
app.config['MAIL_MAX_EMAILS'] = 10  # Limit emails per connection

These settings provide more control over email sending behavior.

Conclusion

Flask-Mail makes email sending in Flask applications simple. With just a few lines of code, you can configure and send emails.

Remember to secure your email credentials. For more Flask extensions, check out pytz for timezone handling.

Now you're ready to integrate email functionality into your Flask projects!