使用mailx和bash脚本解析邮件正文

Raj*_*ena 5 unix linux bash mailx

我正在尝试使用电子邮件使工作的某些部分自动化。使用mailx和bash是否已有可用的方法来提取邮件正文?

Sri*_*bat 5

formailprocmail正如其他答案中所述,从包中可以很好地完成这项工作,但这里总结了我认为是问题的直接答案:

$ 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"
Run Code Online (Sandbox Code Playgroud)

  • 要仅提取正文,请使用 `formail -I "" < "$your_mail_file"` (3认同)

gle*_*man 2

如果这是由类似于 sendmail 的 MTA 传递到本地用户帐户的邮件,那么您可以使用procmail在传递电子邮件时解析电子邮件。

在我使用的系统上,sendmail 会检查该~/.forward文件,因此我将其放在 ~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"
Run Code Online (Sandbox Code Playgroud)

然后,~username/.procmailrc包含:

# 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
Run Code Online (Sandbox Code Playgroud)

  • 如果无法使用 procmail 怎么办?我使用 Offlineimap 将外部邮件放入文件夹中,并希望解析这些邮件:http://stackoverflow.com/q/36168224/1069083 (2认同)