Create email with attachment using bash

Abstract

In this post we'll see how to create emails with attachments using bash shell.

The script

Be sure you have uuencode installed, it’s required to encode files in MIME format.

#!/bin/bash

PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"

EMAIL_OK="dainese@example.com"
BODY_OK="From: Webmaster\nTo: undisclosed@example.com\nSubject: Requested files"

EMAIL_ERR="dainese@example.com"
BODY_ERR="From: Webmaster\nTo: undisclosed@example.com\nSubject: Cannot send files"

SOURCE="/path/file/report*.xls"
ZIP="/tmp/report-`date +%Y%m%d`.zip"

zip -q $ZIP $SOURCE

if [ $?=0 ]; then
	( echo -e "$BODY_OK"; uuencode $ZIP `basename $ZIP` ) | sendmail $EMAIL_OK
else
	( echo -e "$BODY_ERR" ) | sendmail $EMAIL_ERR
fi

rm -f $ZIP
Posted on 13 Apr 2010 by Andrea.
  • Gmail icon
  • Twitter icon
  • Facebook icon
  • LinkedIN icon
  • Google+ icon