"""Versand gezogener Rechnungen an Accountable (Beleg-Eingangsadresse) per SMTP.""" import os import smtplib from datetime import datetime from email.message import EmailMessage from sqlalchemy.orm import Session from backend.models import Outbound def _cfg() -> dict: return { "host": os.getenv("SMTP_HOST", "smtp.strato.de"), "port": int(os.getenv("SMTP_PORT", "465")), "user": os.getenv("SMTP_USER") or os.getenv("IMAP_USER", ""), "password": os.getenv("SMTP_PASSWORD") or os.getenv("IMAP_PASSWORD", ""), "to": os.getenv("ACCOUNTABLE_INBOX", ""), } def send_queued(db: Session) -> dict: """Alle Outbound-Zeilen mit status=queued senden (eine Mail pro Rechnung). Ohne ACCOUNTABLE_INBOX: nichts.""" c = _cfg() if not c["to"]: return {"sent": 0, "failed": 0, "skipped": "ACCOUNTABLE_INBOX fehlt"} rows = db.query(Outbound).filter(Outbound.status == "queued").all() sent = failed = 0 if not rows: return {"sent": 0, "failed": 0} with smtplib.SMTP_SSL(c["host"], c["port"], timeout=60) as s: s.login(c["user"], c["password"]) for r in rows: try: msg = EmailMessage() msg["From"], msg["To"] = c["user"], c["to"] msg["Subject"] = f"Rechnung: {r.email_subject or os.path.basename(r.file_path)}"[:200] msg.set_content(f"Automatisch abgerufen (Invoice Picker).\nOriginal-Mail: {r.email_date:%d.%m.%Y} von {r.email_from}" if r.email_date else "Automatisch abgerufen (Invoice Picker).") with open(r.file_path, "rb") as f: msg.add_attachment(f.read(), maintype="application", subtype="pdf", filename=os.path.basename(r.file_path)) s.send_message(msg) r.status, r.sent_at, r.error = "sent", datetime.utcnow(), None sent += 1 except Exception as e: r.status, r.error = "failed", f"Versand: {e}"[:500] failed += 1 db.commit() return {"sent": sent, "failed": failed} def report_text(db: Session, state: dict, since) -> str: from sqlalchemy import func totals = dict(db.query(Outbound.status, func.count()).group_by(Outbound.status).all()) manual = (db.query(Outbound).filter(Outbound.status == "manual", Outbound.email_date >= since) .order_by(Outbound.email_date).all()) lines = [f"Invoice Picker – Wochenlauf ab {since:%d.%m.%Y}", "", f"Neu: {state.get('counts') or 'nichts'}", f"Versand: {state.get('versand', '-')}", f"Gesamtstand: {totals}", ""] if manual: lines.append("Manuell abholen (kein Direktlink/Portal):") lines += [f"- {r.email_date:%d.%m.} {r.email_from}: {r.email_subject}" for r in manual] if state.get("errors"): lines += ["", "Fehler:"] + [f"- {e}" for e in state["errors"][:20]] return "\n".join(lines) def send_report(db: Session, state: dict, since): """Kurzbericht an das eigene Postfach (SMTP-User = Markus), nie an Accountable.""" c = _cfg() msg = EmailMessage() msg["From"] = msg["To"] = c["user"] msg["Subject"] = f"Invoice Picker Wochenbericht {datetime.now():%d.%m.%Y}" msg.set_content(report_text(db, state, since)) with smtplib.SMTP_SSL(c["host"], c["port"], timeout=60) as s: s.login(c["user"], c["password"]) s.send_message(msg)