"""Qonto-Zahlungsmails (Strato) nach Händler durchsuchen, nur lesend: Betrag, Originalwährung, Karte. Aufruf (im Backend-Container, PYTHONPATH=/app): python /tmp/qonto_mails.py [...] Zweck: Bankbetrag (EUR) über USD-Originalbetrag exakt einem $-Beleg zuordnen (Whop, Invideo, ...). """ import email, email.utils, os, re, html, sys from backend.routers.emails import connect_imap terms=sys.argv[1:] m=connect_imap(os.getenv('IMAP_HOST','imap.strato.de'),993,os.getenv('IMAP_USER'),os.getenv('IMAP_PASSWORD')) def body(msg): for p in msg.walk(): if p.get_content_type() in('text/plain','text/html'): t=p.get_payload(decode=True).decode(p.get_content_charset() or 'utf-8','replace') if p.get_content_type()=='text/html': t=html.unescape(re.sub(r'<[^>]+>',' ',re.sub(r'(?s)<(style|script).*?','',t))) return ' '.join(t.split()) return '' for f in ['INBOX','Archive','Archive.2026','Archive.2025']: if m.select(f'"{f}"',readonly=True)[0]!='OK': continue for term in terms: for i in m.search(None,f'FROM "qonto" TEXT "{term}"')[1][0].split(): msg=email.message_from_bytes(m.fetch(i,'(BODY.PEEK[])')[1][0][1]) b=body(msg); k=b.lower().find(term.lower()) print(f,'|',msg['Date'][:22],'|',term,'|',b[max(0,k-200):k+250])