inotify: procmail for IMAP folders

Moving mail to an IMAP folder is easy. Often easier than “pipe the mail through this command” or even “forward the mail with all headers to this address”. But what magic can you use to get something done with the mail after moving it to the correct IMAP folder?

Using Courier IMAP and thus Mairdirs I came up with the following shell snippet:

cd $MAILDIR

inotifywait -m -q -e CREATE --format %f cur |
  while read mail ; do
        [ -f cur/$mail ] && $HOME/bin/process_mail < cur/$mail > /dev/null ;
        [ -f cur/$mail ] && rm cur/$mail ;
  done

It’s is not completely race condition free. cur/$mail can get renamed and will then be reprocessed. Interesting note: mail is moved from $MAILDIR/tmp to $MAILDIR/cur by link/unlink so the inotify-event is CREATE and not the expected MOVED_TO.

Any better solution?

1 Comment »

  1. Arne Jørgensen said,

    July 1, 2007 @ 2:01 pm

    I had the same idea as you - and your posting inspired me to actually do something about.

    What I wanted was an IMAP-folder called “Report-as-spam” and mail that I move into that folder would be reported ad spam via “spamassassin -r” and then deleted.

    I have a setup with Dovecot as IMAP-server and Dovecot is configured to use maildir as its mailstorage format. As opposed to your Cyrus the event from Dovecot is actually MOVED_TO when the mail is moved from $MAILDIR/tmp to $MAILDIR/current.

    I used incron (http://inotify.aiken.cz/?section=incron&page=about&lang=en) to run a shell-script that reports and deletes the mail.

    My incrontab is (one line):

    /var/maildir/arne/.Report-as-spam/cur IN_MOVED_TO /home/arne/usr/bin/report-as-spam $#

    A few lessons I learned was that there should be one and only one space between the event and the command. And incron doesn’t have a build the shell like syntax like cron — so don’t use “spamassassin -r && rm $@/$#” as the command.

    My report-as-spam shell script is (don’t know if it will bw shown correctly — but there nothing spooky in there):

    #!/bin/sh
    SPAMFILE=/var/maildir/arne/.Report-as-spam/cur/$1
    if [[ -f $SPAMFILE ]]; then
    /usr/bin/spamassassin -r $SPAMFILE && rm $SPAMFILE && logger Reported $SPAMFILE as spam
    fi

RSS feed for comments on this post · TrackBack URI

Leave a Comment