Index: foomailer/foomail.py
===================================================================
--- foomailer/foomail.py	(revision 404)
+++ foomailer/foomail.py	(revision 405)
@@ -1,10 +1,19 @@
 #!/usr/bin/env python
-# Rick van der Zwet
-# TODO: May need to implement some RFC checkers
+#
+# Rick van der Zwet <rick@vanderzwet.net>
 #
 #
-import sys,smtplib,re,socket,random,string,os,getopt
+import argparse
 import mimetypes
+import os
+import random
+import re
+import smtplib
+import socket
+import string
+import sys
+import textwrap
 import time
+
 from time import gmtime,strftime
 from email.mime.multipart import MIMEMultipart
@@ -14,145 +23,81 @@
 from email import encoders
 
-__svnversion__ = "$Id: foomail.py 633 2008-06-12 19:29:56Z rick $"
+__svnversion__ = "$Id$"
 __author__ = "Rick van der Zwet"
 
 
-def usage():
-    print("usage %s -f <from> -r <recipient> -s <server> [--spam]" % sys.argv[0])
-    print("[--virus] [--file <size in kB>] [--message <file>]")
-    print("[--subject <string>] [--to <string>] [--cc <string>]")
-    print("[--force]")
+default_subject = strftime('Test email send at  %a, %d %b %Y %T %z', gmtime())
 
-default_domain = 'example.com'
-def emailparse(email):
-    if re.compile('.*@.*').match(email):
-        return(email)
-    else:
-        return(email + '@' + default_domain)
+parser = argparse.ArgumentParser(
+            description=textwrap.dedent('''
+            Sent test emails for mailserver verification and debugging 
 
-try:
-    opts, args = getopt.getopt(sys.argv[1:], "f:r:s:dp:t",
-                 ["from=","force","recipient=","server=","spam","port=","virus","files=","dry-run","message=","subject=","to=","trace","cc="])
-except getopt.GetoptError:
-    usage()
-    sys.exit(128)
-
-spam = False
-virus = False
-server = False
-port = "25"
-trace = False
-recipient = False
-sender = False
-files = False
-force = False
-dry = False
-message = False
-subject = False
-to = False
-cc = False
-
-tests = ""
-
-for o, a in opts:
-    if o in ("-f","--from"):
-        sender_raw = a
-        sender = emailparse(a)
-    elif o in ( "-r", "--recipient"):
-        recipient_raw = a
-        recipient = emailparse(a)
-    elif o in ("-s", "--server"):
-        server = a
-    elif o in ("-p", "--port"):
-        port = a
-    elif o == "--trace":
-        trace = True
-    elif o == "--spam":
-        spam = True
-        tests += " Spam"
-    elif o == "--virus":
-        virus = True
-        tests += " Virus"
-    elif o == "--files":
-        files = a
-    elif o in ("-d","--dry-run"):
-        dry = True
-    elif o in ("--message"):
-        message = a
-    elif o in ("--subject"):
-        subject = a
-    elif o in ("--to"):
-        to = a
-    elif o in ("--cc"):
-        cc = a
-    elif o in ("--force"):
-        force = True;
-
-error = False
-if not sender:
-    print("No sender defined")
-    error = True
-elif not recipient:
-    print("No recipient defined")
-    error = True
-elif not server:
-    print("No server defined")
-    error = True
-
-if error:
-    usage()
-    sys.exit(128)
-
-if force:
-    sender = sender_raw
-    recipient = recipient_raw
+            Author : %s
+            Version: %s 
+            ''' % (__author__, __svnversion__)),
+            formatter_class=argparse.RawDescriptionHelpFormatter)
+parser.add_argument('--from', '-f', dest='sender', required=True)
+parser.add_argument('--recipient', '-r', required=True)
+parser.add_argument('--server', '-s', required=True)
+parser.add_argument('--cc', help='Carbon Copy header')
+parser.add_argument('--file', action='append', help='Attachments to sent')
+parser.add_argument('--hostname', default=socket.gethostname(), help='EHLO/HELO hostname to present')
+parser.add_argument('--message', help='Alternative message text of body')
+parser.add_argument('--subject', default=default_subject, help='Alternative Subject header')
+parser.add_argument('--spam', action='store_true', help='Include X-Spam testing headers')
+parser.add_argument('--port', type=int, default=25, help='SMTP port used for connection')
+parser.add_argument('--reply-to', help='Set Reply-To: header')
+parser.add_argument('--to', help='Alternative To: header')
+parser.add_argument('--silent', action='store_true', help='Do not-follow SMTP flow verbosely')
+parser.add_argument('--virus', action='store_true', help='Include eicar.txt sample virus')
+parser.add_argument('--dry-run', '-d', action='store_true', help='Do not actually sent out the message')
+args = parser.parse_args()
 
 
-#Subject here, just to keep the settings/layout a bit more constent
-if not subject:
-    subject = 'Test email send at  %a, %d %b %Y %T %z'
-subject = strftime(subject,gmtime())
-
-if not to:
-    to = 'Testing received <' + recipient + '>'
-    to = recipient
-
 email = MIMEMultipart()
-hostname = socket.gethostname()
-
-email['From'] = 'Testing sender <' + sender + '>'
-email['To'] = to
-if cc:
-    email['Cc'] = cc
-email['X-Server'] = server
-email['X-Port'] = port
-email['X-Hostname'] = hostname
+email['From'] = 'Testing sender <' + args.sender + '>'
+email['To'] = args.to or args.recipient
+if args.cc:
+    email['Cc'] = args.cc
+email['X-Server'] = args.server
+email['X-Port'] = str(args.port)
+email['X-Hostname'] = args.hostname
 email['Message-ID' ] = '<' +''.join(random.sample(string.ascii_letters +
                        string.digits,10)) + '@' + email['X-Hostname'] + '>'
 email['Date'] = strftime('%a, %d %b %Y %T %z',gmtime())
-email['Subject'] = subject
+email['Subject'] = args.subject
 email['X-Version'] = __svnversion__
 email['X-Author'] = __author__
-email['X-Tests'] = tests
-#email['Reply-To'] = "Rick vd Zwet <rick@joost.com>, Wouter Simons <wouter@joost.com>"
-if spam:
+
+tests = []
+if args.spam:
+    tests.append('spam')
+if args.virus:
+    test.append('virus')
+email['X-Tests'] = ' '.join(tests)
+
+if args.reply_to:
+    email['Reply-To'] = args.reply_to
+
+if args.spam:
     email['X-Spam'] = 'XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X'
 
-
-def defaultmessage():
-    msg = ''
-    msg += \
-    '''
-Hi,
-
-    Sorry to bother you...
-
-Please ignore this message as it is used to test
-and verify systems to make sure everything works
-flawless.
-
-%(virus)s
-
-Technical details:\n''' % email
+if args.message:
+    f = open(args.message,'r')
+    msg = f.read()
+    f.close()
+else:
+    msg = textwrap.dedent('''
+        Hi,
+        
+            Sorry to bother you...
+        
+        Please ignore this message as it is used to test
+        and verify systems to make sure everything works
+        flawless.
+        
+        %(virus)s
+        
+        Technical details:\n''' % email)
     
     for k in list(email.keys()):
@@ -160,25 +105,16 @@
         msg += "* %-15s : %s\n" % (k,v)
     
-    
-    msg = msg + \
-    '''
-Best regards,
-Your system administrator
--- 
-BSD Licensed Source Code for this tool at: 
-https://rickvanderzwet.nl/svn/personal/foomailer
-    '''
-    return(msg)
+    msg += textwrap.dedent('''
+        Best regards,
+        Your system administrator
+        -- 
+        BSD Licensed Source Code for this tool at: 
+        https://rickvanderzwet.nl/svn/personal/foomailer
+        ''')
 
-if message:
-    f = open(message,'r')
-    msg = f.read()
-    f.close()
-else:
-    msg = defaultmessage()
 
 email.attach(MIMEText(msg))
 
-if virus:
+if args.virus:
     part = MIMEBase('application', "octet-stream")
     part.set_payload('X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*')
@@ -187,24 +123,24 @@
     email.attach(part)
 
-if files:
-    for file in files.split(':'):
-        mimetype = mimetypes.guess_type(file)[0].split('/')
+if args.file:
+    for filename in args.file:
+        mimetype = mimetypes.guess_type(filename)[0].split('/')
         part = MIMEBase(mimetype[0],mimetype[1])
-        f = open(file,'r')
+        f = open(filename,'r')
         part.set_payload(f.read())
         f.close()
         encoders.encode_base64(part)
-        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
+        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename))
         email.attach(part)
 
 print(email.as_string())
 
-if not dry:
+if not args.dry_run:
     mark = time.time()
-    server = smtplib.SMTP(server, port, timeout=600)
-    server.set_debuglevel(trace)
-    server.helo(hostname)
-    server.ehlo(hostname)
-    server.sendmail(sender, recipient, email.as_string())
+    server = smtplib.SMTP(args.server, args.port, timeout=600)
+    server.set_debuglevel(not args.silent)
+    server.helo(args.hostname)
+    server.ehlo(args.hostname)
+    server.sendmail(args.sender, args.recipient, email.as_string())
     server.quit()
     print("Sending took sec: %.2f" % (time.time() - mark))
