Web-based applications typically require the ability to send mail to the user/client. Flask doesn’t have an out of the box solution to send mail.
Instead, the Flask-Mail extension makes it easy to establish a simple interface with any email server.
Email generally uses two protocols, one for sending mails (smtp) and one for receiving mail (pop3). This article is about sending mails.
Related course: Python Flask: Create Web Apps with Flask
Introduction
First, the Flask-Mail extension should be installed with the help of the pip utility.
1 | pip install Flask-Mail |
You then need to configure the Flask-Mail by setting the values for the following application parameters.
- MAIL_SERVER
- MAIL_USE_TLS
- MAIL_USE_SSL
- MAIL_DEBUG
- MAIL_USERNAME
- MAIL_PASSWORD
- MAIL_DEFAULT_SENDER
- MAIL_MAX_EMAILS
- MAIL_SUPPRESS_SEND
- MAIL_ASCII_ATTACHMENTS
The flask-mail module contains definitions of the following important classes.
The Mail class manages email messaging requirements.The class constructor takes the form of:
1 | flask-mail.Mail(app = None) |
Mail class methods include: send()
, connect()
and send_message()
.
The Message class encapsulated an email.The Message class constructor has several parameters:
1 | flask-mail.Message(subject, recipients, body, html, sender, cc, bcc, |
Message class method attach () - Add attachment for mail.This method takes the following parameters:
- filename : The name of the file
- content_type : MIME type
- data - file data
You can use add_recipient()
to add another recipient to the message.
Mail config and functions
In the example below, the SMTP server for the Google gmail service is used as the MAIL_SERVER for the Flask-Mail configuration.
Step 1: Import the Mail and Message classes from the flask-mail module in the code.
1 | from flask_mail import Mail, Message |
Step 2: Configure server parameters
1 | app.config['MAIL_SERVER']='smtp.gmail.com' |
Step 3: Create an instance of the Mail class.
1 | mail = Mail(app) |
Step 4: The Message object is set in a Python function that is mapped by the URL rule (‘/‘).
1 |
|
Flask mail example
The entire code is as follows.Run the following script in the Python shell and access localhost:5000/.
1 | from flask import Flask |
Note that security in the Gmail service can prevent this login attempt. If you use gmail smtp server, you might have to reduce the security level.
Related course: Python Flask: Create Web Apps with Flask