Skip to content

Instantly share code, notes, and snippets.

@keune
Created October 23, 2016 19:40
Show Gist options
  • Save keune/3e344681dc87d2b151f5f199c9d12db3 to your computer and use it in GitHub Desktop.
Save keune/3e344681dc87d2b151f5f199c9d12db3 to your computer and use it in GitHub Desktop.
Send yourself latest XKCD comic as email.
#! /bin/bash
# We'll keep the ID of last sent comic here
logFile='./xkcd-last-sent.log'
toEmail='your_email@example.com'
function getJsonVal() {
python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)['$1']))";
}
echo $(date)
# if logfile exists, its content is the id of last sent comic
lastSent=0
if [ -f $logFile ]; then
lastSent=`cat xkcd-last-sent.log`
fi
# get comic json data
jsonStr=$(wget -qO- https://xkcd.com/info.0.json)
if [ "$jsonStr" == "" ]
then
echo -e "Failed pulling JSON data.\n";
exit;
fi
currentNum=`echo $jsonStr | getJsonVal num`
# if id from json is bigger than our id, it means the comic is new to us, and we will send email
if [[ $currentNum -gt $lastSent ]]
then
echo "Sending $currentNum"
# prepare HTML content
title=`echo $jsonStr | getJsonVal title`
img=`echo $jsonStr | getJsonVal img`
alt=`echo $jsonStr | getJsonVal alt`
htmlContent="<h2>${title:1:-1}</h2><br><img src=$img><br><p>${alt:1:-1}</p>"
# prepare headers
mailContent="Subject: XKCD #${currentNum}\r\n"
mailContent=$mailContent"MIME-Version: 1.0\r\n"
mailContent=$mailContent'Content-type: text/html; charset=utf-8\r\n\r\n'
mailContent=$mailContent$htmlContent
# if you're using ssmtp uncomment the next line, and comment the line after that
#echo -e "$mailContent" | ssmtp $toEmail
echo -e "$mailContent" | sendmail -t $toEmail
# update our log file with the latest id
echo $currentNum > $logFile
else
echo "Already sent $currentNum"
fi
echo # just to put a blank line after all output.
#Useful when you use crontab to append the output into a file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment