Login

SMTP sink server

Author:
twinsant
Posted:
March 9, 2007
Language:
Python
Version:
Pre .96
Tags:
email debug smtp server eml
Score:
41 (after 41 ratings)

In development, we need a SMTP Server to see the results of send mail via SMTP protocol in Python application. Instead of configure a mail daemon, we could use this little script to receive the SMTP request, and save each session into an EML file. *.eml could be viewed with your favorite email client, you need not send them out.

EML description

Update: Fix bug for overwrite files when received multi-message in one SMTP session.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from datetime import datetime
import asyncore
from smtpd import SMTPServer

class 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 += 1


def run():
    foo = EmlServer(('localhost', 25), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        pass


if __name__ == '__main__':
	run()

More like this

  1. One line SMTP sink server by Baguage 2 years, 1 month ago
  2. Better debugging mail server by yourcelf 5 years, 6 months ago
  3. Email queue in DB by fish2000 6 years, 4 months ago
  4. SMTP sink server: prettier output by huwshimi 6 years, 3 months ago
  5. Simple class to organize email templates by jean 1 year, 4 months ago

Comments

twinsant (on March 20, 2007):
<p>I'm so happy to learn that it's helpful to you:)</p> <p>Note: This sinppet has been fixed for bug overwriting files when received multi-messages in on session.</p>

#

zgoda (on July 13, 2007):
<p>This snippet requires running it from root account. You have to add some code to bind to a port number over 1024. Like in line 17 and 18:</p> <pre>def run(port=25): foo = EmlServer(('localhost', port), None) </pre> <p>and later in line 26 and later:</p> <pre>try: port = int(sys.argv[1]) except IndexError: sys.exit("Usage: smtpsink.py <port>") run(port) </pre> <p>Of course, you have to import sys at the top of the module too.</p>

#

arne (on August 27, 2007):
<p>very useful, thanks for sharing this snippet</p>

#

vung (on December 23, 2007):
<p>Line 12 should be: f.close()</p>

#

zero (on February 12, 2008):
<p>instead of writing an .eml you can directly send your mail to the built in python mail server. on a shell do:</p> <pre>sudo /usr/lib/python2.4/smtpd.py -n -c DebuggingServer localhost:25 </pre> <p>then send your mails to localhost:25 and you will see the results immediately :-)</p>

#

hasenj (on September 21, 2008):
<p>thank you man, this is awesome!! helps so much!</p>

#

bartTC (on June 3, 2012):
<p>I'm still using this after years.</p>

#

jezdez (on June 3, 2012):
<p>Me too!</p>

#

Please login first before commenting.