Cannot attach file and include a body while sending an email in Linux

2.3k Views Asked by At

The command below will send an email with a Subject and Body, but no Attachment. If I remove < /usr/tmp/BODY_OF_EMAIL I receive the email with Subject and Attachment, but no Body.

cat /usr/tmp/ATTACHMENT.xls | uuencode ATTACHMENT.xls | mailx -s "Subject of email!" [email protected] < /usr/tmp/BODY_OF_EMAIL

/usr/tmp/BODY_OF_EMAIL contains the text "Email Body."

2

There are 2 best solutions below

0
On BEST ANSWER

Using mailx:

(cat /usr/tmp/BODY_OF_EMAIL;
 echo; 
 uuencode ATTACHMENT.xls < /usr/tmp/ATTACHMENT.xls ) | 
 mailx -s "Subject of email!" [email protected]

Using nail:

nail -s "Subject of email!" -a /usr/tmp/ATTACHMENT.xls [email protected] < /usr/tmp/BODY_OF_EMAIL

The nail mailer is sometimes installed as mail, but it understands MIME, for real attachments.

2
On

Firstly, there's no need to use cat to feed uuencode, which can read from a file quite happily:

uuencode /usr/tmp/ATTACHMENT.xls ATTACHMENT.xls | ...

The main problem you have is with this part:

... | mailx < body_text_file

There's only one standard input stream, so when you give the shell contradictory instructions like this, it has to choose which redirection takes effect (what actually happens is that stdin is initially set to come from the process pipeline, and then when the < is read, that's disconnected and replaced by a file stream).

What you probably want to do is to use cat to concatenate the body text with the uuencoded file, like this:

... | cat body_text_file - | mailx

(I'm assuming the body text is an introduction and so comes first - swap the arguments to cat if I'm wrong).

Your full command would then be

uuencode /usr/tmp/ATTACHMENT.xls ATTACHMENT.xls \
  | cat /usr/tmp/BODY_OF_EMAIL - \
  | mailx -s "Subject of email!" [email protected]