Question

I need to attach a file with mailx but at the moment I am not having success.

Here's my code:

subject="Something happened"
to="somebody@somewhere.com"
body="Attachment Test"
attachment=/path/to/somefile.csv

uuencode $attachment | mailx -s "$subject" "$to" << EOF

The message is ready to be sent with the following file or link attachments:

somefile.csv

Note: To protect against computer viruses, e-mail programs may prevent
sending or receiving certain types of file attachments.  Check your
e-mail security settings to determine how attachments are handled.

EOF

Any feedback would be highly appreciated.


Update I have added the attachment var to avoid having to use the path every time.

Was it helpful?

Solution

You have to concat both the text of your message and the uuencoded attachment:

$ subject="Something happened"
$ to="somebody@somewhere.com"
$ body="Attachment Test"
$ attachment=/path/to/somefile.csv
$
$ cat >msg.txt <<EOF
> The message is ready to be sent with the following file or link attachments:
>
> somefile.csv
>
> Note: To protect against computer viruses, e-mail programs may prevent
> sending or receiving certain types of file attachments.  Check your
> e-mail security settings to determine how attachments are handled.
>
> EOF
$ ( cat msg.txt ; uuencode $attachment somefile.csv) | mailx -s "$subject" "$to"

There are different ways to provide the message text, this is just an example that is close to your original question. If the message should be reused it makes sense to just store it in a file and use this file.

OTHER TIPS

Well, here are the first few problems you've got.

  1. You appear to be assuming that a mail client is going to handle uuencoded attachment without any headers. That won't happen.

  2. You're misusing I/O redirection: uuencode's output and the here-document are both being fed to mailx, which can't happen.

  3. You're misusing uuencode: if one path is given, it's just a name to give the decoded file, not an input file name. Giving the file twice will assign the same name to the decoded file as that which was read. The -m flag forces base64 encode. But this still isn't going to provide attachment headers for mailx.

You're way better getting a copy of mpack, which will do what you want.

If you must do it, you could do something like this:

cat <<EOF | ( cat -; uuencode -m /path/to/somefile.csv /path/to/somefile.csv; ) | mailx -s "$subject" "$to" 
place your message from the here block in your example here
EOF

There are lots of other possibilities... but this one still has the here document as in your example and was easy off the top of my head, and there's no temp file involved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top