Python mail filter

Ulf Göransson ug at algonet.se
Wed Feb 9 05:22:35 EST 2005


Mailer wrote:
> The basic premise, as I understand is this:
> 
> Read mail from stdin
> Parse headers etc using rfc822 or email module
> Process
> 
> # Now I need to do one of the following:
> 
> # Discard mail
> # Pass through
> # Forward to another account, possibly modifying the mail
> 
> Now that I have coded up some stuff, the first looks easy - mails are
> getting lost. So the question is (may not be entirely specific to Python),
> how do I achieve the other two?
> 
> Currently, I have set up a .forward that pipes the mail to my script. I can
> verify that this works by dumping the contents to a file. If I write to
> stdout, however, the mail is not delivered. That doesn't quite look right
> either - it's probably too late for the MTA to pick up. What I want to do is
> to pass the processed mail back to Postfix so it can deliver it to the
> correct local mail box.

I think something like this might work (snipped from a small script I 
use to email log files to myself):

smtp = smtplib.SMTP('localhost')
smtp.sendmail(sender, rcpt, msg.as_string())
smtp.close()

Regardless of MTA software, this should resend whatever is in msg (in my 
case a MIMEMultipart). If it should be forwarded, just change rcpt and 
the To: header.

Unless of course, the server is configured to block messages sent by 
localhost claiming to be from somewhere else...

/ug



More information about the Python-list mailing list