c-stone-invoice-check/tools/mail_pdfs.py
Markus Kruse 4f9bec81fe feat(tools): Qonto-Abgleich, Mailsuche, PDF-Export, Accountable-Helfer
Wiederverwendbare Session-Skripte parametrisiert ins Repo; Cron Wochenlauf in README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Wd9aeEvgYF6ZmZGc5PTULK
2026-11-15 19:25:53 +01:00

32 lines
1.7 KiB
Python

"""PDF-Anhänge passender Mails aus Strato (INBOX + Archive) und Gmail (INBOX) speichern, nur lesend.
Aufruf (im Backend-Container): python /tmp/mail_pdfs.py <absender> <betreff-begriff> <zielordner>
Dateiname: YYYY-MM-DD_<original>.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))