This commit is contained in:
2020-11-12 14:21:19 +01:00
parent 0aa7c05313
commit 3e42ca0bcd
7 changed files with 130 additions and 27 deletions

View File

@@ -22,7 +22,22 @@ WEEKDAYS = { 0: "Montag",
6: "Sonntag" }
def decode_header(header):
return "".join([ x[0].decode(x[1] or "ascii") if isinstance(x[0], bytes) else x[0] for x in email.header.decode_header(header) ])
decoded_header = email.header.decode_header(header)[0]
encoding = decoded_header[1] or "ascii"
if encoding == "unknown-8bit":
encoding = "ascii"
return decoded_header[0].decode(encoding, errors="replace") if isinstance(decoded_header[0], bytes) else decoded_header[0]
def get_body_text(msg):
# from https://stackoverflow.com/a/1463144
for part in msg.walk():
# each part is a either non-multipart, or another multipart message
# that contains further parts... Message is organized like a tree
if part.get_content_type() == 'text/plain':
payload = part.get_payload()
if part["Content-Transfer-Encoding"] == "quoted-printable":
payload = quopri.decodestring(payload.encode("ascii")).decode(part.get_content_charset("utf-8"))
return payload
class Top:
def __init__(self, title=None, sender=None, body=None, protostub=None, message=None):
@@ -30,10 +45,8 @@ class Top:
self.title = decode_header(message["Subject"])[6:]
real_name, address = email.utils.parseaddr(message["From"])
self.sender = real_name or address
payload = message.get_payload()
if message["Content-Transfer-Encoding"] == "quoted-printable":
payload = quopri.decodestring(payload.encode("ascii")).decode("utf8")
self.body = payload.rpartition("\n--")[0] if "\n--" in payload else payload
payload = get_body_text(message)
self.body = str(payload.rpartition("\n--")[0] if "\n--" in payload else payload)
elif title:
self.title = title
self.sender = sender
@@ -74,6 +87,14 @@ def time(intime):
def weekday(indate):
return WEEKDAYS[indate.weekday()]
def prototop(top):
if "protostub" in dir(top) and top.protostub:
return j2env.from_string(top.protostub).render(context, top=top)
elif top.body:
return j2env.from_string(top.body).render(context)
else:
return None
def conf2top(top):
sender = None
body = None
@@ -127,6 +148,7 @@ if __name__ == "__main__":
j2env.filters["date"] = date
j2env.filters["time"] = time
j2env.filters["weekday"] = weekday
j2env.filters["prototop"] = prototop
template = j2env.from_string(open(template_file).read())
mbox = mailbox.mbox(config["top_mbox_file"])