From a212c2bdd80973937eacc7bb5579818ed9d46b2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Poulain?= Date: Mon, 24 Aug 2020 21:05:22 +0200 Subject: [PATCH] =?UTF-8?q?lit=20les=20datas=20depuis=20un=20csv=20et=20pe?= =?UTF-8?q?rmet=20des=20champs=20par=20d=C3=A9faut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mailing.py | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/mailing.py b/mailing.py index fec2735..e913c52 100755 --- a/mailing.py +++ b/mailing.py @@ -22,7 +22,7 @@ # This program is used to mail a message to several recipients, thus # providing customization for each recipient. -import argparse, sys, re +import argparse, csv, sys, re import smtplib, time, mimetypes from email.header import Header from email.message import EmailMessage @@ -34,10 +34,9 @@ def parse_args(): ma.add_argument( "-t", "--tofile", - metavar="TO.FILE", type=str, required=True, - help="Sort of CSV file containing addresses of recipients.", + help="CSV file containing recipients data.", ) ma.add_argument( "-b", @@ -62,11 +61,25 @@ def parse_args(): return parser.parse_args() -# read the recipients file where values are separated by | characters -def read_recipients(args): - recipientfile = open(args.tofile) - lines = recipientfile.readlines() - return [line[:-1].split("|") for line in lines] +def read_recipients_datas(args): + with open(args.tofile) as csv_file: + csv_soup = csv.reader(csv_file) + first = [(s.split(":", 1)) for s in csv_soup.__next__()] + header = [ + (h[0].strip().lower(), h[1].strip() if len(h) == 2 else None) for h in first + ] + datas = [[s.strip() for s in d] for d in csv_soup] + full_datas = [] + for data in datas: + try: + full_data = { + h[0]: data[i] if i < len(data) or not h[1] else h[1] + for i, h in enumerate(header) + } + full_datas.append(full_data) + except Exception: + print("Ligne mal renseignée:", data, file=sys.stderr) + return full_datas def read_body(args): @@ -204,7 +217,9 @@ if __name__ == "__main__": args = parse_args() # read the recipients file - sets = read_recipients(args) + datas = read_recipients_datas(args) + print(datas) + exit(0) # read the template of the mail bodytemplate = read_body(args)