mail: send email with attachment from commandline

The simple way: to use uuencode (part of sharutils package). Any formatting or body text are unavailable. Just a email with attachement and custom subject.

uuencode /path/to/file file_name.ext | mail -s subject [email protected]

The complex way: to use sendmail and html formatting:

v_mailpart="$(uuidgen)/$(hostname)"
echo "To: [email protected]
Subject: subject
Content-Type: multipart/mixed; boundary=\"$v_mailpart\"
MIME-Version: 1.0

This is a multi-part message in MIME format.
--$v_mailpart
Content-Type: text/html
Content-Disposition: inline

<html><body>Message text itself.</body></html>

--$v_mailpart
Content-Transfer-Encoding: base64
Content-Type: application/octet-stream; name=file_name.ext
Content-Disposition: attachment; filename=file_name.ext

`base64 /path/to/file`
 --$v_mailpart--" | /usr/sbin/sendmail -t

in case with several attachments last part may be repeated.


With mutt instead of mail you would simply call

echo "body" | mutt -s "subject" -a attachment0 attachment1 [...] -- [email protected]

Here, attachmentN are the list of files that you want to attach.

Tags:

Linux

Email

Bash