Send Email with Gmail, Python, and Flask

Hasitha Chandula
Analytics Vidhya
Published in
2 min readJan 14, 2020

--

What you’ll need?

  • Python (I’m using Python 3.6.4)
  • Pip for installing dependencies
  • Virtualenv
  • A Gmail account ( Without two-step verification and allow unsafe apps)

First Go to your Project Folder and Open Terminal on that folder and type virtualenv venv and this will create a virtual environment to our project. Then we need to activate virtualenv, if you are using Mac or Linux you can activate by type source env/bin/activate in the terminal. If you are using windows type source env/scripts/activate.

Then We need to install Flask-Mail.

To do that in terminal type pip install Flask-Mail. After that, we can start coding.

from flask import Flask, jsonify
from flask_mail import Mail, Message

app = Flask(__name__)

mail_settings = {
"MAIL_SERVER": 'smtp.gmail.com',
"MAIL_PORT": 465,
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": 'YOUR_GMAIL',
"MAIL_PASSWORD": 'YOUR_PASSWORD'
}

app.config.update(mail_settings)
mail = Mail(app)
app.config.update(mail_settings)mail = Mail(app)

These are the configurations. Now what I’m going to do is when the user requests a Get request “/<string: email>” to this then we will email to users request email. Here is the code,

First, create a file app.py and paste this code and input your Gmail and password.

then you need to run the app using python app.py in the terminal.

You can use postman to do Http requests and test the app.

That’s it. Enjoy Python.

Thank you!

--

--

Hasitha Chandula
Analytics Vidhya

Senior Full Stack Engineer specializing in TypeScript & Go. I create scalable web apps, love learning new tech, and thrive on teamwork.