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.
  1. install email dæmon

    apt install mailutils
    1. 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.

  2. create executable ~/checkIP.sh

    #!/bin/bash
    set -u
    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
  3. 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

    Notes

    Reference