Python's smtplib makes it fairly easy to send mail if you don't need anything complicated and makes it possible for you to send complicated email if you desire.

Let's look at a simple Python function that will send a text message to a single email address. This code is available separately as simple_mail.py


import smtplib

def mail(serverURL=None, sender='', to='', subject='', text=''):
    """
    Usage:
    mail('somemailserver.com', 'me@example.com', 'someone@example.com', 'test', 'This is a test')
    """
    headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject)
    message = headers + text
    mailServer = smtplib.SMTP(serverURL)
    mailServer.sendmail(sender, to, message)
    mailServer.quit()

This defines a function mail with 5 parameters:
serverURLThe URL of the SMTP server to use
sender email address of sender
to email address of recipient
subject subject of message
text text of message
The line:
    headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to, subject)
creates the headers of the message - smtplib does not add headers for you, it assumes that the message you pass it includes the headers. The format string "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" forms the headers with header lines separated by \r\n (carriage-return/linefeed) pairs as required by RFC 822. After the headers there is an empty line to seperate the headers from the message text. This empty line is represented by the \r\n\r\n at the end of the format string.

Now that the headers are in place the line:

    message = headers + text
puts the headers and body text together to form the complete email message.

Now the message gets sent with:

    mailServer = smtplib.SMTP(serverURL)
    mailServer.sendmail(sender, to, message)
    mailServer.quit()
The first line creates an SMTP object called mailServer and opens a connection to the default SMTP port on serverURL, the second line sends the next line sends the message, and the third line disconnects from the server.

That's all there is to it, unless something goes wrong. There's no error handling in this code and the calls into smtplib can raise exceptions. Most of them should be fairly easy to figure out from the traceback. One that may be confusing is the exception raised when smtplib can't find an SMTP server at the URL given in serverURL, which is:
socket.gaierror: (7, 'No address associated with nodename')

Happy mailing.


This page created by James Thiele, who invites comments, questions, and corrections be addressed to jet@eskimo.com

Page created 19 December 2004