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