One day, you may find yourself sitting at a terminal trying to send an email with a MIME attachment. Easy, you think to yourself. Only you can’t install anything onto the server without triggering a long-winded QA process, and it’s then you discover that the machine only has /bin/mail and sendmail available. Oh, and no base64 tools like mpack.
You may ask yourself, how do I work this?
#!/bin/bash
SUBJECT="Hello!"
FROM="test@foo.com"
TO="blah@foo.com"
FILENAME="/path/to/file"
BODY="This is the text body!"
ATTACHMENT=`perl -MMIME::Base64 -0777 -ne 'print encode_base64($_)' < $FILENAME`
/usr/lib/sendmail -t <<ENDMESSAGE
From: $FROM
To: $TO
Subject: $SUBJECT
Mime-Version: 1.0
Content-Type: Multipart/Mixed; boundary="ATTACHMENT"
If you can read this, you can't read MIME-encoded emails.
--ATTACHMENT
$BODY
--ATTACHMENT
Content-Disposition: attachment;
filename="$FILENAME"
Content-type: $MIME;
charset=US-ASCII;
name="$FILENAME"
Content-Transfer-Encoding: base64
$ATTACHMENT
--ATTACHMENT--
ENDMESSAGE
Never let it be said that Snappish Thoughts isn’t a full-service blog. Okay, yes, it does depend on perl being installed with MIME::Base64, but this server had them, so there. If you want to write a base64() function in bash, consider that an exercise (you can, of course just use quoted-printable instead, but that can get you in trouble, whereas base64ing is much safer. And yes, you want to be careful you don’t run this on a 10GB file as it’ll do fun and interesting things as bash/perl run out of memory, but for attachment-sized files, you should be fine)!