Simple SMTP server

Tim Williams listserver at tdw.net
Thu Jun 9 16:20:41 CEST 2005


----- Original Message ----- 
From: "Jesse Noller" <jnoller at gmail.com>

> I am looking at implementing a simple SMTP server in python - I know
> about the smtpd module, but I am looking for code examples/snippets as
> the documentation is sparse.
>
> If anyone has any good examples/recipes I'd greatly appreciate it.

This is a test server I put together (part adapted from somewhere else)
earlier in the week,   it is multithreaded inbound.   You could add your
required functionality quite easily.   It currently starts on port 2525

(watch out for line-wraps)

##
#! /usr/bin/python

import sys
from socket import *
from SocketServer import *


class SMTPServer(ThreadingMixIn, TCPServer):

    #
    # other functions exist here in the live server
    #

    def noFunction():
        pass
#end of class SMTPServer

class SMTPRequestHandler(StreamRequestHandler):
    def handle(self):

        self.terminated = 0
        self.SendResponse('220 ** Welcome **')

        commands={ 'HELO' : self.__HELO,            # supported commands
                   'QUIT' : self.__QUIT,
                   #'MAIL' : self.__MAIL,
                   #'RCPT' : self.__RCPT,
                   'NOOP' : self.__NOOP,
                   #'RSET' : self.__RSET,
                   'EHLO' : self.__HELO,            # handled by HELO
                   #'DATA' : self.__DATA,
                   }

        while not self.terminated:
            try:
                self.inputline = self.rfile.readline()
                self.inputline = self.inputline.rstrip().upper()
            except:
                self.inputline = '*?*'
            request = self.inputline.split()
            print "request=",request
            if request and commands.has_key(request[0]):      # eg: if
has_key FROM
                commands[request[0]](request)
            else:
                self.SendResponse("?? "+ self.inputline)

    def __HELO(self,request):
        if request[0]== 'HELO':
            self.SendResponse('250 2.1.0 Hello')
        else:
            self.SendResponse('250-Hello\r\n250-SIZE
9999999\r\n250-ENHANCEDSTATUSCODES\r\n250 HELP')

    def __NOOP(self,request):
        self.SendResponse('250 2.1.0 OK')

    def __QUIT(self,request):
        self.terminated = 1
        self.SendResponse('Goodbye')
        print "Session Closed"

    def SendResponse(self,msg):
        print msg
        msg = msg + '\r\n'
        self.wfile.write(msg)
        self.wfile.flush()
# end of class SMTPRequestHandler

def StartSMTPServer():
    print '*'*35
    print 'Server Starting, CTRL-C to end'
    print '*'*35
    setdefaulttimeout( 30  )  # timeout incoming connections
    server = SMTPServer(('', 2525 ), SMTPRequestHandler)
    server.serve_forever()
#end of def StartSMTPServer

if __name__ == '__main__':

    StartSMTPServer()






More information about the Python-list mailing list