O'Reilly logo

Flask Web Development, 2nd Edition by Miguel Grinberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Email

Many types of applications need to notify users when certain events occur, and the usual method of communication is email. In this chapter you are going to learn how to send emails from a Flask application.

Email Support with Flask-Mail

Although the smtplib package from the Python standard library can be used to send email inside a Flask application, the Flask-Mail extension wraps smtplib and integrates it nicely with Flask. Flask-Mail is installed with pip:

(venv) $ pip install flask-mail

The extension connects to a Simple Mail Transfer Protocol (SMTP) server and passes emails to it for delivery. If no configuration is given, Flask-Mail connects to localhost at port 25 and sends email without authentication. Table 6-1 shows the list of configuration keys that can be used to configure the SMTP server.

Table 6-1. Flask-Mail SMTP server configuration keys
Key Default Description

MAIL_SERVER

localhost

Hostname or IP address of the email server

MAIL_PORT

25

Port of the email server

MAIL_USE_TLS

False

Enable Transport Layer Security (TLS) security

MAIL_USE_SSL

False

Enable Secure Sockets Layer (SSL) security

MAIL_USERNAME

None

Mail account username

MAIL_PASSWORD

None

Mail account password

During development it may be more convenient to connect to an external SMTP server. As an example, Example 6-1 shows how to configure the application to send email through a Google Gmail account.

Example 6-1. hello.py: Flask-Mail configuration for Gmail
import ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required