Mail Processing – How to Read One Message at a Time from /var/mail

mailxmuttpostfix

Lets say I have 5 messages in /var/mail/ and I want to read one message at a time and then do some string search in that mail before moving on to the next message. Is there a command that I can use to parse one message at a time ?

I am looking to write a bash script which will read all messages in an mbox file & then read them one at a time so that I can then extract Subject, To, From & Status of the message(bounceback code). My plan was to use grepmail to get count of emails in the file and then use this count in a for loop to get one mail at a time and them perform operation on the text. Something like:

$count = grepmail -r . /var/mail/user | awk '{print $2}'
for($i=1;$i<=$count;$i++) {
    $content = *GetMessage* -number $i /var/mail/user
    ...
    Do string operation on this message & save to $DelimitedData
    ...
}
$Delimiteddata

I can't figure out how to pickup single message at a time to perform string operation on them. Can someone please guide me which command/program can help me do this non interactively.

Best Answer

The formail tool from procmail (available in any distribution, it's a classic) is designed precisely for this purpose.

Basic usage:

formail -s myprogram --option

runs myprogram --option on each mail in turn. The program receives each mail on its standard input.

Related Question