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
flask
and flask_mail
.from flask import Flask
from flask_mail import Mail
Flask
application.app = Flask(__name__)
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
Mail
.mail = Mail(app)
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"
if __name__ == '__main__':
app.run(debug = True)
flask
server.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)