Quantcast
Channel: postfix | David Goodwin
Viewing all articles
Browse latest Browse all 4

python content_filter for Postfix (rewriting the subject)

$
0
0

A python script which can be used as a Postfix content_filter to headers email going through it … (example shows changing the Subject).

#!/usr/bin/python
from email import Parser
import smtplib
import sys
import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='/tmp/content-filter.log',
                    filemode='a')

# Get the CLI arguments.
try:
    cli_from = sys.argv[2].lower()
    cli_to = sys.argv[4:]
    logging.debug("To / From : %r" % sys.argv)
except:
    logging.error("Invalid to / from : %r" % sys.argv)
    sys.exit(69) # postfix will bounce the mail. retrying bad args won't work

logging.debug("From : %s, to : %r" % (cli_from, cli_to))
# Get the email content from STDIN.
content = ''.join(sys.stdin.readlines())
p = Parser.Parser()
parsed = p.parsestr(content, True)
#logging.debug("email source : %s" % parsed.as_string())

old_subject = parsed.get('Subject');

# remove the old header, and add a new one.
del parsed['subject']
parsed['Subject'] = "New Subject -- " + old_subject

# convert it back to a big string.
content = str(parsed)
# and let's try reinjecting it into Postfix.
command = ["/usr/sbin/sendmail", "-G", "-i", "-f", cli_from, cli_to]
stdout = ''
stderr = ''
retval = 0
try :
    process = Popen(command, stdin=PIPE)
    (stdout, stderr) = process.communicate(content);
    retval = process.wait()
    if retval == 0:
        logging.debug("Mail resent via sendmail, stdout: %s, stderr: %s" % (stdout, stderr))
        sys.exit(0)    
    else:
        raise Exception("retval not zero - %s" % retval)
except Exception, e:
    print "Error re-injecting via /usr/sbin/sendmail."
    logging.error("Error resending mail %s -- stdout:%s, stderr:%s, retval: %s" % (e, stdout, stderr, retval))
    sys.exit(75) # tempfail, we hope.

Viewing all articles
Browse latest Browse all 4

Trending Articles