DEV Community

Cover image for Sending Emails using Python with Gmail SMTP SSL Setup 2022
Renee Betina Esperas
Renee Betina Esperas

Posted on

Sending Emails using Python with Gmail SMTP SSL Setup 2022

(May 30, 2022) ​​Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

Now, we have to use an App Password - this password is specific to the device type (Windows, Mac, etc.) and specific to the Google application we will use (Mail, Calendar, YouTube, etc.)

If you are building a new python app that sends an email using GMAIL, follow the steps below:

Part 1: Setup you Python Functions to generate and send an email

In this example, we have the email module which contains the ff. functions:
a) generate_email - we set a sender, recipient, subject, body and attachment.
b) generate_error_report - custom email where attachment is not needed.
c) send_email - to send an actual email, configure a secure connection to Gmail SMTP_SSL server by declaring the right host and port.

You can check my full code: [Github] Python Functions to Generate and Send an Email

Part 2: Gmail Setup

Once your Python script is ready, you can now configure the Gmail account you will use for this automation.

Step 1: Enable IMAP

  • On your computer, open Gmail.
  • In the top right, click Settings Settings and then See all settings.
  • Click the Forwarding and POP/IMAP tab.
  • In the "IMAP access" section, select Enable IMAP.
  • Click Save Changes.

Enable IMAP

Step 2: Enable 2FA

Go to your Google Account Settings > Security
Enable 2FA

*IMPORTANT: Make sure that this is ON for you to access the next step.

Step 3: Generate an App Password

Go to Google Account > App Passwords

App Passwords Page

Select App: Mail
Select App

Select the specific device you are using
Select Device

Click GENERATE and you will see a prompt like this:
Generated App Password

When you are connecting to the Gmail SMTP server, you will use this App Password instead of your personal Gmail password.

Running your Python Script to send your emails

Sample Run
You can do this approach or directly declare the sender (your gmail) and your app password in your Python script.

If your still encounter errors on your setup, you can also read this thread:

Top comments (0)