After dragging my feet for quite some time, I finally decided to set up an email service associated with my site. I needed a stable way of sending alert emails for the variety of scripts I've developed, and leveraging Google's SMTP servers gets hairy due to their policies on less secure apps. But, let's be honest, the biggest reason to do this is that sweet, sweet @aarondevelops.com email address.

Email Marketing
Photo by Campaign Creators / Unsplash

The Mail Server

First things first, we need to have a provider for the core email functionality - this means either setting up a server yourself, or going through a third-party provider. For me, I didn't want to go through the trouble of setting up an SMTP server, nor did I want to have all my eggs in one basket. So I decided to purchase the managed mail server option from No-IP, which is also where I park my domain.

Sending via Software

The CLI sendemail is readily available on most Unix systems, and mostly works out the box. It took me a surprising amount of digging around, as well as trial and error, before I could get it to play nicely with No-IP's SMTP server. Eventually, I was able to settle on this simple script:

#!/bin/bash

# Validate sendemail tool installed.
if ! type sendemail > /dev/null 2>&1; then
    echo 'This script requires sendemail, please install.' 1>&2
    exit 1
fi

# Validate sendemail credentials are retrieved.
if [ -z "$MAIL_ACCOUNT" -a "$MAIL_ACCOUNT" != " " ]; then
    echo 'Failed to retrieve mail account and password.' 1>&2
    echo 'Ensure shell environment contains MAIL_ACCOUNT variable.' 1>&2
    exit 1
fi

if [ -z "$MAIL_PASSWORD" -a "$MAIL_PASSWORD" != " " ]; then
    echo 'Failed to retrieve mail account and password.' 1>&2
    echo 'Ensure shell environment contains MAIL_PASSWORD variable.' 1>&2
    exit 1
fi

# Validate input arguments
if [ "$#" -lt 3 ]; then
    echo "Usage: email TO SUBJECT MESSAGE ATTACHMENT(Optional)" 1>&2
    exit 1
fi

# $1: Subject
# $2: Body
# $3: Attachment
sendemail \
    -f "aknobloch@aarondevelops.com" \
    -xu "${MAIL_ACCOUNT}" \
    -xp "${MAIL_PASSWORD}" \
    -s "mail.noip.com:587" \
    -o tls=yes \
    -t $1 \
    -u $2 \
    -m $3 \
    -a $4