Get email upon changed IP address

Setup a cron script to check for changed IP address at reboot and each hour. Uses mailutils to setup an email server on your PC.

Note: intended for devices with IPv6/IPv4 public internet addresses.

Install email dæmon

apt install mailutils

Test email dæmon. Port 25 is blocked by many home ISPs.

echo "testing" | mail -s "test" my@email.address

Check /var/log/mail.log for Connection timed out errors that may indicate port 25 is blocked by your ISP. You might config for port 587 in that case.

Create executable ~/checkIP.sh

#!/usr/bin/env bash

set -o nounset
emailaddr=$1

CurIP=$(hostname -I | tr -d [:space:])

OldIP=$(tr ' ' '\n' < ~/.current_ip) #space to \n for consistency

if [[ ${CurIP} != ${OldIP} ]]; then
    echo -e "IP change detected\n $CurIP \n $OldIP"
    echo "New IP address: ${CurIP} (old address: ${OldIP} )" | mail -s "IP address change: $(hostname)" "$emailaddr"
    echo -e "${CurIP}" > ~/.current_ip
fi

be sure it’s executable

chmod +x ~/checkIP.sh

Edit your cron schedule

crontab -e

add at the top:

SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin

add at the bottom:

@reboot ~/checkIP.sh my@email.address
@hourly ~/checkIP.sh my@email.address