93 lines
3.8 KiB
Python
93 lines
3.8 KiB
Python
"""E-Mails aus Stalwart (JMAP, RFC 8620/8621) – nur lesen.
|
||
|
||
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). Es gibt bewusst keine Methode zum Senden,
|
||
Verschieben oder Löschen.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import json
|
||
import os
|
||
import urllib.request
|
||
|
||
USING = ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"]
|
||
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 shield/mail.py)")
|
||
return val
|
||
|
||
|
||
def _auth() -> str:
|
||
roh = f"{_env('STALWART_USER')}:{_env('STALWART_APP_PASSWORD')}".encode()
|
||
return "Basic " + base64.b64encode(roh).decode()
|
||
|
||
|
||
def _http(url: str, body: dict | None = None) -> dict:
|
||
req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
|
||
headers={"Authorization": _auth(), "Content-Type": "application/json"})
|
||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||
return json.load(resp)
|
||
|
||
|
||
def _sitzung() -> tuple[str, str]:
|
||
s = _http(_env("STALWART_URL").rstrip("/") + "/.well-known/jmap")
|
||
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", [])]}
|