Skip to content

Instantly share code, notes, and snippets.

@ltpitt
Created June 19, 2023 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ltpitt/10723c221b076ffb5bfdd379ac62a356 to your computer and use it in GitHub Desktop.
Save ltpitt/10723c221b076ffb5bfdd379ac62a356 to your computer and use it in GitHub Desktop.
Fake SMTP server in Python that saves received email in TMP folder and opens them right away
import argparse
import asyncore
import logging
import os
import platform
import smtpd
import subprocess
import tempfile
from datetime import datetime
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
parser = argparse.ArgumentParser()
parser.add_argument('--open', action='store_true', help='Automatically open email with default email program')
args = parser.parse_args()
args.open = True
class FakeSMTPServer(smtpd.SMTPServer):
def __init__(self, localaddr, remoteaddr):
super().__init__(localaddr, remoteaddr)
logging.info(f'Starting fake SMTP server on {localaddr[0]}:{localaddr[1]}')
def process_message(self, peer, mailfrom, rcpttos, data, mail_options=None, rcpt_options=None):
temp_dir = tempfile.gettempdir()
date_time = datetime.now().strftime('%Y%m%d%H%M%S')
file_name = os.path.join(temp_dir, f'email_{date_time}.msg')
with open(file_name, 'wb') as f:
f.write(data)
logging.info(f'Saved email from {mailfrom} to {rcpttos} to: {file_name}')
if args.open:
if platform.system() == 'Linux':
subprocess.call(['xdg-open', file_name])
elif platform.system() == 'Darwin':
subprocess.call(['open', file_name])
elif platform.system() == 'Windows':
subprocess.call(['start', file_name], shell=True)
server = FakeSMTPServer(('127.0.0.1', 1025), None)
asyncore.loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment