Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse mail's body using mailx and bash scripting

I am trying to automate certain part of my work using emails.Is there any method already available using mailx and bash which I can use to extract mail's body?

like image 372
Rajat Saxena Avatar asked Mar 24 '13 15:03

Rajat Saxena


2 Answers

formail from the procmail package does the job nicely as stated in the other answer, but here's a summary of what I think is the direct answer to the question:

$ sudo apt-get install procmail

$ cat test.eml | formail -x To
 [email protected]

$ cat test.eml | formail -x Subject
 hello

$ cat test.eml | formail -x Content
 multipart/alternative; boundary="f403043eea78e8658a0554677278"
like image 59
Sridhar Sarnobat Avatar answered Oct 20 '22 14:10

Sridhar Sarnobat


If this is mail delivered to a local user account by a sendmail-like MTA, then you can use procmail to parse email as it's being delivered.

On a system I was using, sendmail would examine the ~/.forward file, so I had this in ~username/.forward

# pipe incoming mail to procmail
# ref: http://www.panix.com/~elflord/unix/procmail.html
# ref: http://porkmail.org/era/procmail/mini-faq.html#forward
"|IFS=' ' && p=/usr/local/bin/procmail && test -x $p && exec $p -f- || exit 75 #username"

Then, ~username/.procmailrc contained:

# procmail tutorial: http://tldp.org/LDP/LG/issue14/procmail.html

PATH=/usr/local/bin:/bin:/usr/bin
MAILDIR=$HOME/Mail
DEFAULT=$HOME/Mail/inbox
LOGFILE=$HOME/procmail.`date +%Y-%m`.log
SHELL=/usr/bin/ksh

MY_XLOOP='X-Loop: [email protected]'
MY_RECIPIENT='[email protected]'


#############################################################################
# if the email comes from the client with a specific Subject,
# send a copy of the message to the processing script, and 
# carry on with the next recipe

:0c
* ^From:.*@clientdomain\.invalid
* ^Subject:.*Account.*(Request|Access|Approval)
| $HOME/bin/process_account_request_email.pl | \
  mailx -s "Account request results" $MY_RECIPIENT


#############################################################################
# forward all mail to mailing list
:0
* ! ^$MY_XLOOP
{
    # add a header
    # 'f' = filter: pass message to program and continue processing results 
    # 'h' = pass message headers to program
    # 'w' = wait for program to return
    :0fhw
    | formail -A "$MY_XLOOP"

    # then forward the message
    # 'c' = send a copy to recipient and continue processing
    :0c
    ! $MY_RECIPIENT
}

# if we get here, then the message has an X-Loop header.
# let it fall into $DEFAULT
like image 28
glenn jackman Avatar answered Oct 20 '22 16:10

glenn jackman