Fake mail server template

Here is a basic template for a fake mail server using Python and the smtpd module:

fake_smtp_server.py

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class FakeSMTPServer:
    def __init__(self, host='localhost', port=25):
        self.host = host
        self.port = port
        self.smtpd = smtplib.SMTPServer((host, port))

    def start(self):
        self.smtpd.start()

    def stop(self):
        self.smtpd.quit()

    def handle_message(self, connection, command, mailfrom, rcpttos, data):
        # Handle incoming email message
        message = MIMEMultipart()
        message['From'] = mailfrom
        message['To'] = rcpttos[0]
        message['Subject'] = 'Test Email'
        message.attach(MIMEText('This is a test email', 'plain'))

        # Send response to client
        connection.send_response(b'250 OK')
        connection.send_data(message.as_string())

    def run(self):
        self.start()
        print(f"Fake SMTP server started on {self.host}:{self.port}")
        while True:
            # Wait for incoming connections
            connection, address = self.smtpd.accept()
            print(f"Connection from {address}")
            command = connection.recv_line()
            if command == b'HELO':
                connection.send_response(b'250 Hello')
            elif command == b'MAIL':
                mailfrom = connection.recv_line().decode()
                rcpttos = connection.recv_line().decode().split(',')
                self.handle_message(connection, command, mailfrom, rcpttos, data=connection.recv_data())
            elif command == b'QUIT':
                connection.send_response(b'221 Bye')
                connection.close()
            else:
                connection.send_response(b'500 Unknown command')
                connection.close()

if __name__ == '__main__':
    server = FakeSMTPServer()
    server.run()

This script creates a fake SMTP server that listens on port 25 (the default SMTP port) and responds to incoming email messages. When a message is received, it creates a new MIMEMultipart object and sets the From, To, and Subject headers. It then sends a response to the client with the message as a string.

To use this script, simply run it and then use a mail client (such as telnet or a mail client like Thunderbird) to connect to the fake SMTP server. For example:

$ python fake_smtp_server.py
Fake SMTP server started on localhost:25
$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
HELO client
250 Hello
MAIL FROM:<[email protected]>
250 2.1.0 Ok
RCPT TO:<[email protected]>
250 2.1.5 Ok
DATA
This is a test email
.
250 2.0.0 Ok: queued as 1234567890
QUIT
221 Bye
Connection closed.

Note that this is a very basic implementation and does not support many of the features of a real SMTP server, such as authentication, encryption, or message queuing.