Sending Email from Python using Gmail

It is extremely useful to send emails from scripts.  Emails can alert you to errors as soon as they happen or can give you regular status updates about the running of your programs.

I have several scripts that run regularly to update various websites or scrape data from different places and quite often when dealing with the internet things change.  Code breaks constantly as the things they depend on change so to make sure everything continues to run it’s important to be notified when errors happen.

One of the greatest ways to do this is to have your programs send email messages to you.  I use Google’s Gmail SMTP server to relay my messages to me.  That way I don’t have to rely on having sendmail installed on the machine or hooking into something like MS Outlook to compose an email.

This small simple script uses smtplib to send simple text emails using Gmail’s SMTP service.

#!/usr/bin/python
 
import smtplib
from email.MIMEText import MIMEText
 
GMAIL_LOGIN = 'myemail@gmail.com'
GMAIL_PASSWORD = 'password'
 
 
def send_email(subject, message, from_addr=GMAIL_LOGIN, to_addr=GMAIL_LOGIN):
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
 
    server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(GMAIL_LOGIN,GMAIL_PASSWORD)
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.close()
 
 
if __name__=="__main__":
    send_email('test', 'This is a test email')