"""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}