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.
Key | Default | Description |
---|---|---|
|
localhost |
Hostname or IP address of the email server |
|
25 |
Port of the email server |
|
|
Enable Transport Layer Security (TLS) security |
|
|
Enable Secure Sockets Layer (SSL) security |
|
|
Mail account username |
|
|
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 ...
Get Flask Web Development, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.