Flask-Mail

0.10.0 · active · verified Sun Apr 12

Flask-Mail is an extension for Flask that simplifies sending emails from your application. It provides a straightforward interface for integrating SMTP capabilities. Currently at version 0.10.0, the project is actively maintained as part of the Pallets Community Ecosystem, the open-source organization behind Flask.

Warnings

Install

Imports

Quickstart

Initializes Flask-Mail with configuration from environment variables for security and flexibility, then defines a simple route to send a test email. Remember to set `MAIL_USERNAME`, `MAIL_PASSWORD`, and other `MAIL_` environment variables before running the application. For Gmail, use an App Password if 2FA is enabled.

import os
from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)

# Configure Flask-Mail using environment variables for sensitive data
app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER', 'smtp.example.com')
app.config['MAIL_PORT'] = int(os.environ.get('MAIL_PORT', 587))
app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS', 'True').lower() == 'true'
app.config['MAIL_USE_SSL'] = os.environ.get('MAIL_USE_SSL', 'False').lower() == 'true'
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME', '')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD', '')
app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER', 'noreply@example.com')

mail = Mail(app)

@app.route('/send-test-email')
def send_email():
    if not app.config['MAIL_USERNAME'] or not app.config['MAIL_PASSWORD']:
        return "Email credentials not set in environment variables. Cannot send.", 500

    msg = Message(
        subject='Hello from Flask-Mail!',
        recipients=['recipient@example.com'], # Replace with a real recipient email
        body='This is a test email sent from your Flask application.'
    )
    try:
        mail.send(msg)
        return 'Email sent successfully!'
    except Exception as e:
        return f'Failed to send email: {e}', 500

if __name__ == '__main__':
    # Example usage with environment variables (set these before running):
    # export MAIL_SERVER='smtp.gmail.com'
    # export MAIL_PORT=587
    # export MAIL_USE_TLS=True
    # export MAIL_USE_SSL=False
    # export MAIL_USERNAME='your_gmail@gmail.com'
    # export MAIL_PASSWORD='your_app_password'
    # export MAIL_DEFAULT_SENDER='your_gmail@gmail.com'
    app.run(debug=True)

view raw JSON →