Advertisement
Kagee

SMTP-to-file

Jan 26th, 2015
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """A noddy fake smtp server."""
  3.  
  4. from datetime import datetime
  5. import smtpd
  6. import asyncore
  7. import re
  8.  
  9. class FakeSMTPServer(smtpd.SMTPServer):
  10.     """A Fake smtp server"""
  11.  
  12.     def __init__(*args, **kwargs):
  13.         print "Running fake smtp server on port 25"
  14.         smtpd.SMTPServer.__init__(*args, **kwargs)
  15.  
  16.     def process_message(self, peer, mailfrom, rcpttos, data):
  17.         tos = "_and_".join(rcpttos).replace("@", "_at_")
  18.         ts = datetime.now().isoformat().replace(":","-")
  19.         path = re.sub("[^A-z0-9/-]", "_", "/tmp/email/%s-%s" % (ts, tos))
  20.         with open(path, "w") as f:
  21.             inheaders = 1
  22.             lines = data.split('\n')
  23.             print >>f, "Peer : %s" % (peer,)
  24.             print >>f, "From : %s" % (mailfrom,)
  25.             print >>f, "To[s]: %s" % (rcpttos,)
  26.             print >>f, '---------- MESSAGE FOLLOWS ----------'
  27.             for line in lines:
  28.                 # headers first
  29.                 if inheaders and not line:
  30.                     print >>f, 'X-Peer:', peer[0]
  31.                     inheaders = 0
  32.                 print >>f, line
  33.             print >>f, '------------ END MESSAGE ------------'
  34.  
  35. if __name__ == "__main__":
  36.     smtp_server = FakeSMTPServer(('localhost', 25), None)
  37.     try:
  38.         asyncore.loop()
  39.     except KeyboardInterrupt:
  40.         smtp_server.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement