Send mail with Python

Good system admins get to know scripting languages well and sometimes use them for all kinds of purposes, from scripts that do backups to complex automated tasks. Often times it would be nice to get an email notification when the script finished or completed OK. Cron does a good job of sending emails when scripts run into errors or problems, but sometimes it is necessary to get custom email messages sent from the script itself. Python makes sending email alerts a breeze.

The Code

import smtplib

fromaddr = 'fromuser@gmail.com'
toaddrs  = 'touser@gmail.com'
msg = 'There was a terrible error that occured and I wanted you to know!'


# Credentials (if needed)
username = 'username'
password = 'password'

# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

What Now?

You will want to use this with an already existing script or a script where you want to add email alerts. For example:

# A big task
...
if task.completedOk():
     # Insert email code here, explaining that 
     # the task is done and some details about it

Or perhaps you wanted Python to send you an email if the server room gets too hot:

# Get temp
...
if temperature > 70:
     # Insert email code here

Subscribe via Email

Subscribe to Nixtutor via Email

Enter your email address:

Was this information useful?

6 Responses

  1. Eric Wendelin

    6-30-2009

    Python FTW!

  2. [...] email through PHP, Python, Ruby, and [...]

  3. [...] talked about some of the benefits of setting up an email server in Linux and how you can use python to send email. Now we are going to look at how you can send email from [...]

  4. Tait Clarridge

    7-27-2009

    Great article, one thing to note though.

    If you are using an IDE that adds your workspace directory to the Python PATH or a directory that is already included in the Python PATH, do not name the file email.py. It will screw up the email.py module from smtplib.

  5. Wilson Silva

    8-15-2009

    Thanks. I’ve been searching for this code for a loooong time. Everytime I find something about sending emails with a programming language I get an error or the code is too complicated to understand and maintain. But you made my week :D

  6. Zach Dwiel

    9-9-2009

    I had to do the following to get this code to work for me:

    server = smtplib.SMTP(‘smtp.gmail.com:587′)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(username,password)