0
0
Flaskframework~5 mins

Flask-Mail setup

Choose your learning style9 modes available
Introduction

Flask-Mail helps your Flask app send emails easily. It connects your app to an email server so you can send messages.

You want to send a welcome email when a user signs up.
You need to send password reset links to users.
You want to notify admins about important events.
You want to send newsletters or updates to users.
You want to confirm user actions by email.
Syntax
Flask
from flask_mail import Mail, Message

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)

Replace the config values with your email server details.

Use Mail(app) to connect Flask-Mail to your Flask app.

Examples
Example setup for Gmail SMTP with SSL.
Flask
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'myemail@gmail.com'
app.config['MAIL_PASSWORD'] = 'mypassword'
Using app.config.update() to set multiple mail settings at once.
Flask
app.config.update(
    MAIL_SERVER='smtp.mailtrap.io',
    MAIL_PORT=2525,
    MAIL_USERNAME='username',
    MAIL_PASSWORD='password',
    MAIL_USE_TLS=True,
    MAIL_USE_SSL=False
)
Sample Program

This Flask app sets up Flask-Mail with Mailtrap SMTP. When you visit /send-email, it sends a simple email.

Flask
from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.mailtrap.io'
app.config['MAIL_PORT'] = 2525
app.config['MAIL_USERNAME'] = 'your-username'
app.config['MAIL_PASSWORD'] = 'your-password'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False

mail = Mail(app)

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

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Make sure to use real SMTP server details to send emails.

For testing, services like Mailtrap let you catch emails without sending real ones.

Keep your email password safe and do not hardcode it in public code.

Summary

Flask-Mail connects your Flask app to an email server.

Configure mail server settings in app.config.

Use Mail(app) and Message to send emails.