Current File : /home/tdmfgi5/.imh/redirect_mail.py |
#!/opt/imh-python/bin/python
"""Redirects mail after account migration, during DNS propagation.
The script delivering this script to the account should replace
10.127.100.208 with the appropriate IP"""
import smtplib
import platform
import sys
import select
import email
def main():
"""Main logic: decode stdin as an email and attempt to re-deliver it"""
raw = sys.stdin.read()
raw_message = email.message_from_string(raw)
from_addr = raw_message['From']
to_addr = raw_message['To']
try:
raw_message.replace_header("From", from_addr)
raw_message.replace_header("To", to_addr)
server = smtplib.SMTP('10.127.100.208')
server.sendmail(from_addr, to_addr, raw_message.as_string())
server.quit()
except Exception as exc:
bounce = """From: Mail Delivery System <Mailer-Daemon@{0}>
To: {1}
Subject: Mail delivery failed: returning message to sender
This message was created automatically by mail delivery software.
A message that you sent could not be delivered to one or more of its
recipients. This is a permanent error. The following address(es) failed:
{1}
{2.__name__} {3}
------ This is a copy of the message, including all the headers. ------
{4}
""".format(platform.node(), from_addr, type(exc), vars(exc), raw)
server = smtplib.SMTP('127.0.0.1')
server.sendmail(to_addr, from_addr, bounce)
server.quit()
if __name__ == '__main__':
if not select.select([sys.stdin,], [], [], 0.0)[0]:
sys.exit(0)
main()