12

I am writing a shell script to send an email using Linux Mailx, the email must contain a file attachment and a message body.

Currently sending an email with an attachment:

output.txt | mail -s "Daily Monitoring" james@dell.com

I wish to add a message body. How should i?

Linux Mailx:

mail [-eIinv] [-a header] [-b addr] [-c addr] [-s subj] to-addr
Oh Chin Boon
  • 22,288
  • 48
  • 139
  • 212
  • 1
    This should have all the answers to your questions: http://stackoverflow.com/questions/17359/how-do-i-send-a-file-as-an-email-attachment-using-linux-command-line/14213935#14213935 – Eric Leschinski Jan 16 '13 at 04:14

6 Answers6

26

The usual way is to use uuencode for the attachments and echo for the body:

(uuencode output.txt output.txt; echo "Body of text") | mailx -s 'Subject' user@domain.com

For Solaris and AIX, you may need to put the echo statement first:

(echo "Body of text"; uuencode output.txt output.txt) | mailx -s 'Subject' user@domain.com
JonathanDavidArndt
  • 2,245
  • 13
  • 33
  • 46
johnsyweb
  • 129,524
  • 23
  • 177
  • 239
4

The best way is to use mpack!

mpack -s "Subject" -d "./body.txt" "././image.png" mailadress

mpack - subject - body - attachment - mailadress

Vautschi
  • 49
  • 1
1

Johnsyweb's answer didn't work for me, but it works for me with Mutt:

echo "Message body" | mutt -s "Message subject" -a myfile.txt recipient@domain.com
Slothario
  • 2,550
  • 3
  • 27
  • 45
1

Try this it works for me:

(echo "Hello XYX" ; uuencode /export/home/TOTAL_SI_COUNT_10042016.csv TOTAL_SI_COUNT_10042016.csv ) | mailx -s 'Script test' abc@xde.com
krampstudio
  • 3,231
  • 2
  • 40
  • 56
Vishy
  • 11
  • 1
1

On RHEL Linux, I had trouble getting my message in the body of the email instead of as an attachment . Using od -cx, I found that the body of my email contained several /r. I used a perl script to strip the /r, and the message was correctly inserted into the body of the email.

mailx -s "subject text" me@yahoo.com < 'body.txt'

The text file body.txt contained the char \r, so I used perl to strip \r.

cat body.txt | perl success.pl > body2.txt
mailx -s "subject text" me@yahoo.com < 'body2.txt'

This is success.pl

    while (<STDIN>) {
        my $currLine = $_;
        s?\r??g;
        print
    }
;
Loretta
  • 11
  • 1
0

You can try this:

(cat ./body.txt)|mailx -s "subject text" -a "attchement file" receiver@domain.com
Matthew Verstraete
  • 5,958
  • 21
  • 63
  • 113
Ray S
  • 9
  • 2