Saturday 1 November 2014

Sending Email using Python

I often see people asking the question how do you send Email using Python?
Well a few years ago I had the idea to write a program, which would automatically send an Email should a certain event happen. I have been meaning to include the Email code in a blog post, but have never managed to get around to it.

Until now...

So here is the code I used. I know it works with Gmail, but have not tested it with other providers, although I am sure a little modification would make it work.

Remember this program requires you to store your Email password in plain text, something you need to be aware of!

Just ensure you add your username and password where necessary, and change the other fields as required.


#!/usr/bin/python
import smtplib

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
GMAIL_USERNAME = 'your_username@gmail.com'
GMAIL_PASSWORD = 'your_gmail_password' #CAUTION: This is stored in plain text!

recipient = 'recipient@email_address.com'
subject = 'Email Subject'
emailText = 'This is the content of the e-mail.'

emailText = "" + emailText + ""

headers = ["From: " + GMAIL_USERNAME,
           "Subject: " + subject,
           "To: " + recipient,
           "MIME-Version: 1.0",
           "Content-Type: text/html"]
headers = "\r\n".join(headers)

session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

session.ehlo()
session.starttls()
session.ehlo

session.login(GMAIL_USERNAME, GMAIL_PASSWORD)

session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + emailText)
session.quit()