On Linux and Unix operating systems, you can use fetchmail
to poll your IMAP e-mail account, and pass any new messages to procmail
. You could configure procmail to run scripts based on regular expression pattern matches in received messages.
To do this, you'll need to install the fetchmail and procmail packages. The following configuration allowed me to run a script for every new e-mail message is received in my e-mail account. I used Ubuntu 12.04 LTS.
In ~/.fetchmailrc
:
# .fetchmailrc checks my e-mail account for new messages, sends them to procmail
set logfile /home/myusername/fetchmail.log
poll mail.domain.com protocol IMAP
user "emailaccountname"
password 'emailpassword'
folder 'INBOX'
keep
ssl
mda "/usr/bin/procmail -f %F"
Note the keep
directive above, which ensures that messages are not removed from the IMAP server after they're retrieved.
In ~/.procmailrc
:
# .procmailrc received e-mails from fetchmail and runs a script
PATH=/usr/bin:/usr/local/bin
LOGFILE=/home/username/procmail.log
SHELL=/bin/sh
# This rule triggers for every e-mail message:
:0
| `/home/username/myscript.sh`
There are lots of tutorials online for fetchmail and procmail, and also tutorials for how to integrate the two (that's how I came up with the above).
Now if I run fetchmail
or fetchmail -v
the script /home/username/myscript.sh
runs once for every new message. I can run fetchmail in a cron, or configure fetchmail to run as a daemon with the set daemon 600
directive in .fetchmailrc
(where 600 is the number of seconds between polls).