26

I am using the following command to create messages on the fly, and send them:

echo "Subject:Hello \n\n I would like to buy a hamburger\n" | sendmail [email protected]

It seems that when you send the information from a file, by doing something like:

sendmail [email protected] mail.txt 

Then sendmail sees each line as a header, and parses it. But the way I sent it above, everything ends up in the subject line.

If one wants to echo a message complete with headers, into sendmail, then what is the format ? How does one do it ?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Kaizer Sozay
  • 739
  • 3
  • 13
  • 19

2 Answers2

29

Your echo statement should really output newlines not the sequence \ followed by n. You can do that by providing the -e option:

echo -e "Subject:Hello \n\n I would like to buy a hamburger\n" | sendmail [email protected]

To understand what is the difference have a look at the output from the following two commands:

echo "Subject:Hello \n\n I would like to buy a hamburger\n"
echo -e "Subject:Hello \n\n I would like to buy a hamburger\n"
Anthon
  • 78,313
  • 42
  • 165
  • 222
1

"Here document" in shell scripts (You compose message headers and body)

#!/bin/sh
[email protected]
/usr/sbin/sendmail -i $TO <<MAIL_END
Subject: Hello
To: $TO

I would like to buy a hamburger
MAIL_END

Message body from external file

#!/bin/sh
[email protected]
BODY_FILE=mail.txt
(cat - $BODY_FILE)<<HEADERS_END | /usr/sbin/sendmail -i $TO
Subject: Hello
To: $TO

HEADERS_END
AnFi
  • 1,516
  • 7
  • 10