Automate Your Email Sending with Flask and Gmail App Password: A Step-by-Step Guide

Dhruv Singhal
3 min readMar 30, 2021

--

In this article, we will learn about sending mail to our Gmail using Flask and app password(Gmail).

What is an app password and why do we need it?

An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on.

Steps to generate App password:

If you have enabled 2-Step Verification and get a “smtplib.SMTPAuthenticationError” error when we try to send mail using flask-mail, we can try to use an App Password.

  1. Go to your Google Account.
  2. Select Security.
Select Security Tab

3. Under “Signing in to Google,” select App Passwords. You may need to sign in. If you don’t have this option, it might be because:

a) 2-Step Verification is not set up for your account.
b) 2-Step Verification is only set up for security keys.
c) Your account is through work, school, or other organizations.
d) You turned on Advanced Protection.

2-Step Verification is enabled

4. At the bottom, choose Select App and Select Other(Custom name), and enter the name of your app. Select the device(not mandatory) and choose the device you’re using and click on Generate.

5. Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.

16-digit App password window

Now we are all set to use this App password.

Note: Most of the time, you’ll only have to enter an App Password once per app or device, so don’t worry about memorizing it.

Let’s use this password in our app

Flask code to send mail:

from flask import Flask
from flask_mail import Mail

app=Flask(__name__)
app.config.update(
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT='465',
MAIL_USE_SSL=True,
MAIL_USERNAME="your gmail_id"
MAIL_PASSWORD="your gmail 16 digit app password"
)

mail=Mail(app)
mail.send_message('New test message from'+name,
sender="sender_email@gmail.com",
recipients=MAIL_USERNAME,
body=message+"\n"+phone)
  1. The server is “smtp.gmail.com”.
  2. Each port is dedicated to the type of security used.
  • If STARTTLS is used with MAIL_USE_TLS = True, then use MAIL_PORT = 587.
  • If SSL/TLS is used with MAIL_USE_SSL = True, then use MAIL_PORT = 465.
  • Enable either STARTTLS or SSL/TLS, not both.

Note: Please ensure that flask-mail is installed. If not installed use pip install flask-mail.

Any suggestions and comments will be highly appreciated. Please do like and share this article. Thanks for reading this article.

--

--

Dhruv Singhal
Dhruv Singhal

Written by Dhruv Singhal

Data engineer with expertise in PySpark, SQL, Flask. Skilled in Databricks, Snowflake, and Datafactory. Published articles. Passionate about tech and games.

No responses yet