Automated Email Script in Bash

Rewrote my “Free Ice Cream” script in bash because I needed to be able to flexibly send emails without going through 20 UAC prompts due to restrictions and how many people are scared of PowerShell.

Below is my new implementation, instead of relying on Outlook (like before), this version is platform independent and will work on any OS with any Mail Client like Thunderbird or Gmail.

rawurlencode() {
  local string="${1}"
  local strlen=${#string}
  local encoded=""
  local pos c o
 
  for (( pos=0 ; pos<strlen ; pos++ )); do
     c=${string:$pos:1}
     case "$c" in
        [-_.~a-zA-Z0-9] ) o="${c}" ;;
        * )               printf -v o '%%%02x' "'$c"
     esac
     encoded+="${o}"
  done
  echo "${encoded}"
}

function generateParticipants() {
	PARTICIPANT_LIST=("$@")
	
	PARTICIPANT_STRING_TO_RETURN=""

	SEPARATOR=";"

	for PARTICIPANT in "${PARTICIPANT_LIST[@]}";
	do
		PARTICIPANT_STRING_TO_RETURN+="$PARTICIPANT"
		PARTICIPANT_STRING_TO_RETURN+="$SEPARATOR"
	done

	echo "$PARTICIPANT_STRING_TO_RETURN"
}
 
function createEmail() {
	SUBJECT="$1" # Save first argument in a variable
	shift
	BODY="$1" # Save second argument in a variable
	shift # Shift all arguments to the left (original $1 gets lost)
	TO_ARRAY=("$@")

	TO=$(generateParticipants "${TO_ARRAY[@]}")

	SUBJECT_ENCODED=$(rawurlencode "$SUBJECT")
	BODY_ENCODED=$(rawurlencode "$BODY")

	MESSAGE_OBJECT="mailto:$TO&amp;subject=$SUBJECT_ENCODED&amp;body=$BODY_ENCODED"
	
	echo "########################"
	echo "#### EMAIL PREVIEW: ####"
	echo "########################"
	echo ""
	echo "To: $TO"
	echo "Subject: $SUBJECT"
	echo "Body: $BODY"
	echo ""
	echo "Sending to Email Client..."
	echo ""
	echo start "" "$MESSAGE_OBJECT"
	start "" "$MESSAGE_OBJECT"
}
 
EMAIL_SUBJECT="Free Ice Cream!"
EMAIL_BODY="I'm Buying."

PARTICIPANT_LIST+=("person1@company.com")
PARTICIPANT_LIST+=("person2@company.com")
PARTICIPANT_LIST+=("person3@company.com")

createEmail "$EMAIL_SUBJECT" "$EMAIL_BODY" "${PARTICIPANT_LIST[@]}"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s