Zeige den Bezug zwischen Schreiben und lies eine E-Mail vor dem Uebernehmen.
Deploy Development / deploy (push) Successful in 27s
Test Suite / pytest-backend (push) Successful in 1m10s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 8s

Die Liste behaelt die Schreiben dazwischen. Richtung, Absender, Empfaenger und Anhaenge bleiben an der Nachricht erkennbar.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-17 17:27:17 +02:00
1 parent 97bffc6175
commit f27df3ff35
19 files changed
+1049 -49

No files matched your search

+167 -1
View File
@@ -143,6 +143,21 @@ def imap_messages(
_imap_logout(client)
def imap_preview(conn, owner_id: UUID, connector_id: UUID, mailbox: str, uid: int) -> dict:
row = _owned(conn, owner_id, connector_id)
if row["kind"] != "imap":
raise unprocessable("Das ist kein E-Mail-Konto.")
_check_mailbox(mailbox)
if uid < 1:
raise unprocessable("Die Nachricht ist ungültig.")
client = _imap_login(row["settings"], row["secret"])
try:
_select_mailbox(client, mailbox)
return _fetch_message(client, uid, mailbox)
finally:
_imap_logout(client)
def _owned(conn, owner_id: UUID, connector_id: UUID) -> dict:
row = conn.execute(
"SELECT id, kind, name, settings, secret FROM connectors WHERE id = %s AND owner_id = %s",
@@ -432,13 +447,42 @@ def _uid_search(client: imaplib.IMAP4, query: str):
raise unprocessable("Das Postfach kann diese Suche nicht ausführen. Blättere im Fach oder kürze den Suchtext.") from exc
def _check_mailbox(mailbox: str) -> None:
if any(char in mailbox for char in "\r\n\x00"):
raise unprocessable("Der Fachname ist ungültig.")
def _select_mailbox(client: imaplib.IMAP4, mailbox: str) -> None:
folders = _imap_mailboxes(client)
match = next((item for item in folders if item["name"] == mailbox), None)
if match is None or not match["selectable"]:
raise unprocessable("Dieses Fach gibt es in dem Konto nicht.")
try:
status, _ = client.select(mailbox, readonly=True)
except imaplib.IMAP4.error as exc:
raise unprocessable("Dieses Fach lässt sich nicht öffnen.") from exc
if status != "OK":
raise unprocessable("Dieses Fach lässt sich nicht öffnen.")
def _fetch_header(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict | None:
try:
status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE MESSAGE-ID)])")
status, fetched = client.uid(
"FETCH",
str(uid),
"(BODY.PEEK[HEADER.FIELDS (FROM TO CC SUBJECT DATE MESSAGE-ID)])",
)
except imaplib.IMAP4.error:
return None
if status != "OK" or not fetched or not isinstance(fetched[0], tuple):
return None
attachments = []
try:
struct_status, structure = client.uid("FETCH", str(uid), "(BODYSTRUCTURE)")
if struct_status == "OK":
attachments = _structure_attachments(structure)
except imaplib.IMAP4.error:
attachments = []
header = BytesParser().parsebytes(fetched[0][1])
subject = _decode(header.get("Subject")) or "(ohne Betreff)"
sender = _decode(header.get("From"))
@@ -448,10 +492,132 @@ def _fetch_header(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict | None:
"uid": uid,
"title": subject[:200],
"message_from": sender[:200],
"message_to": _decode(header.get("To"))[:500],
"message_cc": _decode(header.get("Cc"))[:500],
"direction": _direction(mailbox),
"attachments": attachments,
"document_on": _mail_date(header.get("Date")),
}
def _fetch_message(client: imaplib.IMAP4, uid: int, mailbox: str) -> dict:
try:
status, fetched = client.uid("FETCH", str(uid), "(BODY.PEEK[])")
except imaplib.IMAP4.error as exc:
raise unprocessable("Die Nachricht lässt sich nicht lesen.") from exc
raw = _literal(fetched)
if status != "OK" or raw is None:
raise unprocessable("Die Nachricht lässt sich nicht lesen.")
if len(raw) > 1_500_000:
raise unprocessable("Die Nachricht ist zu groß für die Vorschau.")
message = BytesParser().parsebytes(raw)
subject = _decode(message.get("Subject")) or "(ohne Betreff)"
return {
"uid": uid,
"mailbox": mailbox,
"title": subject[:200],
"message_from": _decode(message.get("From"))[:200],
"message_to": _decode(message.get("To"))[:500],
"message_cc": _decode(message.get("Cc"))[:500],
"direction": _direction(mailbox),
"document_on": _mail_date(message.get("Date")),
"attachments": _message_attachments(message),
"text": _message_text(message),
}
_SENT_FOLDER = re.compile(
r"(^|/)(sent|sent items|sent messages|gesendet|gesendete|gesendete elemente|outbox|postausgang)($|/)",
re.IGNORECASE,
)
def _direction(mailbox: str) -> str:
folded = mailbox.casefold().replace("\\", "/")
return "out" if _SENT_FOLDER.search(folded) else "in"
def _literal(fetched) -> bytes | None:
for part in fetched or []:
if isinstance(part, tuple) and len(part) > 1 and isinstance(part[1], (bytes, bytearray)):
return bytes(part[1])
return None
def _structure_attachments(fetched) -> list[dict]:
chunks: list[bytes] = []
for part in fetched or []:
if isinstance(part, tuple):
chunks.extend(bytes(item) for item in part if isinstance(item, (bytes, bytearray)))
elif isinstance(part, (bytes, bytearray)):
chunks.append(bytes(part))
blob = b" ".join(chunks)
names = re.findall(br'FILENAME"\s+"([^"\r\n]+)"', blob, flags=re.IGNORECASE)
items = []
seen: set[str] = set()
for raw in names:
name = raw.decode("utf-8", errors="replace").strip()[:200]
if not name or name in seen:
continue
seen.add(name)
items.append({"filename": name})
if len(items) == 40:
break
return items
def _message_attachments(message) -> list[dict]:
items = []
seen: set[str] = set()
for part in message.walk():
filename = part.get_filename()
if not filename:
continue
name = _decode(filename)[:200]
if not name or name in seen:
continue
seen.add(name)
items.append({"filename": name, "content_type": part.get_content_type()[:120]})
if len(items) == 40:
break
return items
def _message_text(message) -> str:
plain: list[str] = []
html: list[str] = []
parts = message.walk() if message.is_multipart() else [message]
for part in parts:
if part.is_multipart() or part.get_content_disposition() == "attachment" or part.get_filename():
continue
kind = part.get_content_type()
if kind == "text/plain":
plain.append(_part_text(part))
elif kind == "text/html":
html.append(_html_text(_part_text(part)))
text = "\n".join(chunk for chunk in plain if chunk).strip()
if not text:
text = "\n".join(chunk for chunk in html if chunk).strip()
return text[:8000]
def _part_text(part) -> str:
payload = part.get_payload(decode=True)
if payload is None:
raw = part.get_payload()
return raw.strip() if isinstance(raw, str) else ""
charset = part.get_content_charset() or "utf-8"
return payload.decode(charset, errors="replace").strip()
def _html_text(value: str) -> str:
text = re.sub(r"(?is)<(script|style)\b.*?>.*?</\1>", " ", value)
text = re.sub(r"(?i)<br\s*/?>", "\n", text)
text = re.sub(r"(?i)</p>", "\n", text)
text = re.sub(r"<[^>]+>", " ", text)
return re.sub(r"[ \t]{2,}", " ", text).strip()
def _parse_list_line(raw) -> dict | None:
if not isinstance(raw, (bytes, str)) or not raw:
return None