User Tools

Site Tools


python:sendemailsgmail

HOWTO SEND EMAILS USING PYTHON AND A GMAIL ACCOUNT

05.11.2008

Before we begin…

… you'll need a gmail account, of course. Even this script applies to gmail, it can be easily modified and used for any email service.

The Script

First, import the needed library smtplib

#!/usr/bin/env python
# EXAMPLE: HOWTO SEND AN EMAIL USING A GMAIL ACCOUNT
#
#
 
import smtplib

Prepare the sender/addressee name and email address:

from_addr = "sender@gmail.com"
sender = "Sender Name"
 
to_addr = "johndoe@yahoo.com"
to = "John Doe"

Fill up the subject. Then create the message from the headers and the body of the message:

subject = "Test smtplib"
 
# pay attention here: To: and Subject must be right after \n (no space between)
headers = "From: %s \r\nTo: %s\r\nSubject: %s \r\n\r\n" % (sender, to, subject)
msg = headers + "This is the body of the message!"

Sending the mail

mailserver = smtplib.SMTP("smtp.gmail.com", 587) 
mailserver.set_debuglevel(1) # to get interesting messages
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login(from_addr, 'password') 
 
mailserver.sendmail(from_addr, to_addr, msg)
mailserver.quit()

Download here the python source file

python/sendemailsgmail.txt · Last modified: 2013/03/16 17:40 (external edit)