"""Alle Ordner der Postfächer (Strato + optional Gmail) nach Begriffen durchsuchen, nur lesend. Aufruf (im Backend-Container): python /tmp/mail_suche.py [begriff ...] Sucht je Begriff in FROM, SUBJECT und TEXT; zeigt die letzten 20 Treffer je Ordner/Kriterium. """ import email, os, sys from backend.routers.emails import connect_imap, decode_hdr terms = sys.argv[1:] or sys.exit(__doc__) boxes = [(os.getenv('IMAP_HOST', 'imap.strato.de'), int(os.getenv('IMAP_PORT', '993')), os.getenv('IMAP_USER'), os.getenv('IMAP_PASSWORD'))] if os.getenv('GMAIL_IMAP_PASSWORD'): boxes.append(('imap.gmail.com', 993, os.getenv('GMAIL_IMAP_USER'), os.getenv('GMAIL_IMAP_PASSWORD'))) for h, p, u, pw in boxes: m = connect_imap(h, p, u, pw) for f in m.list()[1]: name = f.decode().split(' "/" ')[-1].split(' "." ')[-1].strip() if m.select(name if name.startswith('"') else f'"{name}"', readonly=True)[0] != 'OK': continue for term in terms: seen = set() for crit in (f'FROM "{term}"', f'SUBJECT "{term}"', f'TEXT "{term}"'): try: ids = m.search(None, crit)[1][0].split() except Exception: continue for i in ids[-20:]: if i in seen: continue seen.add(i) hd = email.message_from_bytes(m.fetch(i, '(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])')[1][0][1]) print(h[:12], name[:20], '|', term, '|', hd.get('Date', '')[:16], '|', decode_hdr(hd.get('From', ''))[:40], '|', decode_hdr(hd.get('Subject', ''))[:70]) m.logout()