May. 30, 2013

Sending emails using Google


A common task for system administrators and developers is to use scripts to send
emails if an error occurs.

Why use Gmail?

Using Googles SMTP servers are free to use and works perfectly fine to relay

Note that Google has a sending limit: "Google will temporarily disable your
account if you send messages to more than 500 recipients or if you send a large
number of undeliverable messages. "

As long as you are fine with that, you are good to go.

Where do I start?

Sending mail is done with Python's smtplib using an SMTP (Simple Mail Transfer
Protocol) server.

Since we will use Google's SMTP server to deliver our emails, we will need to
gather information such as server, port, authentication. 

That information is easy to find with a Google search.

Google's Standard configuration instructions

Outgoing Mail (SMTP) Server - requires TLS or SSL:

Use Authentication:


Port for SSL:

Server timeouts:
Greater than 1 minute, we recommend 5

Account Name or User Name:
your full email address (including or

Email Address: 
your email address ( or

your Gmail password

Getting Started

Begin with opening up your favorite text editor and import the smtplib module at
the top of your script.
import smtplib
Already at the top we will create some SMTP headers.
fromaddr = ''
toaddrs  = ''
msg = 'Enter you message here'
Once that is done, create a SMTP object which is going to be used for connection
with the server.
server = smtplib.SMTP("")
Next, we will use the starttls() function which is required by Gmail.
Next, log in to the server:
Then, we will send the email:
server.sendmail(fromaddr, toaddrs, msg)

The final program

You can see the full program below, by now you should be able to understand what
it does.
import smtplib

# Specifying the from and to addresses

fromaddr = ''
toaddrs  = ''

# Writing the message (this message will appear in the email)

msg = 'Enter you message here'

# Gmail Login

username = 'username'
password = 'password'

# Sending the mail  

server = smtplib.SMTP('')
server.sendmail(fromaddr, toaddrs, msg)
More Reading
Using Python to send email

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, only recommend products or services that we try personally and believe will add value to our readers.