Sending email using unix shell scripting Sending email using unix shell scripting shell shell

Sending email using unix shell scripting


You forgot the quotes:

echo $body | mail $receiver -s "$subj"

Note that you must use double quotes (otherwise, the variable won't be expanded).

Now the question is: Why double quotes around $subj and not $body or $receiver. The answer is that echo doesn't care about the number of arguments. So if $body expands to several words, echo will just print all of them with a single space in between. Here, the quotes would only matter if you wanted to preserve double spaces.

As for $receiver, this works because it expands only to a single word (no spaces). It would break for mail addresses like John Doe <doe@none.com>.


Old question, I know, but likely ever popular. My favorite way provides more flexibility and has worked on any UNIX/POSIX environment I have used since the dawn of my UNIX use. Only the sendmail path may change to meet the local implementation.

sed <<"ENDMAIL" -e '/^From [^ ]/s/^From /From  /' -e 's/^\.$/. /' | /usr/sbin/sendmail -t -f "$sender"To: $receiver, $receiver2, $receiver3From: $senderSubject: $subjAny-Other-Standard-Optional-Headers: place headers in any order, including,MIME-Version: 1.0Content-Type: text/plain;X-Mailer: any identity you want to give your E-mailing applicationX-Your-Custom-Headers: X- headers can be your own private headersx-Last-Header: a blank line MUST follow the last headerYour body text hereENDMAIL
  • In many environments lines starting with "From " then a non-space, are reserved as an internal "start new message" marker in bundles of messages. Stick an extra space in to avoid truncating your messages.Though for maximum portability on any system with perl replace sed with: perl -p -e 's/^From ([^ ])/From $1/' as sed in some UNIX systems is not really up to what I like and especially if echo "From me" gets a third space when piped into your local sed.
  • A line consisting of just a period is the classic end-of-message marker to the sendmail family of agents. Change such lines to end in a space... looks the same but no longer triggers end-of-message truncations.
  • You can use full E-mail addresses, like:
    "Long Name" <email-addr@example.com>
  • Except for sendmail's -f option all the text needing quotes, escapes, and the like, are buried in the "here document", which suddenly are much less bothersome.
  • Read the man page on the sendmail "-" options used here.

Get more elaborate and you can send attachments, different message encoding, different E-mail formats, multipart messagesm and more. Do some research on this and beware the number of hyphens needed in different parts of the message.

Content-Type: multipart/mixed;  boundary="----Some-unique-char-string-not-in-any-message"------Some-unique-char-string-not-in-any-message. . .


you can use mailx and always put your quotes around variables

mailx -s "$subj" my.email@my.domain.com < myfile.txt