-
-
Save teward/2b3b9d1852a6958c7fcea4021e1797a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Libraries | |
import smtplib | |
import smtpd | |
import asyncore | |
import email | |
import sys | |
from datetime import datetime | |
print('Starting custom mail handling server...') | |
# We need to know where the SMTP server is heh. | |
SMTP_OUTBOUND = 'localhost' | |
# We also need to know what we want the "FROM" address to be | |
FROM_ADDR = "foo@bar.baz" | |
DESTINATION_ADDRESS = "foo@bar.baz" | |
############# | |
############# | |
# SMTP SERVER | |
############# | |
############# | |
# noinspection PyMissingTypeHints,PyBroadException | |
class AutoForwardHandlerSMTP(smtpd.SMTPServer): | |
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): | |
print('MESSAGE RECEIVED - [%s]' % datetime.now().strftime('%Y-%m-%d %H:%M:%S')) | |
print('Receiving message from:', peer) | |
print('Message addressed from:', mailfrom) | |
print('Message addressed to :', rcpttos) | |
print('Message length :', len(data)) | |
print(data) | |
# Flush the output buffered (handy with the nohup launch) | |
sys.stdout.flush() | |
# Analyze and extract data headers | |
msg = email.message_from_string(data) | |
orig_from = '' | |
try: | |
orig_from = msg['From'] | |
msg['Reply-To'] = orig_from | |
# We have to use 'replace header' methods to overwrite existing headers. | |
msg.replace_header("From", FROM_ADDR) | |
except: | |
print("Error manipulating headers:", sys.exc_info()[0]) | |
conn = smtplib.SMTP(SMTP_OUTBOUND, 10025) | |
conn.sendmail(FROM_ADDR, msg["To"], msg.as_string()) | |
# Flush the output buffered (handy with the nohup launch) | |
print("\n\n") | |
sys.stdout.flush() | |
return | |
# Listen to port 25 ( 0.0.0.0 can be replaced by the ip of your server but that will work with 0.0.0.0 ) | |
server = AutoForwardHandlerSMTP(('0.0.0.0', 25), None) | |
# Wait for incoming emails | |
asyncore.loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment