Flask – Mail extension explained and how to use it?
In this tutorial, we are going to learn about the Flask – Mail extension. We are also going to learn about all its functionalities and features. We will also learn about how to implement it in our Flask webpage.
Flask – Mail
In a web application, it is necessary to have a mailing functionality through which mail can be sent to clients/users. Flask-Mail is an extension that helps us in achieving that by providing a simple interface with any email server.
But before all this you need to first install the Flask-Mail extension using the pip installer-
pip install Flask-Mail
Then configure the Flask-Mail extension by setting the values of the following parameters.
- MAIL_SERVER – Used to store the Name/IP address of the e-mail server.
- MAIL_PORT – Used to store the port number of the server used
- MAIL_USE_TLS – Used to enable/disable Transport Security Layer encryption.
- MAIL_USE_SSL – Used to enable/disable Secure Sockets Layer encryption.
- MAIL_DEBUG – Used to provide Debug support. The debug status is by default set by flask application.
- MAIL_USERNAME – Gets the username of the sender.
- MAIL_PASSWORD – Gets the password of the sender.
- MAIL_DEFAULT_SENDER – Sets a default sender of mail.
- MAIL_MAX_EMAILS – Sets a maximum number of emails to be sent.
- MAIL_SUPPRESS_SEND – Sends suppressed if the app.testing is set to true.
- MAIL_ASCII_ATTACHMENTS – Converts attached filenames into ASCII, if this parameter is set to true.
Message Class in Flask
The massage class constructor contains many parameters such as –
flask-mail.Message(subject, recipients, body, html, sender, cc, bcc, reply-to, date, charset, extra_headers, mail_options, rcpt_options)
In the following example, the SMTP server of Google’s gmail service is used as the MAIL_SERVER for the Flask-Mail configuration.
First, from the flask_mail module import the Mail and Message class –
from flask_mail import Mail, Message
flask_mail is getting configured with the below settings.
app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = 'yourId@gmail.com' app.config['MAIL_PASSWORD'] = '*****' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True
After that create an instance of the Mail class.
mail = Mail(app)
I hope you understood what was explained in this tutorial. If you have any doubts or queries regarding anything described here, please feel free to comment them down below.
You may also read: