from exchangelib import FileAttachment from serenitas.utils.env import DAILY_DIR from serenitas.utils.exchange import ExchangeMessage from io import BytesIO em = ExchangeMessage() emails = em.get_msgs(path=["NYops", "FXgo"], count=5, subject__contains="Notification") for msg in emails: cp = msg.subject.split("/", 1)[0] for attach in msg.attachments: if isinstance(attach, FileAttachment): with attach.fp as fh: for _ in range(4): next(fh) buf = BytesIO() # header line buf.write(next(fh)) line = next(fh) if b"DEAL" in line: msg_type = "DEAL" elif b"ALOC" in line: msg_type = "ALOC" else: raise ValueError("Unknown message type") fname = f"{msg.last_modified_time:%Y%m%d}_{cp}_{msg_type}_{msg.last_modified_time:%H%M%S}.csv" dest = DAILY_DIR / "fxgo" / fname if dest.exists(): continue buf.write(line) buf.writelines(iter(fh.readline, b"-----BEGIN PGP SIGNATURE-----\n")) with dest.open("wb") as fh: fh.write(buf.getbuffer())