Sending Emails with Python

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

"""The first step is to create an SMTP object, each object is used for connection 
with one server."""

import smtplib
server = smtplib.SMTP('', 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("", "", 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 = ""
toaddr = ""
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('', 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

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    = '', 
          to_addr_list = [''],
          cc_addr_list = [''], 
          subject      = 'Howdy', 
          message      = 'Howdy from a python function', 
          login        = 'pythonuser', 
          password     = 'XXXXX')
Sample Email Received
sendemail(from_addr    = '', 
          to_addr_list = [''],
          cc_addr_list = [''], 
          subject      = 'Howdy', 
          message      = 'Howdy from a python function', 
          login        = 'pythonuser', 
          password     = 'XXXXX')
Python on

Leave a Reply

Your email address will not be published. Required fields are marked *