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:


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 ;

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?