Sending email with text & attachment using mailx

I spent some time working this out, with a little help from various forums, and thought the community would like to know :

Here is how you can send an email from a single Unix command line :

/usr/bin/echo "Email text\nNew line\nAnother new line" >x | uuencode sourcefile.txt sourcefile.txt | cat x - | mailx -s "Email subject" -r "reply@to.com" "recipient@company.com"

Breakdown :

  • /usr/bin/echo : I use /usr/bin/echo because it consistently handles embedded control characters like \n (newline)

  • >x : The echoed text is saved in file "x" for use by "cat"

  • uuencode : This takes the file and generates it as a MIME-encoded attachment. The output (encoded file) is piped to "cat"

  • cat : Concatenates the echoed text to the encoded file. Cat takes the contents of file "x", appends the output from uuencode and pipes them to "mailx"

  • mailx : Sends the email. -s is the subject text, -r is the reply-to email address, followed by the recipient's email address. The contents of the email come from the output of "cat"

This command does leave behind a file called "x". You may want to delete this file later. You could save it in /var/tmp, if the contents aren't sensitive.

This works for me on Solaris (SunOS 5.6). I believe it should be fairly portable to other environments.

If you want to include HTML in the text part of the email, you can include "Content-Type: text/html" in the echoed text, followed by your HTML code.

I try it ok in FreeBSD:-)
1.)/usr/bin/echo "Email text\nNew line\nAnother new line" >x

2.) uuencode sourcefile.txt sourcefile.txt | cat x - | mailx -s "Email subject" "recipient@company.com"

Thanks a lot;
Before you post,I can do only post content or post attechment with command line;can't bind them :frowning:
cat content.txt | mailx -s "Email subject" "recipient@company.com"
or
cat attechment.tar.gz | uuencode attechmetn.tar.gz | mailx -s "Email subject"
"recipient@company.com"

You could use a sub-shell, e.g....

( echo "Email text"
  echo "etc"
  uuencode /path/to/sourcefile.txt sourcefile.txt
) | mailx -s "Email subject" "recipient@company.com"

I tried this command but i m not getting the mail!!