Runar Ovesen Hjerpbakk

Software Philosopher

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.


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,
        ), '\r\n')
	server = smtplib.SMTP('')
	server.login(username, password)
	server.sendmail(from_address, to_address, email)

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.