340 lines
16 KiB
Python
340 lines
16 KiB
Python
"""E-Mails in Stalwart (JMAP, RFC 8620/8621): suchen, lesen, Entwürfe anlegen und Entwürfe absenden.
|
||
|
||
Zugang über .env: STALWART_URL (z. B. https://mail.infra.mintel.me), STALWART_USER, STALWART_APP_PASSWORD
|
||
(App-Passwort aus dem Stalwart-Konto, nicht das Hauptpasswort). Optional MAIL_SEND_ALLOWED: Komma-Liste erlaubter
|
||
Empfänger (Adressen oder '@domain.de'); leer = alle. Gesendet wird nur ein vorhandener Entwurf, genau so wie er im
|
||
Entwürfe-Ordner liegt. Es gibt keine Methode zum Verschieben oder Löschen.
|
||
|
||
Postfach je Nutzer: Mit MAIL_PER_USER=true kommt der Zugang nur noch aus `zugang(...)` (der MCP-Server setzt ihn je
|
||
Anfrage aus den Kopfzeilen, die LibreChat aus den Nutzer-Variablen füllt) – ohne ihn wird abgelehnt, nie auf ein
|
||
gemeinsames Konto zurückgefallen. Ohne MAIL_PER_USER gilt STALWART_USER/STALWART_APP_PASSWORD aus der Umgebung.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import datetime as _dt
|
||
import json
|
||
import os
|
||
import urllib.error
|
||
import urllib.request
|
||
from urllib.parse import quote
|
||
from contextlib import contextmanager
|
||
from contextvars import ContextVar
|
||
|
||
USING = ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail", "urn:ietf:params:jmap:submission"]
|
||
LISTE = ["id", "threadId", "subject", "from", "to", "receivedAt", "preview", "hasAttachment"]
|
||
|
||
|
||
def _env(name: str) -> str:
|
||
val = os.environ.get(name)
|
||
if not val:
|
||
raise SystemExit(f"{name} fehlt in .env (Stalwart-Zugang, siehe butler/mail.py)")
|
||
return val
|
||
|
||
|
||
_ZUGANG: ContextVar[tuple[str, str] | None] = ContextVar("stalwart_zugang", default=None)
|
||
|
||
|
||
def je_nutzer() -> bool:
|
||
return os.environ.get("MAIL_PER_USER", "").strip().lower() in ("1", "true", "yes")
|
||
|
||
|
||
@contextmanager
|
||
def zugang(benutzer: str | None, passwort: str | None):
|
||
"""Stalwart-Zugang für die Dauer eines Aufrufs (Postfach des anfragenden Nutzers). Leere oder nicht ersetzte
|
||
Platzhalter ({{…}}) zählen als fehlend."""
|
||
def wert(v):
|
||
v = (v or "").strip()
|
||
return "" if not v or "{{" in v else v
|
||
b, p = wert(benutzer), wert(passwort)
|
||
marke = _ZUGANG.set((b, p) if b and p else None)
|
||
try:
|
||
yield
|
||
finally:
|
||
_ZUGANG.reset(marke)
|
||
|
||
|
||
def _konto() -> tuple[str, str]:
|
||
z = _ZUGANG.get()
|
||
if z:
|
||
return z
|
||
if je_nutzer():
|
||
raise SystemExit("Kein Postfach verbunden: In LibreChat beim Server „mail“ den eigenen Stalwart-Benutzer und "
|
||
"ein App-Passwort eintragen (Einstellungen der MCP-Server).")
|
||
return _env("STALWART_USER"), _env("STALWART_APP_PASSWORD")
|
||
|
||
|
||
def _auth() -> str:
|
||
benutzer, passwort = _konto()
|
||
roh = f"{benutzer}:{passwort}".encode()
|
||
return "Basic " + base64.b64encode(roh).decode()
|
||
|
||
|
||
def _http(url: str, body: dict | None = None, roh: bytes | None = None, typ: str = "application/json") -> dict:
|
||
daten = roh if roh is not None else (json.dumps(body).encode() if body is not None else None)
|
||
req = urllib.request.Request(url, data=daten, headers={"Authorization": _auth(), "Content-Type": typ})
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||
return json.load(resp)
|
||
except urllib.error.HTTPError as e:
|
||
if e.code == 401:
|
||
raise RuntimeError("Stalwart lehnt den Zugang ab – Mail-Adresse oder App-Passwort stimmen nicht "
|
||
"(in LibreChat beim Server „mail“ neu eintragen).") from e
|
||
raise
|
||
|
||
|
||
def _session() -> dict:
|
||
return _http(_env("STALWART_URL").rstrip("/") + "/.well-known/jmap")
|
||
|
||
|
||
def _sitzung() -> tuple[str, str]:
|
||
s = _session()
|
||
return s["apiUrl"], s["primaryAccounts"]["urn:ietf:params:jmap:mail"]
|
||
|
||
|
||
def _aufruf(calls: list) -> list:
|
||
api, _ = _sitzung()
|
||
antwort = _http(api, {"using": USING, "methodCalls": calls})["methodResponses"]
|
||
for name, inhalt, _ in antwort:
|
||
if name == "error":
|
||
raise RuntimeError(f"JMAP-Fehler: {inhalt}")
|
||
return antwort
|
||
|
||
|
||
def _adr(liste) -> str:
|
||
return ", ".join(f"{a.get('name') or ''} <{a.get('email')}>".strip() for a in (liste or []))
|
||
|
||
|
||
def suchen(text: str = "", absender: str = "", nach: str = "", vor: str = "", anzahl: int = 20) -> list[dict]:
|
||
"""Volltext und/oder Absender; nach/vor als ISO-Datum (YYYY-MM-DD). Neueste zuerst."""
|
||
_, konto = _sitzung()
|
||
f: dict = {}
|
||
if text:
|
||
f["text"] = text
|
||
if absender:
|
||
f["from"] = absender
|
||
if nach:
|
||
f["after"] = f"{nach}T00:00:00Z"
|
||
if vor:
|
||
f["before"] = f"{vor}T00:00:00Z"
|
||
antwort = _aufruf([
|
||
["Email/query", {"accountId": konto, "filter": f, "sort": [{"property": "receivedAt", "isAscending": False}],
|
||
"limit": anzahl}, "q"],
|
||
["Email/get", {"accountId": konto, "#ids": {"resultOf": "q", "name": "Email/query", "path": "/ids"},
|
||
"properties": LISTE}, "g"]])
|
||
return [{"id": m["id"], "datum": m["receivedAt"], "von": _adr(m.get("from")), "an": _adr(m.get("to")),
|
||
"betreff": m.get("subject"), "vorschau": m.get("preview"), "anhang": m.get("hasAttachment")}
|
||
for m in antwort[1][1]["list"]]
|
||
|
||
|
||
def lesen(mail_id: str, max_zeichen: int = 30000) -> dict:
|
||
"""Volltext (Textteil) einer Mail plus Liste der Anhänge."""
|
||
_, konto = _sitzung()
|
||
antwort = _aufruf([["Email/get", {
|
||
"accountId": konto, "ids": [mail_id], "fetchTextBodyValues": True, "maxBodyValueBytes": max_zeichen * 4,
|
||
"properties": LISTE + ["cc", "textBody", "bodyValues", "attachments"]}, "g"]])
|
||
liste = antwort[0][1]["list"]
|
||
if not liste:
|
||
raise ValueError(f"Mail {mail_id} nicht gefunden")
|
||
m = liste[0]
|
||
text = "\n".join(m["bodyValues"][t["partId"]]["value"] for t in m.get("textBody", []) if t["partId"] in m["bodyValues"])
|
||
return {"id": m["id"], "datum": m["receivedAt"], "von": _adr(m.get("from")), "an": _adr(m.get("to")),
|
||
"cc": _adr(m.get("cc")), "betreff": m.get("subject"), "text": text[:max_zeichen],
|
||
"gekuerzt": len(text) > max_zeichen,
|
||
"anhaenge": [{"name": a.get("name"), "typ": a.get("type"), "groesse": a.get("size")}
|
||
for a in m.get("attachments", [])]}
|
||
|
||
|
||
def anhang(mail_id: str, name: str = "") -> tuple[bytes, str, str]:
|
||
"""Anhang einer Mail laden (nach Name; ohne Name: der einzige bzw. erste PDF-Anhang). Gibt (daten, name, typ)."""
|
||
s = _session()
|
||
konto = s["primaryAccounts"]["urn:ietf:params:jmap:mail"]
|
||
liste = _aufruf([["Email/get", {"accountId": konto, "ids": [mail_id],
|
||
"properties": ["attachments"]}, "g"]])[0][1]["list"]
|
||
if not liste:
|
||
raise ValueError(f"Mail {mail_id} nicht gefunden")
|
||
anh = liste[0].get("attachments") or []
|
||
if not anh:
|
||
raise ValueError("Die Mail hat keine Anhänge.")
|
||
if name:
|
||
treffer = [a for a in anh if (a.get("name") or "") == name] or [a for a in anh if name.lower() in (a.get("name") or "").lower()]
|
||
if not treffer:
|
||
raise ValueError(f"Anhang {name!r} nicht gefunden – vorhanden: {', '.join(a.get('name') or '?' for a in anh)}")
|
||
else:
|
||
treffer = [a for a in anh if (a.get("type") or "").endswith("pdf")] or anh
|
||
if len(anh) > 1 and len(treffer) != 1:
|
||
raise ValueError(f"Mehrere Anhänge – bitte Namen angeben: {', '.join(a.get('name') or '?' for a in anh)}")
|
||
a = treffer[0]
|
||
dateiname = a.get("name") or "anhang"
|
||
typ = a.get("type") or "application/octet-stream"
|
||
url = (s["downloadUrl"].replace("{accountId}", quote(konto, safe="")).replace("{blobId}", quote(a["blobId"], safe=""))
|
||
.replace("{name}", quote(dateiname, safe="")).replace("{type}", quote(typ, safe="")))
|
||
req = urllib.request.Request(url, headers={"Authorization": _auth()})
|
||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||
return resp.read(), dateiname, typ
|
||
|
||
|
||
URLAUB = "urn:ietf:params:jmap:vacationresponse"
|
||
|
||
|
||
def _urlaub_konto() -> str:
|
||
s = _session()
|
||
konto = (s.get("primaryAccounts") or {}).get(URLAUB)
|
||
if not konto:
|
||
raise RuntimeError("Der Mailserver bietet keine Abwesenheitsnotiz über JMAP an.")
|
||
return konto
|
||
|
||
|
||
def _urlaub_aufruf(calls: list) -> list:
|
||
api, _ = _sitzung()
|
||
antwort = _http(api, {"using": ["urn:ietf:params:jmap:core", URLAUB], "methodCalls": calls})["methodResponses"]
|
||
for name, inhalt, _ in antwort:
|
||
if name == "error":
|
||
raise RuntimeError(f"JMAP-Fehler: {inhalt}")
|
||
return antwort
|
||
|
||
|
||
def abwesenheit() -> dict:
|
||
"""Aktuelle Abwesenheitsnotiz: aktiv, von, bis, betreff, text."""
|
||
v = (_urlaub_aufruf([["VacationResponse/get", {"accountId": _urlaub_konto(), "ids": ["singleton"]}, "g"]])
|
||
[0][1].get("list") or [{}])[0]
|
||
return {"aktiv": bool(v.get("isEnabled")), "von": v.get("fromDate"), "bis": v.get("toDate"),
|
||
"betreff": v.get("subject"), "text": v.get("textBody")}
|
||
|
||
|
||
def abwesenheit_setzen(aktiv: bool, von: str = "", bis: str = "", betreff: str = "", text: str = "") -> dict:
|
||
"""Abwesenheitsnotiz ein- oder ausschalten. von/bis: Datum YYYY-MM-DD bzw. YYYY-MM-DDTHH:MM (deutsche Zeit);
|
||
bis gilt bis Ende des Tages."""
|
||
from . import kalender
|
||
if aktiv and not text.strip():
|
||
raise ValueError("Text der Abwesenheitsnotiz fehlt")
|
||
aenderung: dict = {"isEnabled": aktiv}
|
||
if aktiv:
|
||
def utc(wert, ende):
|
||
if not wert:
|
||
return None
|
||
t = kalender.eingabe(wert)
|
||
if not isinstance(t, _dt.datetime): # nur Datum: ab 0:00 bzw. bis 23:59:59 deutscher Zeit
|
||
t = _dt.datetime(t.year, t.month, t.day, tzinfo=kalender.BERLIN)
|
||
if ende:
|
||
t += _dt.timedelta(days=1, seconds=-1)
|
||
return t.astimezone(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
anfang, schluss = utc(von, False), utc(bis, True)
|
||
if anfang and schluss and schluss <= anfang:
|
||
raise ValueError("bis liegt vor von")
|
||
aenderung |= {"fromDate": anfang, "toDate": schluss, "subject": betreff.strip() or None,
|
||
"textBody": text.strip()}
|
||
r = _urlaub_aufruf([["VacationResponse/set", {"accountId": _urlaub_konto(),
|
||
"update": {"singleton": aenderung}}, "s"]])[0][1]
|
||
if "singleton" not in (r.get("updated") or {}):
|
||
raise RuntimeError(f"Abwesenheitsnotiz nicht gespeichert: {r.get('notUpdated')}")
|
||
return abwesenheit()
|
||
|
||
|
||
def _adressen(text: str) -> list[dict]:
|
||
aus = []
|
||
for teil in (t.strip() for t in (text or "").replace(";", ",").split(",")):
|
||
if not teil:
|
||
continue
|
||
name, klammer, adr = teil.rpartition("<")
|
||
adr = (adr.rstrip(">") if klammer else teil).strip()
|
||
if adr.count("@") != 1 or " " in adr:
|
||
raise ValueError(f"Keine gültige Mailadresse: {teil!r}")
|
||
aus.append({"name": name.strip().strip('"') or None, "email": adr})
|
||
return aus
|
||
|
||
|
||
def nicht_erlaubt(adressen: list[dict], liste: str | None = None) -> list[str]:
|
||
"""Empfänger, die nicht in MAIL_SEND_ALLOWED stehen (Liste leer = alle erlaubt)."""
|
||
roh = liste if liste is not None else os.environ.get("MAIL_SEND_ALLOWED", "")
|
||
regeln = [r.strip().lower() for r in roh.split(",") if r.strip()]
|
||
if not regeln:
|
||
return []
|
||
return [a["email"] for a in adressen if not any(
|
||
a["email"].lower() == r or (r.startswith("@") and a["email"].lower().endswith(r)) for r in regeln)]
|
||
|
||
|
||
def _ordner(konto: str) -> dict[str, str]:
|
||
r = _aufruf([["Mailbox/get", {"accountId": konto, "properties": ["id", "role"]}, "m"]])
|
||
return {m["role"]: m["id"] for m in r[0][1]["list"] if m.get("role")}
|
||
|
||
|
||
def _identitaet(konto: str) -> dict:
|
||
ids = _aufruf([["Identity/get", {"accountId": konto}, "i"]])[0][1]["list"]
|
||
if not ids:
|
||
raise RuntimeError("Keine Absender-Identität im Mailkonto")
|
||
z = _ZUGANG.get() # Postfach je Nutzer: Absender ist der angemeldete Nutzer
|
||
wunsch = (z[0] if z else os.environ.get("MAIL_FROM", os.environ.get("STALWART_USER", ""))).lower()
|
||
return next((i for i in ids if i.get("email", "").lower() == wunsch), ids[0])
|
||
|
||
|
||
def entwurf(an: str, betreff: str, text: str, cc: str = "", anhaenge: list[tuple[str, bytes, str]] = (),
|
||
antwort_auf: str = "") -> dict:
|
||
"""Legt einen Entwurf im Entwürfe-Ordner an – nichts wird gesendet. anhaenge: (name, daten, mime)."""
|
||
s = _session()
|
||
konto = s["primaryAccounts"]["urn:ietf:params:jmap:mail"]
|
||
to, kopie = _adressen(an), _adressen(cc)
|
||
if not to:
|
||
raise ValueError("Empfänger fehlt")
|
||
ich = _identitaet(konto)
|
||
mail: dict = {"mailboxIds": {_ordner(konto)["drafts"]: True}, "keywords": {"$draft": True, "$seen": True},
|
||
"from": [{"name": ich.get("name") or None, "email": ich["email"]}], "to": to, "subject": betreff,
|
||
"bodyValues": {"t": {"value": text}}, "textBody": [{"partId": "t", "type": "text/plain"}]}
|
||
if kopie:
|
||
mail["cc"] = kopie
|
||
if antwort_auf:
|
||
alt = _aufruf([["Email/get", {"accountId": konto, "ids": [antwort_auf],
|
||
"properties": ["messageId", "references"]}, "g"]])[0][1]["list"]
|
||
if not alt:
|
||
raise ValueError(f"Mail {antwort_auf} nicht gefunden")
|
||
mid = alt[0].get("messageId") or []
|
||
mail["inReplyTo"] = mid
|
||
mail["references"] = (alt[0].get("references") or []) + mid
|
||
if anhaenge:
|
||
upload = s["uploadUrl"].replace("{accountId}", konto)
|
||
mail["attachments"] = [{"blobId": _http(upload, roh=d, typ=mime)["blobId"], "type": mime, "name": name,
|
||
"disposition": "attachment"} for name, d, mime in anhaenge]
|
||
r = _aufruf([["Email/set", {"accountId": konto, "create": {"e": mail}}, "c"]])[0][1]
|
||
if "e" not in (r.get("created") or {}):
|
||
raise RuntimeError(f"Entwurf nicht angelegt: {r.get('notCreated')}")
|
||
return zeigen(r["created"]["e"]["id"])
|
||
|
||
|
||
def zeigen(entwurf_id: str) -> dict:
|
||
"""Entwurf so, wie er gesendet würde: Absender, Empfänger, Betreff, Text, Anhänge."""
|
||
_, konto = _sitzung()
|
||
r = _aufruf([["Email/get", {"accountId": konto, "ids": [entwurf_id], "fetchTextBodyValues": True,
|
||
"properties": ["id", "from", "to", "cc", "bcc", "subject", "keywords", "textBody",
|
||
"bodyValues", "attachments"]}, "g"]])[0][1]["list"]
|
||
if not r:
|
||
raise ValueError(f"Entwurf {entwurf_id} nicht gefunden")
|
||
m = r[0]
|
||
werte = m.get("bodyValues") or {}
|
||
return {"entwurf_id": m["id"], "ist_entwurf": bool((m.get("keywords") or {}).get("$draft")),
|
||
"von": _adr(m.get("from")), "an": _adr(m.get("to")), "cc": _adr(m.get("cc")), "bcc": _adr(m.get("bcc")),
|
||
"betreff": m.get("subject"),
|
||
"text": "\n".join(werte[t["partId"]]["value"] for t in m.get("textBody", []) if t["partId"] in werte),
|
||
"anhaenge": [{"name": a.get("name"), "typ": a.get("type"), "groesse": a.get("size")}
|
||
for a in m.get("attachments", [])],
|
||
"_empfaenger": [a for k in ("to", "cc", "bcc") for a in (m.get(k) or [])]}
|
||
|
||
|
||
def senden(entwurf_id: str) -> dict:
|
||
"""Sendet einen vorhandenen Entwurf unverändert und verschiebt ihn nach „Gesendet“."""
|
||
e = zeigen(entwurf_id)
|
||
if not e["ist_entwurf"]:
|
||
raise ValueError(f"{entwurf_id} ist kein Entwurf (schon gesendet?) – nichts gesendet")
|
||
nein = nicht_erlaubt(e["_empfaenger"])
|
||
if nein:
|
||
raise ValueError(f"Empfänger nicht freigegeben (MAIL_SEND_ALLOWED): {', '.join(nein)} – nichts gesendet")
|
||
_, konto = _sitzung()
|
||
o = _ordner(konto)
|
||
r = _aufruf([["EmailSubmission/set", {
|
||
"accountId": konto, "create": {"s": {"emailId": entwurf_id, "identityId": _identitaet(konto)["id"]}},
|
||
"onSuccessUpdateEmail": {"#s": {f"mailboxIds/{o['drafts']}": None, f"mailboxIds/{o['sent']}": True,
|
||
"keywords/$draft": None}}}, "s"]])[0][1]
|
||
if "s" not in (r.get("created") or {}):
|
||
raise RuntimeError(f"Nicht gesendet: {r.get('notCreated')}")
|
||
return {"gesendet": True, "an": e["an"], "cc": e["cc"], "betreff": e["betreff"],
|
||
"anhaenge": [a["name"] for a in e["anhaenge"]]}
|