new_contents: #!/usr/bin/env python
  '''SMTP server'''
  from __future__ import print_function
  from smtpd import SMTPServer
  from optparse import OptionParser
  import asyncore
  import os
  import sys
  import time
  import inspect
  
  
  # shut up about constants pylint!
  # pylint: disable-msg=C0103
  
  class CustomSMTPServer(SMTPServer):
      '''Custom SMTP receiver class that writes output to individual files on disk'''
  
      def __init__(self, localaddr, remoteaddr, outputdir, debug=False):
          '''Initialise'''
          self.outputdir = outputdir
          self.debug = debug
          if not (os.path.exists(outputdir) and os.path.isdir(outputdir)):
              raise ValueError('Provided output dir does not exist or is not a directory')
          SMTPServer.__init__(self, localaddr, remoteaddr)
  
  
      def get_messageid(self, data):
          '''Gets the sanitised message id from a message or a random hex string if missing'''
          allowed = '._-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
          m_ids = [a for a in data.split('\n') if a.startswith('Message-ID: ')]
          m_id = m_ids[0].split(': ', 1)[1] if m_ids else os.urandom(20).encode('hex')
          m_id = m_id.replace('@', '_at_')
          return ''.join([a for a in m_id if a in allowed])
  
  
      def process_message(self, peer, mailfrom, rcpttos, data):
          '''Process received messages'''
  
          # hacky method of getting HELO header
          frame = inspect.currentframe().f_back
          try:
              # pylint: disable-msg=W0212
              helo = str(frame.f_locals['self']._SMTPChannel__greeting) + ' '
          except AttributeError:
              helo = ''
  
  
          headers = []
          headers.append('Received: from ' + helo + ':'.join([str(a) for a in peer]))
          headers.append('Rcpt date: ' + time.strftime('%c %Z'))
          headers.append('Rcpt from: ' + mailfrom)
          headers.append('Rcpt to: ' + ', '.join([a for a in rcpttos]))
          if self.debug:
              for header in headers:
                  print(header)
              print(data)
          message_id = self.get_messageid(data)
          time_stamp = time.strftime('%Y%m%d%H%M%S')
          out = os.path.join(self.outputdir, time_stamp + '_' + message_id)
          open(out, 'w').write('\n'.join([a for a in headers]) + '\n' + data)
          return
  
  
  if __name__ == '__main__':
      parser = OptionParser(usage='%prog [options] host port output_directory')
      parser.add_option('-d', '--debug', dest='debug', default=False,
                        action='store_true', help='show debugging messages')
      opts, args = parser.parse_args()
  
      try:
          host = args[0]
          port = int(args[1])
          output = args[2]
      except (ValueError, NameError, IndexError):
          print(parser.format_help())
          sys.exit(1)
  
      try:
          smtp_server = CustomSMTPServer((host, port), None, output, debug=opts.debug)
      except ValueError:
          print('Provided output_directory does not exist')
          sys.exit(1)
  
      asyncore.loop()
  
subject: Create smtp_receiver.py