#!/bin/bash
# script to send test mail with netcat.
# expects the following arguments:
# 1. recipient mail server
# 2. port (typically 25 or 465)
# 3. mail from (e.g. from@example.com)
# 4. mail to (e.g. to@example.com)
# 5. domain (e.g. example.com)

# for mail_input function
from="$3"
to="$4"
domain="$5"

[ -z "$domain" ] && domain=$(hostname -f)

# error handling
function err_exit { echo -e 1>&2; exit 1; }

# check if proper arguments are supplied
if [ $# -ne 4 ]; then
  echo -e "\n Usage error!"
  echo " This script requires at least four arguments:"
  echo " 1. recipient mail server"
  echo " 2. port (typically 25 or 465)"
  echo " 3. mail from (e.g. from@example.com)"
  echo " 4. mail to (e.g. to@example.com)"
  echo " 5. domain (e.g. example.com) - optional"
  exit 1
fi

# create message
function mail_input {
  echo "helo $domain"
  echo "MAIL FROM: <$from>"
  echo "RCPT TO: <$to>"
  echo "DATA"
  echo "From: <$from>"
  echo "To: <$to>"
  echo "Subject: Test email"
  echo "This is only a test. If you received this message, then your SMTP setup is working."
  echo "."
  echo "quit"
}

# send
mail_input | nc $1 $2 || err_exit
