Jan. 14, 2013

Using Python to Send Email

Python includes several modules in the standard library for working with emails and email servers.

smtplib Overview

The smtplib module defines an SMTP client session object that can be used to send
mail to any Internet machine with an SMTP or ESMTP listener daemon. 

SMTP stands for Simple Mail Transfer Protocol. 

The smtplib modules is useful for communicating with mail servers to send mail.

Sending mail is done with Python's smtplib using an SMTP server. 

Actual usage varies depending on complexity of the email and settings of the
email server, the instructions here are based on sending email through Gmail.

smtplib Usage

This example is taken from this post at wikibooks.org
"""The first step is to create an SMTP object, each object is used for connection 
with one server."""

import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)

#Next, log in to the server
server.login("youremailusername", "password")

#Send the mail
msg = "
Hello!" # The /n separates the message from the headers
server.sendmail("you@gmail.com", "target@example.com", msg)
To include a From, To and Subject headers, we should use the email package,
since smtplib does not modify the contents or headers at all.

Email Package Overview

Python's email package contains many classes and functions for composing and
parsing email messages.

Email Package Usage

We start by only importing only the classes we need, this also saves us from
having to use the full module name later.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
Then we compose some of the basic message headers:
fromaddr = "you@gmail.com"
toaddr = "target@example.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Python email"
Next, we attach the body of the email to the MIME message:
body = "Python test mail"
msg.attach(MIMEText(body, 'plain'))
For sending the mail, we have to convert the object to a string, and then
use the same prodecure as above to send using the SMTP server..
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login("youremailusername", "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)

Verify an email address

The SMTP protocol includes a command to ask a server whether an address is valid. 

Usually VRFY is disabled to prevent spammers from finding legitimate email 
addresses,but if it is enabled you can ask the server about an address and
receive a status code indicating validity along with the user’s full name. 

This example is based on this post
import smtplib

server = smtplib.SMTP('mail')
server.set_debuglevel(True)  # show communication with the server
    dhellmann_result = server.verify('dhellmann')
    notthere_result = server.verify('notthere')

print 'dhellmann:', dhellmann_result
print 'notthere :', notthere_result

Sending Mails using Gmail

This example is taken from http://rosettacode.org/wiki/Send_an_email#Python
import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
              subject, message,
              login, password,
    header  = 'From: %s
' % from_addr
    header += 'To: %s
' % ','.join(to_addr_list)
    header += 'Cc: %s
' % ','.join(cc_addr_list)
    header += 'Subject: %s

' % subject
    message = header + message
    server = smtplib.SMTP(smtpserver)
    problems = server.sendmail(from_addr, to_addr_list, message)
Example Usage of above script
sendemail(from_addr    = 'python@RC.net', 
          to_addr_list = ['RC@gmail.com'],
          cc_addr_list = ['RC@xx.co.uk'], 
          subject      = 'Howdy', 
          message      = 'Howdy from a python function', 
          login        = 'pythonuser', 
          password     = 'XXXXX')
Sample Email Received
sendemail(from_addr    = 'python@RC.net', 
          to_addr_list = ['RC@gmail.com'],
          cc_addr_list = ['RC@xx.co.uk'], 
          subject      = 'Howdy', 
          message      = 'Howdy from a python function', 
          login        = 'pythonuser', 
          password     = 'XXXXX')
Python on Wikibooks.org

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.