Filling the IIS7 SMTP hole with Python Goodness

Posted by Tom on 2012-10-11 14:43

I'm currently working on a site with a load of background processes that run and fire emails left, right and centre. And it's on IIS7, so I don't have a local SMTP server at my disposal. Dang.

But wait! I bet Python has some magical module which does crap like this. Could I just import SMTP from python and be on my merry way?

import smtpd
import asyncore
import os
import sys
from datetime import datetime

class StoreSMTP(smtpd.SMTPServer):
    def __init__(*args, **kwargs):
        smtpd.SMTPServer.__init__(*args, **kwargs)

    def process_message(self, peer, mailfrom, rcpttos, data):
        filename = '{0}_{1}.txt'.format(rcpttos[0], datetime.now().strftime('%Y%m%d-%H%M%S-%f'))
        print('Writing: ' + filename)
        f = open(os.path.join(self._remoteaddr, filename), 'a')
        f.write(data)
        f.close()

if __name__ == '__main__':
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    if not os.path.exists(path):
        os.mkdir(path)
    print('Running [' + path + '] . . .')
    server = StoreSMTP(('localhost', 25), path)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        server.close()

I guess so.