fsremail/main.py
2024-09-02 16:56:54 +02:00

62 lines
1.8 KiB
Python

import datetime
import email
import email.header
import imaplib
import os
passw = os.getenv("IMAP_PASSWORD", "")
mail = os.getenv("IMAP_EMAIL", "")
domain = os.getenv("IMAP_SERVER", "imap.uni-potsdam.de")
folder = os.getenv("IMAP_FOLDER", "Uni Mail")
cutoff = os.getenv("IMAP_CUTOFF") or datetime.date.today() - datetime.timedelta(weeks=1)
def get_titles(cutoff):
with imaplib.IMAP4_SSL(domain) as imap:
imap.login(mail, passw)
status, [message_count] = imap.select(folder)
message_count = int(message_count)
m = message_count
date = datetime.date.today()
while date >= cutoff:
res, msg = imap.fetch(str(m), "(RFC822)") # fetches email using ID
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1])
subj = msg["Subject"]
subj = subj.split("[FSR MaPhy]", 1)[1]
decoded_subj, enc = email.header.decode_header(subj)[0]
if isinstance(decoded_subj, bytes):
decoded_subj = decoded_subj.decode(enc)
decoded_subj = decoded_subj.strip()
received, _ = email.header.decode_header(msg["Received"])[0]
received = received.split(";")[-1].strip()
date = datetime.datetime.strptime(received, "%a, %d %b %Y %X +0200").date()
yield date.isoformat(), decoded_subj
m -= 1
def generate_template(cutoff, template):
for date, subject in get_titles(cutoff):
yield template.format(date, subject)
if __name__ == "__main__":
template = r"""\textbf{{{}: {}}}
\begin{{itemize}}
\item
\end{{itemize}}"""
for t in generate_template(cutoff, template):
print(t)