From 73b87797c19d7ea869cc71b7f37e0bb18c47dfd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Poulain?= Date: Mon, 24 Aug 2020 18:34:32 +0200 Subject: [PATCH] refactor: passage argparse --- mailing.py | 75 +++++++++++++++++++++++++++--------------------------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/mailing.py b/mailing.py index f48c561..a016574 100755 --- a/mailing.py +++ b/mailing.py @@ -22,27 +22,44 @@ # This program is used to mail a message to several recipients, thus # providing customization for each recipient. -import sys, getopt, re +import argparse, sys, re import smtplib, time, mimetypes from email.header import Header from email.message import EmailMessage -# -# displays usage of the program, then quit -# -def usage(returncode): - print( - """SYNTAX: - """, - sys.argv[0], - """ -t tofile -b bodyfile [-p attachedfile] - - tofile : sort of CSV file containing addresses of recipients - bodyfile : template of the mail to be sent - attachedfile : optionnal attachment - """, - ) - sys.exit(returncode) + +parser = argparse.ArgumentParser( + description=""" +Simple mailing script. +""" +) + +ma = parser.add_argument_group(title="mandatory arguments", description=None) +ma.add_argument( + "-t", + "--tofile", + metavar="TO.FILE", + type=str, + required=True, + help="Sort of CSV file containing addresses of recipients.", +) +ma.add_argument( + "-b", + "--bodyfile", + metavar="BODY.FILE", + type=str, + required=True, + help="Template of the mail to be sent", +) + +parser.add_argument( + "-a", + "--attachement", + metavar="ATTACHED.FILE", + type=str, + nargs="?", + help="Optionnal attachment.", +) TOFILE = None @@ -180,26 +197,10 @@ def send_message(message, to, attachment): if __name__ == "__main__": - # handle options of the program - try: - opts, args = getopt.getopt(sys.argv[1:], "t:b:p:") - except getopt.error as msg: - print("getopt error: %s" % msg) - usage(1) - - for name, value in opts: - if name == "-t": - TOFILE = value - elif name == "-b": - BODYFILE = value - elif name == "-p": - JOINFILE = value - else: - print("argument: ", name, " invalid") - usage(1) - - if not TOFILE or not BODYFILE: - usage(1) + args = parser.parse_args() + TOFILE = args.tofile + BODYFILE = args.bodyfile + JOINFILE = args.attachement # read the recipients file sets = read_recipients()