refactor: passage argparse

This commit is contained in:
François Poulain 2020-08-24 18:34:32 +02:00
parent 1064e517be
commit 73b87797c1
1 changed files with 38 additions and 37 deletions

View File

@ -22,27 +22,44 @@
# This program is used to mail a message to several recipients, thus # This program is used to mail a message to several recipients, thus
# providing customization for each recipient. # providing customization for each recipient.
import sys, getopt, re import argparse, sys, re
import smtplib, time, mimetypes import smtplib, time, mimetypes
from email.header import Header from email.header import Header
from email.message import EmailMessage from email.message import EmailMessage
#
# displays usage of the program, then quit parser = argparse.ArgumentParser(
# description="""
def usage(returncode): Simple mailing script.
print( """
"""SYNTAX: )
""",
sys.argv[0], ma = parser.add_argument_group(title="mandatory arguments", description=None)
""" -t tofile -b bodyfile [-p attachedfile] ma.add_argument(
"-t",
tofile : sort of CSV file containing addresses of recipients "--tofile",
bodyfile : template of the mail to be sent metavar="TO.FILE",
attachedfile : optionnal attachment type=str,
""", required=True,
) help="Sort of CSV file containing addresses of recipients.",
sys.exit(returncode) )
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 TOFILE = None
@ -180,26 +197,10 @@ def send_message(message, to, attachment):
if __name__ == "__main__": if __name__ == "__main__":
# handle options of the program args = parser.parse_args()
try: TOFILE = args.tofile
opts, args = getopt.getopt(sys.argv[1:], "t:b:p:") BODYFILE = args.bodyfile
except getopt.error as msg: JOINFILE = args.attachement
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)
# read the recipients file # read the recipients file
sets = read_recipients() sets = read_recipients()