Flask - Mail

Flask - Mail

Sending an email is a very common requirement in any application, Flask also provides a simple interface to send email from Flask Application. Flask email setup is very easy.

first, install flask-email using pip

pip install Flask-Mail

Then Flask-Mail needs to be configured by setting values of the following application parameters.

Parameters Description
MAIL_SERVER Name/IP address of email server
MAIL_PORT Port number of server used
MAIL_USE_TLS Enable/disable Transport Security Layer encryption
MAIL_USE_SSL Enable/disable Secure Sockets Layer encryption
MAIL_DEBUG Debug support
MAIL_USERNAME User name of sender
MAIL_PASSWORD Password of sender
MAIL_DEFAULT_SENDER Sets default sender
MAIL_MAX_EMAILS Sets maximum mails to be sent
MAIL_ASCII_ATTACHMENTS If set to true, attached filenames converted to ASCII

Mail class

It manages email messaging object, class construct like below

flask-mail.Mail(app = None)

Methods of Mail class

Methods Description
send() Sends contents of Message class object
connect() Opens connection with mail host
send_message() Sends message object

Message class

Message class constructor has several parameters as below,

flask-mail.Message(subject, recipients, body, html, sender, cc, bcc, 
   reply-to, date, charset, extra_headers, mail_options, rcpt_options)

Some more method of the Message class
attach()

  • filename − name of file to attach
  • content_type − MIME type of file
  • data − raw file data
  • disposition − content-disposition

add_recipient()
adds another recipient to message

Let's understand this using simple example, 1st import Mail and Message class

from flask_mail import Mail, Message

2nd Config Flak email

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

Now, Create an instance of the Mail class

mail = Mail(app)

After that let's create URL end point in our flask-app

@app.route("/send-email")
def send_email():
   msg = Message('Hello', sender = 'yourId@gmail.com', recipients = ['id1@gmail.com'])
   msg.body = "This is the email body"
   mail.send(msg)
   return "eMail Sent"

I hope you learn how to send email using flak application

Happy Leaning!!