#!/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 ./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"
    sleep 0s
    grep -v "^From " $3
    echo -e ".\r"
    echo "quit"
  ) | nc $1 $2
  exit 0
fi

if [ "$3" ]; then
  PORT=$3
else
  PORT=25
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 +5 | head -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`
  fi
  SMTPHOST=`echo $SMTPHOST | sed 's/.$//'`
fi

(
  echo "ehlo `hostname`"
  echo "mail from: <$MAILFROM>"
  echo "rcpt to: <$1>"
  echo "data"
  sleep 1s
  grep -v "^From " $2
  echo -e ".\r"
  sleep 1s
  echo "quit"
) | nc $SMTPHOST $PORT
