55

I'm running a bash script in cron to send mail to multiple recipients when a certain condition is met.

I've coded the variables like this:

subject="Subject"
from="user@example.com"
recipients="user1@mail.example user2@mail.example"
mail="subject:$subject\nfrom:$from\nExample Message"

And the actual sending:

echo -e $mail | /usr/sbin/sendmail "$recipients"

The problem is that only user2@mail.example is receiving the email. How can I change this so all the recipients receive the email?

NOTE: The solution has to be with sendmail, I'm using jailshell and it seems to be the only available method

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Amir
  • 2,082
  • 4
  • 22
  • 28

4 Answers4

97

Try doing this:

recipients="user1@mail.example,user2@mail.example,user3@mail.example"

And another approach, using shell here-doc:

/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from

Example Message
EOF

Be sure to separate the headers from the body with a blank line as per RFC 822.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
10

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add your recipient list to message itself like To: someone@example.com someother@nowhere.example right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Harijs Krūtainis
  • 1,261
  • 14
  • 13
  • When I pass the `-t` option, I get `sendmail: recipients with -t option not supported`. Any ideas? Thanks. – Vassilis Oct 28 '16 at 09:01
8

to use sendmail from the shell script

subject="mail subject"
body="Hello World"
from="me@example.com"
to="recipient1@example.com,recipient2@example.com"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Denish Thummar
  • 199
  • 2
  • 4
0

For postfix sendmail, I am adding one line command useful for scripting

I had problem adding recipients in default position in the end of sendmail command in RHEL (Undisclosed Recipients) and piping echo command saved the day.

Option -f found from http://www.postfix.org/sendmail.1.html

Please note that syntax in echo is important, try echo to a file to check before attempting with sendmail.

echo -e "To:receiver1@domain1, receiver2@domain2 \nSubject:Subject of email \n\nBody of email.\n" | /usr/sbin/sendmail -f sender@domain -F sendername -it

craigdfrench
  • 972
  • 10
  • 20