Sending email using Python and Gmail

(1) Set up an application password through Google

In order to send emails using Gmail, you'll need to set up an app password. Fortunately, this is pretty simple:

  1. Head over to, and then click into the 'app passwords section (as shown in image below). Create credentials

  2. Select the app ('mail' in this case) and device (I used 'mac').
  3. Click 'generate', save the password (we will feed it into the python script below).

(2) Build a Python script to send email from our gmail account

import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

from_address = ""

to_address = ""

# Create message container - the correct MIME type is multipart/alternative.

msg = MIMEMultipart('alternative')

msg['Subject'] = "Test email"

msg['From'] = from_address

msg['To'] = to_address

# Create the message (HTML).

html = """\

We are sending an email using Python and Gmail, how fun! We can fill this with html, and gmail supports a decent range of css style attributes too -


# Record the MIME type - text/html.

part1 = MIMEText(html, 'html')

# Attach parts into message container


# Credentials

username = ''

password = 'your_password'

# Sending the email

## note - this smtp config worked for me, I found it googling around, you may have to tweak the # (587) to get yours to work

server = smtplib.SMTP('', 587)




server.sendmail(from_address, to_address, msg.as_string())


(3) Voila! We can now use python to send emails through our gmail account

This is a pretty simple example, but hopefully gives you a sense of some of the cool things that can be done with this functionality. For example, you can build out complex html templates (using Python to build unique templates for each individual if desired). If you end up building something with this, let me know!

Interested in practicing for data scientist or analyst interviews?

We send 3 questions each week to thousands of data scientists and analysts preparing for interviews or just keeping their skills sharp. You can sign up to receive the questions for free on our home page.