Twisted Mail Tutorial: Building an SMTP Client from Scratch

Introduction

This tutorial will walk you through the creation of an extremely simple SMTP client application. By the time the tutorial is complete, you will understand how to create and start a TCP client speaking the SMTP protocol, have it connect to an appropriate mail exchange server, and transmit a message for delivery.

For the majority of this tutorial, twistd will be used to launch the application. Near the end we will explore other possibilities for starting a Twisted application. Until then, make sure that you have twistd installed and conveniently accessible for use in running each of the example .tac files.

SMTP Client 1

The first step is to create smtpclient-1.tac possible for use by twistd .

from twisted.application import service

The first line of the .tac file imports twisted.application.service , a module which contains many of the basic service classes and helper functions available in Twisted. In particular, we will be using the Application function to create a new application service . An application service simply acts as a central object on which to store certain kinds of deployment configuration.

application = service.Application("SMTP Client Tutorial")

The second line of the .tac file creates a new application service and binds it to the local name application . twistd requires this local name in each .tac file it runs. It uses various pieces of configuration on the object to determine its behavior. For example, "SMTP Client Tutorial" will be used as the name of the .tap file into which to serialize application state, should it be necessary to do so.

That does it for the first example. We now have enough of a .tac file to pass to twistd . If we run smtpclient-1.tac using the twistd command line:

twistd -ny smtpclient-1.tac

we are rewarded with the following output:

exarkun@boson:~/mail/tutorial/smtpclient$ twistd -ny smtpclient-1.tac
18:31 EST [-] Log opened.
18:31 EST [-] twistd 2.0.0 (/usr/bin/python2.4 2.4.1) starting up
18:31 EST [-] reactor class: twisted.internet.selectreactor.SelectReactor
18:31 EST [-] Loading smtpclient-1.tac...
18:31 EST [-] Loaded.

As we expected, not much is going on. We can shutdown this server by issuing ^C :

18:34 EST [-] Received SIGINT, shutting down.
18:34 EST [-] Main loop terminated.
18:34 EST [-] Server Shut Down.
exarkun@boson:~/mail/tutorial/smtpclient$

SMTP Client 2

The first version of our SMTP client wasn’t very interesting. It didn’t even establish any TCP connections! The smtpclient-2.tac will come a little bit clos