From 1688532aee9fe431abf0b1f4cba225512f6ff1b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Poulain?= Date: Mon, 24 Aug 2020 21:06:21 +0200 Subject: [PATCH] =?UTF-8?q?charge=20les=20templates=20jinja2=20depuis=20le?= =?UTF-8?q?=20basename=20pass=C3=A9=20en=20argument?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + mailing.py | 33 +++++++++++++++++++++------------ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e4962a6..c288d0a 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ On a Debian-based host running at least Debian Stretch, you will need the following packages: - git (recommended for getting the source) - python3 +- python3-jinja2 ### Manual installation diff --git a/mailing.py b/mailing.py index e913c52..cc463af 100755 --- a/mailing.py +++ b/mailing.py @@ -26,6 +26,7 @@ import argparse, csv, sys, re import smtplib, time, mimetypes from email.header import Header from email.message import EmailMessage +from jinja2 import Environment, FileSystemLoader, select_autoescape def parse_args(): @@ -40,11 +41,12 @@ def parse_args(): ) ma.add_argument( "-b", - "--bodyfile", - metavar="BODY.FILE", + "--basename", type=str, required=True, - help="Template of the mail to be sent", + help="Templates basename to be used. The known extensions are: " + ".subject for subject, .txt for plain body " + "and optionally .html for html alternative.", ) parser.add_argument( "-d", @@ -82,12 +84,19 @@ def read_recipients_datas(args): return full_datas -def read_body(args): - bodyfile = open(args.bodyfile) - body = "" - for line in bodyfile.readlines(): - body = body + line - return body +def read_templates(args): + env = Environment( + loader=FileSystemLoader("."), autoescape=select_autoescape(["html"]) + ) + templates = [ + env.get_template("{}.subject".format(args.basename)), + env.get_template("{}.txt".format(args.basename)), + ] + try: + templates.append(env.get_template("{}.html".format(args.basename))) + except Exception: + pass + return templates def read_join(args): @@ -218,11 +227,11 @@ if __name__ == "__main__": # read the recipients file datas = read_recipients_datas(args) - print(datas) - exit(0) # read the template of the mail - bodytemplate = read_body(args) + templates = read_templates(args) + print(templates) + exit(0) # optionnaly read the attachment of the mail attachment = None