Introduction

Sending emails is a common feature in web applications, and Flask-Mail is an extension for Flask that simplifies the process. In this guide, we'll explore how to use Flask-Mail to send emails from your Flask application. By following this guide, you'll be able to set up email functionality in your web application and send emails to users, whether it's for notifications, password resets, or other purposes.


Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and installing the necessary extensions. Here's a sample directory structure:

email-app/
app.py
templates/
email_template.html

Step 2: Configuring Flask-Mail

In your Flask application, configure Flask-Mail with your email service provider's information. Here's a basic example:

# app.py
from flask import Flask, render_template
from flask_mail import Mail, Message
app = Flask(__name)
app.config['MAIL_SERVER'] = 'smtp.example.com' # Replace with your SMTP server
app.config['MAIL_PORT'] = 587 # Port for SMTP
app.config['MAIL_USE_TLS'] = True # Use TLS encryption
app.config['MAIL_USE_SSL'] = False # Do not use SSL
app.config['MAIL_USERNAME'] = 'your_email@example.com' # Your email
app.config['MAIL_PASSWORD'] = 'your_password' # Your email password
mail = Mail(app)
if __name__ == '__main__':
app.run(debug=True)

Step 3: Creating an Email Template

Create an HTML template for your email content. Here's a basic example:

<!-- templates/email_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>Your Email Subject</title>
</head>
<body>
<h1>Hello, {{ username }}!</h1>
<p>This is the content of your email.</p>
</body>
</html>

Step 4: Sending an Email

Create a route in your Flask application to send emails. Here's an example:

# app.py
@app.route('/send_email')
def send_email():
recipient = 'recipient@example.com' # Replace with the recipient's email address
subject = 'Your Email Subject'
username = 'John' # Example variable to include in the email
message = Message(subject, recipients=[recipient])
message.html = render_template('email_template.html', username=username)
try:
mail.send(message)
return 'Email sent successfully!'
except Exception as e:
return f'Email not sent. Error: {str(e)}'

Step 5: Running Your Email App

Run your Flask email application using the following command:

python app.py

Access your Flask application in a browser and navigate to the '/send_email' route to send a sample email.


Conclusion

Working with Flask-Mail makes it easy to send emails from your Flask application. By following the steps in this guide, you can set up your Flask application to send emails, configure Flask-Mail with your email service provider's information, create email templates, and send emails to recipients. You can further enhance your email functionality by handling email attachments, using different email templates, and sending emails to different recipients.