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/FSR"') cutoff = ( datetime.date.fromisoformat(c) if (c := os.getenv("IMAP_CUTOFF")) else 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 True: 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().replace("\n", "") received, _ = email.header.decode_header(msg["Date"])[0] received = received.split(";")[-1].strip() date = datetime.datetime.strptime(received, "%a, %d %b %Y %X %z").date() if date < cutoff: return 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)