#!/usr/bin/env python

import smtplib
import sys
import getopt

my_name = "mail.foobar.example"
smtp_server = None
from_address = "sender@example.net"
to_address = "receiver@example.org"

def usage(msg=None):
    print >>sys.stderr, "Usage: %s [-s sender] [-r receiver] smtp_server_name" % \
        sys.argv[0]
    if msg is not None:
        print >>sys.stderr, msg

try:
    optlist, args = getopt.getopt (sys.argv[1:], "s:r:h:",
                               ["sender=", "receiver=", "my_hostname="])
    for option, value in optlist:
        if option == "--sender" or option == "-s":
            from_address = value
        elif option == "--receiver" or option == "-r":
            to_address = value
        elif option == "--my_hostname" or option == "-h":
            my_name = value
        else:
            # Should never occur, it is trapped by getopt
            print >>sys.stderr, "Unknown option %s" % option
            usage()
            sys.exit(1)
except getopt.error, reason:
    usage(reason)
    sys.exit(1)

if len(args) != 1:
    usage()
    sys.exit(1)
smtp_server = args[0]
s = smtplib.SMTP(smtp_server)

(reply_code, text) = s.ehlo(my_name)
reply_code = str(reply_code) 
if reply_code[0] != '2':
    raise Exception("Wrong reply to EHLO from %s: %s %s" % \
                        (smtp_server, reply_code, text))

(reply_code, text) = s.mail(from_address)
if reply_code == 554:
    print >>sys.stderr, \
        "Email sender address %s rejected (%s) so the test is not possible" % \
        (from_address, text)
    sys.exit(1)
elif reply_code != 250:
    raise Exception("Wrong reply to MAIL FROM from %s: %s %s" % \
                        (smtp_server, reply_code, text))

(reply_code, text) = s.rcpt(to_address)
if reply_code == 554 or reply_code == 550:
    print "Relaying from %s to %s was RIGHTLY rejected by %s" % \
        (from_address, to_address, smtp_server)
elif reply_code != 250:
    raise Exception("Wrong reply to RCPT TO from %s: %s %s" % \
                        (smtp_server, reply_code, text))
else:
    print >>sys.stderr, \
        "WARNING: SMTP server %s accepted to relay from %s to %s\nEither you are an authorized client or it is an open relay, which is bad" % \
        (smtp_server, from_address, to_address)

s.quit()



