Cheap and Cheerful Email Alerting from Your VPS

Written by James McDonald

February 16, 2022

Quick and dirty email sending from a virtual server. (On Azure port 25 outbound is blocked so this works nicely sending to port 587)

You will have to tweak your gmail account to use less secure auth and allow app passwords.

Install the SSMTP package

apt-get install ssmtp

Add the configuration /etc/ssmtp/ssmtp.conf

[email protected]
hostname=site1.toggen.com.au
AuthMethod=LOGIN
UseTLS=YES
mailhub=smtp.gmail.com:587
FromLineOverride=YES
[email protected]
AuthPass=YourSuperSecretGoogleAppPassword
UseSTARTTLS=YES
FromLineOverride=YES
Debug=NO

Then create a script to send an email when something happens. The below script is looking in an nginx access log and will alert when an entry for the bing bot is seen.

What I like about this script is the <<- what it does is let you use a indented here doc so you don’t have to step back to the left hand side of the script which is ugly. The indented text must be a Tab \t character. In effect the addtion of the - character to the << redirection says strip all leading white space from the here doc. Nice

#!/bin/bash
DIR_PATH=$(dirname $(realpath $0))

SEEN=$DIR_PATH/seen

COUNT=`cat /var/log/nginx/brng_access.log | grep -c -i bingbot`

# uncomment for testing
# COUNT=2

if [ -f $SEEN ]
then
        # don't keep sending emails when we first see it
        echo File seen
        exit
fi

if [[ $COUNT =~ ^[1-9]+$ ]];
then
        echo Sending mail
       # make sure you specify the full path because
       # user cron path is /usr/bin:/bin and won't pickup the
       # sendmail binary in /usr/sbin
        /usr/sbin/sendmail -t <<- EMAIL
        To: James McDonald <[email protected]>
        From: Website or Process Name Here <[email protected]>
        Subject: We have seen a Bing Crawler for Brays Roofing
        DATE: `date`

        Entries: ${COUNT}
        EMAIL

        touch $SEEN
else
        echo BingBot not seen
fi

0 Comments

Submit a Comment

Your email address will not be published.

You May Also Like…

List your VSCode Extensions

Ever wondered what extensions you have installed and want to keep a list? This actually is a good way to audit your...

array_merge vs the + operator

<?php $options = [ 'rootNode' => 'response' ]; // array_merge // the same key appearing later will overwrite echo...