(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:
(2) Build a Python script to send email from our gmail account
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_address = "email@example.com"
to_address = "firstname.lastname@example.org"
# 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 - https://developers.google.com/gmail/design/css#example.
# Record the MIME type - text/html.
part1 = MIMEText(html, 'html')
# Attach parts into message container
username = 'email@example.com'
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('smtp.gmail.com', 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!
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.