Skip to content

Instantly share code, notes, and snippets.

@Kassan424kh
Created September 3, 2024 13:04
Show Gist options
  • Save Kassan424kh/237669f89a2991da6dcad9f962b20653 to your computer and use it in GitHub Desktop.
Save Kassan424kh/237669f89a2991da6dcad9f962b20653 to your computer and use it in GitHub Desktop.
forward emails to an real smtp server
import smtpd
import asyncore
import smtplib
from email.message import EmailMessage
from email.parser import Parser, BytesParser
from email.policy import default
from base64 import b64decode
# Configuration for the real SMTP server
REAL_SMTP_SERVER = 'REAL_SMTP_SERVER'
REAL_SMTP_PORT = 587
REAL_SMTP_USERNAME = 'REAL_SMTP_USERNAME'
REAL_SMTP_PASSWORD = 'REAL_SMTP_PASSWORD'
# Local server configuration
LOCAL_SMTP_PORT = 25 # Port for the local SMTP server
class SMTPProxyServer(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
print(f"Received email from: {mailfrom}")
print(f"Recipients: {rcpttos}")
# Ensure data is parsed from bytes to an email message
email_message = BytesParser(policy=default).parsebytes(data)
# Forward the email to the real SMTP server
try:
with smtplib.SMTP(REAL_SMTP_SERVER, REAL_SMTP_PORT) as smtp:
smtp.starttls()
smtp.login(REAL_SMTP_USERNAME, REAL_SMTP_PASSWORD)
# Send the email
smtp.send_message(email_message, from_addr=mailfrom, to_addrs=rcpttos)
print("Email forwarded successfully.")
except Exception as e:
print(f"Failed to forward email: {e}")
# Set up the proxy server
def run_server():
server = SMTPProxyServer(('0.0.0.0', LOCAL_SMTP_PORT), None)
print(f"SMTP Proxy Server listening on port {LOCAL_SMTP_PORT}")
asyncore.loop()
if __name__ == "__main__":
run_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment