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
- Import
flaskandflask_mail.
from flask import Flask
from flask_mail import Mail
- Create an instance of a
Flaskapplication.
app = Flask(__name__)
- 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
is not enabled. 2FA Two-factor authentication
- Create an instance of
Mail.
mail = Mail(app)
- Define the
routeand 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"
- Add the code below to run the program directly.
if __name__ == '__main__':
app.run(debug = True)
- Run the
flaskserver.
flask run
from flask import Flaskfrom flask_mail import Mailapp = Flask(__name__)app.config['MAIL_SERVER']='smtp.gmail.com'app.config['MAIL_PORT'] = 465app.config['MAIL_USERNAME'] = 'your_email@gmail.com'app.config['MAIL_PASSWORD'] = 'your_password'app.config['MAIL_USE_TLS'] = Falseapp.config['MAIL_USE_SSL'] = Truemail = 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)