#!/bin/sh
                                                                                
# smtptest, ver. 2.5
# (c) 2003 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

# usage:
#   ./smtptest to virus [port]
# or:
#   ./smtptest localhost 25 virus
#
# example:
#   ./smtptest root@youdomain.sk virus
#   ./smtptest localhost 25 virus
#
# If you want to define mail from: ..., use:
# MAILFROM=user@host ./smtptest ...
# If you want to connect to an smtpd directly:
# SMTPHOST=ip-or-hostname PORT=25 ./smtptest ...

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

if [ -z "$MAILFROM" ]; then
  MAILFROM="$USER@`hostname`"
fi

# code without email as 1st parameter
if echo $1 | grep -q -v "@"; then
  (
    echo "EHLO `hostname`"
    echo "MAIL FROM:<$MAILFROM>"
    echo "RCPT TO:<root@$1>"
    echo "DATA"
    grep -v "^From " $3
    echo -e ".\r"
    echo "QUIT"
    sleep 0.1 || sleep 1s
  ) | nc $1 $2
  exit 0
fi

if [ "$3" ]; then
  PORT=$3
else
  if [ -z "$PORT" ]; then
    PORT=25
  fi
fi

if [ -z "$SMTPHOST" ]; then
  SMTPHOST1=`echo $1 | cut -d@ -f2`
  H=`host -t mx $SMTPHOST1`
  if echo "$H" | grep -q "is an alias for" >/dev/null; then
    SMTPHOST=`echo "$H" | grep "mail is handled" | cut -d" " -f7`
  elif echo "$H" | grep -q "is handled by" >/dev/null; then
    SMTPHOST=`host -t mx $SMTPHOST1 | sort -n -k 6 | head -n 1 | cut -d" " -f7`
  elif echo "$H" | grep -q "not found:" >/dev/null; then
    echo "Host $SMTPHOST1 not found. Can't send. :-("
    exit 1
  else
    SMTPHOST=`host $SMTPHOST1 | cut -d" " -f4 | head -1`
  fi
  SMTPHOST=`echo $SMTPHOST | sed 's/\.$//'`
fi

(
  echo "EHLO `hostname`"
  echo "MAIL FROM:<$MAILFROM>"
  echo "RCPT TO:<$1>"
  echo "DATA"
  sleep 0.3 || sleep 1s
  grep -v "^From " $2
  echo -e ".\r"
  echo "QUIT"
  sleep 0.1 || sleep 1s
) | nc $SMTPHOST $PORT
