Search
Search Menu

Filtering mail attachments with maildrop and python

For a new feature of our application we had to filter incoming emails based on header values in attached emails. As I could not find examples on how to filter on attachments directly with maildropfilter, I decided to handle the attachments with an external script. In the solution described below, the script returns a value but instead it could also modify the incoming mail and then one would use the xfilter instruction of maildropfilter.

The python script reads the email from stdin using the email package and then iterates over all the parts and subparts of the message object tree. In our example we are looking for a header called ‘x-mailer’ and if the value is BigMailer, we return a value to the maildrop filter.

#!/usr/bin/env python
 
import email
import sys
 
msg = email.message_from_file(sys.stdin)
 
for part in msg.walk():
        if 'x-mailer' in part:
                if part['x-mailer'] == 'BigMailer':
                        print "BigMailer"
                        sys.exit(0)

From maildroprc the python script is being executed when there is a match for a certain subject and in case the script returns ‘BigMailer’, the email is being delivered to the mybigmailer mailbox.

if (/^Subject:.*Mail with attachment mail/)
{
    SOURCE=`/opt/csw/bin/python /opt/csw/etc/maildrop/myfilter.py`
    if ($SOURCE eq "BigMailer")
    {
     to /vmail/mybigmailer/
     exit
    }
}

1 Comment Write a comment

  1. found this via google. solved my issue (how to go from mailfilter to arbitrary python code). thanks

Leave a Comment

Required fields are marked *.