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!
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.
First, let's install Flask-Mail using pip:
pip install Flask-MailNow, let's install it in our Flask application:
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.
Now that we have Flask-Mail installed and configured, let's send an email!
@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.
For more advanced usage, you can pass additional parameters to the Message constructor:
msg = Message('Subject', sender='sender@example.com', recipients=['recipient@example.com'])You can also include attachments:
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)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!