Sending e-mail with attachment via `sendmail`

Recently I came across the need to send notification e-mails about completion of automated job. The e-mail must contain job log in the attachment. This is a very limited system without ability to add any fancy packages and the only e-mail client available is sendmail.

Here I share my shell script which allows me to send notification e-mail with the attached log file.

Prerequisites

All you need are:

  • base64 tool for the attachment.
  • sendmail client with proper configuration of your SMTP server and credentials.

Script itself

Shortly, this script creates HTML formatted message body with the attachment of the plain text file in the base64 encoding.

 1#!/usr/bin/sh
 2
 3ATTACHMENT="log/job.log"
 4
 5SUBJECT="Job result notification mail"
 6
 7TO="non-sleeping-ops-engineer@elswhere.domain"
 8
 9MESSAGE_TXT="Job result notification
10
11Job is done!
12
13BR,
14Your cronjob"
15
16MESSAGE_HTML="<html>
17<head><title>Job result notification mail</title><head>
18<body>
19<h2>Job result notification</h2>
20<p>Job is done!</p>
21<p>BR,<br>
22Your cronjob</p>"
23
24(
25  echo "Subject:${SUBJECT}"
26  echo "MIME-Version: 1.0"
27  echo 'Content-Type: multipart/mixed;'
28# Boundary value - any random sequence of letters and numbers
29# I prefer to use $(date | sha1sum)
30  echo ' boundary="--EBACD08204A6BA2B0A0CDF0AACCD59B41EFB5D4F"'
31  echo 'This is a multi-part message in MIME format.'
32# When you use boundary, please do not forget to put -- in front of it
33  echo "----EBACD08204A6BA2B0A0CDF0AACCD59B41EFB5D4F"
34  echo 'Content-Type: multipart/alternative;'
35  echo ' boundary="--5F1ED6B128B0B811C64160B25A85EC5155C9DB51"'
36  echo
37  echo '----5F1ED6B128B0B811C64160B25A85EC5155C9DB51'
38  echo "Content-Type: text/plain; charset=UTF-8; format=flowed"
39  echo "Content-Transfer-Encoding: 7bit"
40  echo
41  echo "${MESSAGE_TXT}"
42  echo
43  echo '----5F1ED6B128B0B811C64160B25A85EC5155C9DB51'
44  echo "Content-Type: text/html; charset=UTF-8"
45  echo "Content-Transfer-Encoding: 7bit"
46  echo
47  echo "${MESSAGE_HTML}"
48  echo
49# When you close boundary, you must add -- in the end as well
50  echo '----5F1ED6B128B0B811C64160B25A85EC5155C9DB51--'
51  echo
52  echo "----EBACD08204A6BA2B0A0CDF0AACCD59B41EFB5D4F"
53  echo "Content-Type: text/plain; charset=UTF-8; name=\"$(basename ${ATTACHMENT})\""
54  echo "Content-Transfer-Encoding: base64"
55  echo "Content-Disposition: attachment; filename=\"$(basename ${ATTACHMENT})\""
56  echo
57  base64 "${ATTACHMENT}"
58  echo "----EBACD08204A6BA2B0A0CDF0AACCD59B41EFB5D4F--"
59  ) | sendmail "${TO}"

You shall modify your sendmail command if you are using, e.g. SMTP relay.

Result

Using this shell script you can send quite nicely formatted notifications via e-mail with necessary attachments. I hope this small script will be useful to someone.