Python - Fake Smtp and test email


  1. End result. Save a test e-mail message to mail folder

    b'From: From Person <>
    To: To Person <>
    Subject: Fake SMTP e-mail test
    This is a fake e-mail message.'

  2. Create and copy / paste following codes.

    import argparse
    import asyncore
    import smtpd
    from datetime import datetime
    from pathlib import Path
    def get_date_time_stamp():
        today =
        timestamp = str(today.timestamp()).split('.')[0]
        return f'{today:%m_%d_%Y}_{timestamp}' # 10_26_2021_1635302925
    class FakeSMTPServer(smtpd.SMTPServer):
        def __init__(*args, **kwargs):
            smtpd.SMTPServer.__init__(*args, **kwargs)
            print ('Running fake smtp server')
        def process_message(*args, **kwargs):
            destination = Path.cwd() / f'mail/{get_date_time_stamp()}.eml'
            with open (destination, 'w') as file:
                file.writelines(str(args[4]).replace('\\n', '\n')) # email content only and replace \n to newline
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument('-s', '--server', type=str, default='', help='server to listen on. Default')
        parser.add_argument('-p', '--port', type=int, default=2525, help='port to listen on. Default 2525.')
        args = parser.parse_args()
        # python -s -p 2525
        smtp_server = FakeSMTPServer((args.server, args.port), None)
        except KeyboardInterrupt:
  3. Create and copy / paste following codes

    import smtplib
    from_email = ''
    to_emails = ['']
    message = '''From: From Person <>
    To: To Person <>
    Subject: SMTP e-mail test
    This is a fake e-mail message.
    if __name__ == '__main__':
            mail = smtplib.SMTP('', 2525) # Enter host and port from
            mail.sendmail(from_email, to_emails, message)         
            print ('Successfully sent email')
            print ('Error: unable to send email')
  4. Run Ctrl + F5 or Right click >> "Run Python File in Terminal" within VS Code or run it manually if specific host and IP are required.

    $ python -s 123.456.678.9 -p 25
  5. Open a new terminal and run Host and port must match with

    $ python 


taeheechoi © 2023