Skip to content

Instantly share code, notes, and snippets.

@soarez
Created July 10, 2015 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soarez/b2a092c309ed846be4f6 to your computer and use it in GitHub Desktop.
Save soarez/b2a092c309ed846be4f6 to your computer and use it in GitHub Desktop.
Upstart service error email alert
#!/bin/bash
srv=$1
to=$2
machine=$3
loglinesinbody=50
logfile="/var/log/upstart/$srv.log"
from="Upstart"
subject="$srv crashed in $machine"
boundary="ZZ_/afg6432dfgkl.94531q"
body="$(tail -n $loglinesinbody $logfile)"
declare -a attachments
attachments=( "$logfile" )
get_mimetype(){
# warning: assumes that the passed file exists
file --mime-type "$1" | sed 's/.*: //'
}
# Build headers
{
printf '%s\n' "From: $from
To: $to
Subject: $subject
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary=\"$boundary\"
--${boundary}
Content-Type: text/plain; charset=\"US-ASCII\"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
$body
"
# now loop over the attachments, guess the type
# and produce the corresponding part, encoded base64
for file in "${attachments[@]}"; do
[ ! -f "$file" ] && echo "Warning: attachment $file not found, skipping" >&2 && continue
mimetype=$(get_mimetype "$file")
printf '%s\n' "--${boundary}
Content-Type: $mimetype
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=\"$file\"
"
base64 "$file"
echo
done
# print last boundary with closing --
printf '%s\n' "--${boundary}--"
} | sendmail -t -oi

Usage

Instead of executing run-my-service use run-my-service || mail.sh SERVICE_NAME 'user1@mail.com,user2@mail.com' MACHINE_NAME.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment