| September 20, 2011 8:30 pm

Note: Whenever I come across an interesting or potentially useful piece of source code, I like to make a copy and file it away. I post some of them here in the hope that they will be useful to others as well.

For the past couple of days, I have been working on scripts to automate the administration of some of my computers. Because they’ve been runningĀ  big jobs that often take hours to complete, I’ve been leaving them unattended. But since I need to know as soon as the job is completed, it’s nice to receive some sort of alert. For that reason, I wrote a simple script that will send an email when the job is finished. It uses the string and smtplib modules from the standard library. Here’s the code:

import string, smtplib

# Email Settings
HOST = "smtp.gmail.com" # SMTP Server to Send Message From
PORT = 587 # Port you wish to communicate on
USER = "username@gmail.com" # Email Username
PASSWORD = "PASSWORD" # Email Password

FROM = "admin@oak-tree.us"
TO = "recipient@domain.com"

SUBJECT = "Server Notification from " + AMAZON_EC2
TEXT = "Server " + AMAZON_EC2 + " is shutting down.\n" + 'Timestamp: ' +
    str(CURRENT_TIME)

def sendmessage():
  """Send email notification to the specified email address."""
  server = smtplib.SMTP(HOST, PORT)
  server.ehlo()
  server.starttls() # Use Encryption
  server.ehlo
  server.login(USER, PASSWORD)
  BODY = string.join((
    "From: %s" % FROM,
    "To: %s" % TO,
    "Subject: %s" % SUBJECT ,
    "",
    TEXT
    ), "\r\n")
  server.sendmail(FROM, TO, BODY)
  server.quit()

In general, it’s pretty straightforward. You specify what host you want to connect to and the port, then you construct your message. Finally, you send it. In this example, I’ve added a few other things, like a line to log-on to the server and encryption.The actual connection and sending of the email is only two lines of code. The rest is setting up the message.

Pretty cool, huh?

Comments

No Responses to “Code Snippet: Sending Mail with Python”

Care to comment?