Script Help - Parse /var/spool/mail/user

CentOS 5.x | SendMail

Hi guys,

Is there an easy way to retrieve individual messages from /var/spool/mail/? I have an idea for a really simple script and would like to check each individual message for something.

The scenario would be:

1) new email arrives in inbox. 2) Script checks for certain string. 3) If string is found, script retrieves various header info and emails info to address.

I realize that a milter would probably be the way to go but I was hoping to find a way to do this with a shell script as I want to practice that. The problem is that I can't seem to find a way to parse or otherwise isolate the individual messages. When I examine /var/spool/mail/, I see a big file with multiple messages and no unique delimiter between messages.


Solution 1:

If you ignore simple shell scripts almost every single programming language has a library to parse a mbox formated mailbox.

  • http://docs.python.org/library/mailbox.html
  • http://search.cpan.org/~dcoppit/Mail-Mbox-MessageParser-1.5002/lib/Mail/Mbox/MessageParser/Perl.pm
  • http://www.phpclasses.org/browse/file/3127.html

Of course if you look around you can also find lots of POP3 and IMAP client libraries as well.

You should also be able to use something like procmail or maildrop to filter your messages.

Solution 2:

Classically you would do this kind of things when the mail is received, using an MDA such as procmail. If you already have a mailbox, procmail comes with formail(1) which lets you run a program on each mail in a mailbox and has facilities to filter and rewrite headers.