"""PDF-Anhänge passender Mails aus Strato (INBOX + Archive) und Gmail (INBOX) speichern, nur lesend. Aufruf (im Backend-Container): python /tmp/mail_pdfs.py Dateiname: YYYY-MM-DD_.pdf; gleicher Name wird nicht doppelt geschrieben. """ import email, email.utils, os, re, sys from backend.routers.emails import connect_imap if len(sys.argv) != 4: sys.exit(__doc__) sender, subject, out = sys.argv[1:] os.makedirs(out, exist_ok=True) boxes = [(os.getenv('IMAP_HOST', 'imap.strato.de'), os.getenv('IMAP_USER'), os.getenv('IMAP_PASSWORD'), ['INBOX', 'Archive', 'Archive.2026', 'Archive.2025']), ('imap.gmail.com', os.getenv('GMAIL_IMAP_USER'), os.getenv('GMAIL_IMAP_PASSWORD'), ['INBOX'])] got = [] for h, u, pw, folders in boxes: if not pw: continue m = connect_imap(h, 993, u, pw) for f in folders: if m.select(f'"{f}"', readonly=True)[0] != 'OK': continue for i in m.search(None, f'FROM "{sender}" SUBJECT "{subject}"')[1][0].split(): msg = email.message_from_bytes(m.fetch(i, '(BODY.PEEK[])')[1][0][1]) try: d = email.utils.parsedate_to_datetime(msg.get('Date')).date().isoformat() except Exception: d = 'ohne-datum' for part in msg.walk(): fn = part.get_filename() if not fn or not fn.lower().endswith('.pdf'): continue safe = re.sub(r'[^\w.-]', '_', fn) path = os.path.join(out, f'{d}_{safe}') if os.path.exists(path): continue open(path, 'wb').write(part.get_payload(decode=True)); got.append(path) m.logout() print(len(got), 'PDFs:'); print('\n'.join(got))