Chapter 8. Mail Servers

This chapter is about one of Twisted’s greatest strengths: running mail and news servers. Twisted includes modules that you can use to build SMTP, POP3, IMAP, and NNTP servers from scratch, which can be incredibly useful when you have a server application that needs to send, receive, or store email. Server email integration has traditionally required a heavyweight mail server, with a bunch of custom shell scripts to push and pull data between the mail server and your application. But by using Twisted, you can design a mail or news server that does exactly what you need, and that doesn’t even require a separate process. This chapter shows you how.

Accepting Mail with SMTP

As described in Chapter 7, SMTP is the Simple Mail Transfer Protocol, the basic means by which email messages are delivered on the Internet. SMTP is the most popular messaging protocol in use today: everyone uses email, and email uses SMTP.

This lab demonstrates how to write a simple SMTP server using Twisted. It shows how to accept SMTP connections, decide what to do with the incoming message based on the email address, and then process the message data.

How Do I Do That?

Write classes to implement the smtp.IMessage and smtp.IMessageDelivery interfaces. Then create a Factory that uses your implementation of IMessageDelivery to initialize the smtp.SMTP protocol. Example 8-1 accepts email for all addresses in a given domain and stores the messages to maildir directories.

Example 8-1. smtpserver.py ...

Get Twisted Network Programming Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.