How to attach a file using mail command on Linux?
Question
I'm on a server running a Linux shell. I need to mail a simple file to a recipient. How to do this, prefereably using only the mail command?
UPDATE: got a good solution, using mutt instead:
$ echo | mutt -a syslogs.tar.gz [email protected]
Accepted Answer
Example using uuencode:
uuencode surfing.jpeg surfing.jpeg | mail [email protected]
and reference article:
http://www.shelldorado.com/articles/mailattachments.html
Note:
you may apt install sharutils
to have uuencode
command
Read more... Read less...
mail
on every version of modern Linux that I've tried can do it. No need for other software:
[email protected]:~$ mail -a doc.jpg [email protected]
Subject: testing
This is a test
EOT
ctrl+d when you're done typing.
mailx might help as well. From the mailx man page:
-a file
Attach the given file to the message.
Pretty easy, right?
My answer needs base64 in addition to mail, but some uuencode versions can also do base64 with -m, or you can forget about mime and use the plain uuencode output...
[email protected]
[email protected]
SUBJECT="Auto emailed"
MIME="application/x-gzip" # Adjust this to the proper mime-type of file
FILE=somefile.tar.gz
ENCODING=base64
boundary="---my-unlikely-text-for-mime-boundary---$$--"
(cat <<EOF
From: $FROM
To: $REPORT_DEST
Subject: $SUBJECT
Date: $(date +"%a, %b %e %Y %T %z")
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary="$boundary"
Content-Disposition: inline
--$boundary
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
This email has attached the file
--$boundary
Content-Type: $MIME;name="$FILE"
Content-Disposition: attachment;filename="$FILE"
Content-Transfer-Encoding: $ENCODING
EOF
base64 $FILE
echo ""
echo "--$boundary" ) | mail
mailx -a /path/to/file [email protected]
You might go into interactive mode (it will prompt you with "Subject: " and then a blank line), enter a subject, then enter a body and hit Ctrl+D (EOT) to finish.