Flask-Mail Tutorial: Sending Emails with Flask

beginner
16 min

Flask-Mail Tutorial: Sending Emails with Flask

Welcome back to CodeYourCraft! Today, we're going to learn about Flask-Mail, a powerful extension for Flask that allows you to send emails from your applications. This is a useful feature for notifications, password recovery, and more. Let's dive in!

Why Flask-Mail? 🎯

Flask-Mail is an extension of Flask that simplifies the process of sending emails. It abstracts the complexities of email sending, allowing you to focus on your application's core functionality.

Installing Flask-Mail 📝

First, let's install Flask-Mail using pip:

bash
pip install Flask-Mail

Now, let's install it in our Flask application:

python
from flask import Flask from flask_mail import Mail, Message app = Flask(__name__) app.config.update( MAIL_SERVER='smtp.googlemail.com', MAIL_PORT=587, MAIL_USE_TLS=True, MAIL_USERNAME='your-email@gmail.com', MAIL_PASSWORD='your-password' ) mail = Mail(app)

Replace 'your-email@gmail.com' and 'your-password' with your Gmail account credentials. Other email providers may require different configurations.

Sending an Email 💡

Now that we have Flask-Mail installed and configured, let's send an email!

python
@app.route('/send-email') def send_email(): msg = Message('Hello', recipients=['recipient@example.com']) msg.html = """ <html> <body> <h1>Welcome to CodeYourCraft!</h1> <p>We're glad to have you on board!</p> </body> </html> """ mail.send(msg) return "Email sent!"

In this example, we've created a route that sends an email to 'recipient@example.com' with an HTML message.

Advanced Usage ✅

For more advanced usage, you can pass additional parameters to the Message constructor:

python
msg = Message('Subject', sender='sender@example.com', recipients=['recipient@example.com'])

You can also include attachments:

python
from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() msg['Subject'] = 'Attached File' msg['From'] = 'sender@example.com' msg['To'] = 'recipient@example.com' with open('file.txt', 'rb') as attachment: part = MIMEApplication(attachment.read(), Name='file.txt') part['Content-Disposition'] = 'attachment; filename="file.txt"' msg.attach(part)

Quiz 📝

Quick Quiz
Question 1 of 1

What is Flask-Mail used for?

That's it for today! In the next lesson, we'll explore more advanced features of Flask-Mail, including email templates and error handling. See you then!