How to send emails with API in Flask-Mail

No matter what website we create, there is a point where we need to send out emails to users, whether it may be to reset a password or to send confirmation mail when an order is placed. However, we cannot send the emails manually, so we need to automate sending out emails when an event happens.

To send emails from Python, we have a Python package called flask_mail:

pip install flask_mail

In addition, we need a flask server:

pip install flask

Diving into code

Steps

  1. Import flask and flask_mail.
from flask import Flask
from flask_mail import Mail
  1. Create an instance of a Flask application.
app = Flask(__name__)
  1. Set up the configuration for flask_mail.
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
//update it with your gmail
app.config['MAIL_USERNAME'] = 'your_mail@gmail.com'
//update it with your password
app.config['MAIL_PASSWORD'] = 'your_email_password'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

Since we are using Gmail as the SMTP server, we need to take care of some things, as Gmail won’t allow connections from insecure applications. Just head over to your list of less secure apps and toggle on “allow less secure apps”. Make sure 2FATwo-factor authentication is not enabled.

  1. Create an instance of Mail.
mail = Mail(app)
  1. Define the route and send mail.
@app.route("/")
def index():
  msg = Message('Hello from the other side!', sender =   'from@gmail.com', recipients = ['to@gmail.com'])
  msg.body = "hey, sending out email from flask!!!"
  mail.send(msg)
  return "Message sent"
  1. Add the code below to run the program directly.
if __name__ == '__main__':
   app.run(debug = True)
  1. Run the flask server.
flask run
from flask import Flask
from flask_mail import Mail
app = Flask(__name__)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'your_email@gmail.com'
app.config['MAIL_PASSWORD'] = 'your_password'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
@app.route("/")
def index():
msg = Message('Hello from the other side!', sender = 'from@gmail.com', recipients = ['to@gmail.com'])
msg.body = "hey, sending out email from flask!!!"
mail.send(msg)
return "Message sent"
if __name__ == '__main__':
app.run(debug = True)

Free Resources