Runar Ovesen Hjerpbakk

Science-based software development

Send an email via Gmail using Python

Sending an email programmatically from a Gmail account is easy using Python and the smtplib library. The following snippet shows a function written in Python that sends an email with a chosen subject and a body as plain text.

#!/usr/bin/python

import smtplib
import string

def send_email(to_address, subject, body):
	from_address = ''
	username = from_address
	password = ''
	email = string.join((
        'From: %s' % from_address,
        'To: %s' % to_address,
        'Subject: %s' % subject,
        '',
        body
        ), '\r\n')
	server = smtplib.SMTP('smtp.gmail.com:587')
	server.ehlo()
	server.starttls()
	server.login(username, password)
	server.sendmail(from_address, to_address, email)
	server.quit()

Line 7 through 16 creates the email message. Since the from_address will be used as the Gmail username, the from_address and password need to be valid Gmail credentials. The to_address, subject and mail body is given to the function as parameters.

Line 17 gets the SMTP connection and ehlo() identifies us to the ESMTP server using EHLO (Extended HELLO). starttls() puts the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted.

Line 20 through 22 logs us in, sends the email and finally terminates the SMTP session.