How to set the From email address for mailx command?

前端 未结 8 752
鱼传尺愫
鱼传尺愫 2020-12-24 05:28

I am working on a KornShell (ksh) script running on a Solaris server that will send out an email when and error condition is met. I am sending the email via mailx

8条回答
  •  失恋的感觉
    2020-12-24 06:11

    Just ran into this syntax problem on a CentOS 7 machine.

    On a very old Ubuntu machine running mail, the syntax for a nicely composed email is

    echo -e "$body" | mail -s "$subject" -a "From: Sender Name <$sender>" "$recipient"
    

    However on a CentOS 7 box which came with mailx installed, it's quite different:

    echo -e "$body" | mail -s "$subject" -S "from=Sender Name <$sender>" "$recipient"
    

    Consulting man mail indicates that -r is deprecated and the 'From' sender address should now be set directly using -S "variable=value".

    In these and subsequent examples, I'm defining $sender as "Sender Name " and $recipients as "recipient.name@domain.tld" as I do in my bash script.

    You may then find, as I did, that when you try to generate the email's body content in your script at the point of sending the email, you encounter a strange behaviour where the email body is instead attached as a binary file ("ATT00001.bin", "application/octet-stream" or "noname", depending on client).

    This behaviour is how Heirloom mailx handles unrecognised / control characters in text input. (More info: https://access.redhat.com/solutions/1136493, which itself references the mailx man page for the solution.)

    To get around this, I used a method which pipes the generated output through tr before passing to mail, and also specifies the charset of the email:

    echo -e "$body" | tr -d \\r | mail -s "$subject" -S "from=$sender" -S "sendcharsets=utf-8,iso-8859-1" "$recipients"
    

    In my script, I'm also explicitly delaring the locale beforehand as it's run as a cronjob (and cron doesn't inherit environmental variables):

    LANG="en_GB.UTF8" ; export LANG ;
    

    (An alternate method of setting locales for cronjobs is discussed here)

    More info on these workarounds via https://stackoverflow.com/a/29826988/253139 and https://stackoverflow.com/a/3120227/253139.

提交回复
热议问题