At work I recently had to set up a solution that periodically checks a POP3 account on our M$ Exchange wannabe mailserver, and saves the attachments to some folder for further processing. As I didn't find a ready-to-go-solution for this on the web, just snippets here and there, and of course hundrets of other people asking the same, here it is.
You will need
- fetchmail
- procmail
- metamail (or uudeview, see first comment below)
In this example I'll use a POP3 account, the full mail will be backed up to ~/mail_backup, and attachments will be unpacked to ~/attachments. fetchmail also handles IMAP accounts just fine. Please refer to the fetchmail documentation.
Setting up fetchmail
First create a file $HOME/.fetchmailrc
poll my.pop3.server protocol pop3 user 'myuser' password 'mypassword' mda '/usr/bin/procmail -d %T'
Setting up procmail and metamail
Then we configure procmail so it forwards the messages to metamail in $HOME/.procmailrc
:0 *^content-Type: { # backup the complete mail first.. # you can leave out this part if you don't want a backup of the complete mail :0c: $HOME/mail_backup # Now the actual unpacking part # # this is the place where the attachments will be unpacked to METAMAIL_TMPDIR=$HOME/attachments # forward to metamail :0fw | metamail -w -y -x }
Regarding metamail, we tell it to ignore any mailcap file, so it doesn't use interpreters (-w), yanking the message and save the content raw (-y) and force it in non-interactive mode (-x).
That's it about it. We are ready for testing.
Test run
Now we simply fire up fetchmail, the rest should be magic.
fetchmail -kv