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?
Asked
Active
Viewed 6,595 times
2 Answers
5
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
test@mydomain.com
$ cat test.eml | formail -x Subject
hello
$ cat test.eml | formail -x Content
multipart/alternative; boundary="f403043eea78e8658a0554677278"

Sridhar Sarnobat
- 25,183
- 12
- 93
- 106
-
3To extract the body only, use `formail -I "" < "$your_mail_file"` – mivk Aug 17 '19 at 13:13
2
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: username@hostname.subdomain.example.com'
MY_RECIPIENT='mailing.list@example.com'
#############################################################################
# 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

slm
- 15,396
- 12
- 109
- 124

glenn jackman
- 238,783
- 38
- 220
- 352
-
2What if you cannot use procmail? I use offlineimap to get external mails into a folder and would like to parse those: http://stackoverflow.com/q/36168224/1069083 – rubo77 Mar 23 '16 at 10:16