0
0
Flaskframework~5 mins

Sending simple emails in Flask

Choose your learning style9 modes available
Introduction

Sending emails lets your app talk to users by sending messages automatically. It helps with notifications, confirmations, or alerts.

Send a welcome email when someone signs up.
Notify users about password changes.
Send alerts for important events or errors.
Confirm orders or bookings automatically.
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)

msg = Message(subject='Hello', sender='your-email@example.com', recipients=['friend@example.com'])
msg.body = 'This is a simple email sent from Flask.'
mail.send(msg)

Configure your mail server settings before sending emails.

Use Message to create the email content and recipients.

Examples
Sends a plain text email with a subject and body.
Flask
msg = Message(subject='Hi', sender='me@example.com', recipients=['you@example.com'])
msg.body = 'Hello there!'
mail.send(msg)
Sends an email with HTML content instead of plain text.
Flask
msg = Message(subject='Greetings', sender='me@example.com', recipients=['you@example.com'])
msg.html = '<b>Bold hello!</b>'
mail.send(msg)
Sample Program

This Flask app sends a simple email when you visit /send-email. It uses Gmail SMTP settings and Flask-Mail to send the message.

Flask
from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your-email@gmail.com'
app.config['MAIL_PASSWORD'] = 'your-app-password'

mail = Mail(app)

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

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

Use app passwords or OAuth for Gmail instead of your main password for security.

Make sure less secure app access is enabled or use app-specific passwords if needed.

Test emails with a real SMTP server or a service like Mailtrap for development.

Summary

Configure mail server settings in your Flask app.

Create a Message object with subject, sender, recipients, and body.

Use mail.send() to send the email.