Chapter 6. Email
Many types of applications need to notify users when certain events occur, and the usual method of communication is email. 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.
Email Support with Flask-Mail
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.
import
os
# ...
app
.
config
[
'MAIL_SERVER'
]
=
'smtp.googlemail.com'
app
.
config
[
'MAIL_PORT'
]
=
587
app
.
config
[
'MAIL_USE_TLS'
]
=
True
app
.
config ...
Get Flask Web Development 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.