Last Updated: February 25, 2016
·
2.162K
· dhoffm

How to generate a random email signature image.

Introduction

The following script can be called via Linux Cron to select and copy a random image from a predefined set of images. The copied image with a fixed name can be attached to an E-Mail signature. Additionally a Link can be used on the image.

Steps to get this working:

  • Save the script as signature.sh and change the url the image is linked to either via shell argument:
sh path-to-file/signature.sh  "http://your-website.de"

or place the url in a file called link_url.txt (should be used if your hoster disallows cron arguments)

  • Place some images in a subfolder called "signatures".
  • Call your script via Cron
  • Use it in your E-Mail signatures like this:
<a href="http://www.your-website.de/path-where-you-place-the-script/link.php">
<img border="0" src="http://www.your-website.de/path-where-you-place-the-script/signature.jpg" alt="" /></a>
  • If anything goes wrong check the comments in the script.

The script:

#! /bin/bash
# relative path to signatures
signaturepath="signatures"
# absolute path to this script
script=$(readlink -f $0)
scriptpath=$(dirname $script)
# absolute path to signatures
dir="${scriptpath}/${signaturepath}"
# list directory (one file per line), pass it to sort (random), pass it to head (first line)
file=$(/bin/ls -1 ${dir} | sort --random-sort | head -1)
# get the real absolute path to this file with readlink
path=$(readlink --canonicalize "$dir/$file")
# echo "The file is: $path"
# do nothing if file is not present, happens when the signatures folder is empty
if [ -n "$file" ]; then
# copy the random file to script root with new name
cp $path ${scriptpath}/signature.jpg
# default email link url
param="http://www.your-website.de"
# override default email link url with custom one from txt file
# a) override by file link_url.txt if exists
if [ -f ${scriptpath}/link_url.txt ]; then
param=$(cat ${scriptpath}/link_url.txt)
fi
# override default email link url with custom one from shell argument
# b) more important if both are present: override by argument if exists
if [ -n "$1" ]; then
param=$1
fi
# modify the link.php to point to the current link url
echo "<?php header(\"Location:${param}\"); exit; ?>" > ${scriptpath}/link.php
fi