A simple SMTP server (in Python) A simple SMTP server (in Python) python python

A simple SMTP server (in Python)


Take a look at this SMTP sink server:

from __future__ import print_functionfrom datetime import datetimeimport asyncorefrom smtpd import SMTPServerclass EmlServer(SMTPServer):    no = 0    def process_message(self, peer, mailfrom, rcpttos, data):        filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'),                self.no)        f = open(filename, 'w')        f.write(data)        f.close        print('%s saved.' % filename)        self.no += 1def run():    # start the smtp server on localhost:1025    foo = EmlServer(('localhost', 1025), None)    try:        asyncore.loop()    except KeyboardInterrupt:        passif __name__ == '__main__':    run()

It uses smtpd.SMTPServer to dump emails to files.


There are really 2 things required to send an email:

  • An SMTP Server - This can either be the Python SMTP Server or you can use GMail or your ISP's server. Chances are you don't need to run your own.
  • An SMTP Library - Something that will send an email request to the SMTP server. Python ships with a library called smtplib that can do that for you. There is tons of information on how to use it here: http://docs.python.org/library/smtplib.html

For reading, there are two options depending on what server you are reading the email from.


To get Hasen's script working in Python 3 I had to tweak it slightly:

from datetime import datetimeimport asyncorefrom smtpd import SMTPServerclass EmlServer(SMTPServer):    no = 0    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):        filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'),            self.no)        print(filename)        f = open(filename, 'wb')        f.write(data)        f.close        print('%s saved.' % filename)        self.no += 1def run():    EmlServer(('localhost', 25), None)    try:        asyncore.loop()    except KeyboardInterrupt:        passif __name__ == '__main__':    run()