"""IMAP polling — fetch unseen messages with attachments since last UID.""" import imaplib import email import logging from email.header import decode_header from typing import Iterator log = logging.getLogger(__name__) def _decode_str(value) -> str: if value is None: return "" parts = decode_header(value) out = [] for raw, enc in parts: if isinstance(raw, bytes): out.append(raw.decode(enc or "utf-8", errors="replace")) else: out.append(raw) return " ".join(out) def fetch_new_messages(account: dict) -> Iterator[dict]: """ Yield dicts per attachment: {uid, subject, sender, received_at, filename, data (bytes), size} """ host = account["imap_host"] port = int(account["imap_port"]) ssl = bool(account["imap_ssl"]) user = account["imap_user"] pw = account["imap_password"] folder = account.get("folder", "INBOX") last_uid = int(account["last_uid"]) try: imap = imaplib.IMAP4_SSL(host, port) if ssl else imaplib.IMAP4(host, port) except Exception as exc: log.error("IMAP connect failed for %s: %s", user, exc) return try: imap.login(user, pw) except Exception as exc: log.error("IMAP login failed for %s: %s", user, exc) imap.logout() return try: imap.select(folder, readonly=True) except Exception as exc: log.error("IMAP select folder %s failed for %s: %s", folder, user, exc) imap.logout() return try: typ, data = imap.uid("search", None, f"UID {last_uid + 1}:*") if typ != "OK" or not data or not data[0]: return uid_list = data[0].split() for uid_bytes in uid_list: uid = int(uid_bytes) if uid <= last_uid: continue typ2, msg_data = imap.uid("fetch", uid_bytes, "(RFC822)") if typ2 != "OK" or not msg_data or not msg_data[0]: continue raw = msg_data[0][1] msg = email.message_from_bytes(raw) subject = _decode_str(msg.get("Subject", "")) sender = _decode_str(msg.get("From", "")) date_str = msg.get("Date", "") from email.utils import parsedate_to_datetime try: received_at = parsedate_to_datetime(date_str) except Exception: received_at = None for part in msg.walk(): if part.get_content_maintype() == "multipart": continue if part.get("Content-Disposition") is None: continue filename = part.get_filename() if not filename: continue filename = _decode_str(filename) data_bytes = part.get_payload(decode=True) if not data_bytes: continue yield { "uid": uid, "subject": subject, "sender": sender, "received_at": received_at, "filename": filename, "data": data_bytes, "size": len(data_bytes), } finally: try: imap.logout() except Exception: pass