webde-readonly-imap 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """WEB.DE IMAP access with read-only operations only."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,206 @@
1
+ """Small IMAP adapter. All mailbox selection is EXAMINE; all fetches use PEEK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import imaplib
6
+ import os
7
+ import re
8
+ import ssl
9
+ from email import policy
10
+ from email.header import decode_header, make_header
11
+ from email.parser import BytesParser
12
+ from email.utils import parsedate_to_datetime
13
+ from typing import Any, Callable
14
+
15
+ HOST = "imap.web.de"
16
+ PORT = 993
17
+ READ_ONLY = True
18
+ _ALLOWED_UIDS = re.compile(r"[0-9]+(?:\s+[0-9]+)*\Z")
19
+
20
+
21
+ class AdapterError(RuntimeError):
22
+ """A safe, credential-free error suitable for CLI/MCP output."""
23
+
24
+
25
+ def _credentials() -> tuple[str, str]:
26
+ user = os.environ.get("WEBDE_IMAP_USER", "")
27
+ password = os.environ.get("WEBDE_IMAP_PASSWORD", "")
28
+ if not user or not password:
29
+ raise AdapterError("WEBDE_IMAP_USER und WEBDE_IMAP_PASSWORD müssen privat gesetzt sein.")
30
+ return user, password
31
+
32
+
33
+ def _decode(value: Any) -> str:
34
+ if value is None:
35
+ return ""
36
+ try:
37
+ return str(make_header(decode_header(value)))
38
+ except (ValueError, TypeError):
39
+ return str(value)
40
+
41
+
42
+ def _check(result: tuple[str, Any], operation: str) -> Any:
43
+ status, data = result
44
+ if status != "OK":
45
+ raise AdapterError(f"IMAP-Vorgang fehlgeschlagen: {operation}")
46
+ return data
47
+
48
+
49
+ def _mailbox(value: str) -> str:
50
+ if not value or "\r" in value or "\n" in value or "\x00" in value:
51
+ raise AdapterError("Ungültiger Postfachname.")
52
+ return value
53
+
54
+
55
+ def _uid(value: str) -> str:
56
+ if not value.isdigit() or int(value) < 1:
57
+ raise AdapterError("UID muss eine positive ganze Zahl sein.")
58
+ return value
59
+
60
+
61
+ class WebdeReadOnlyAdapter:
62
+ """Only LIST, EXAMINE, UID SEARCH, UID FETCH BODY.PEEK and LOGOUT are used."""
63
+
64
+ def __init__(self, connection_factory: Callable[[], Any] | None = None):
65
+ self._connection_factory = connection_factory or self._connect
66
+
67
+ @staticmethod
68
+ def _connect() -> imaplib.IMAP4_SSL:
69
+ user, password = _credentials()
70
+ context = ssl.create_default_context()
71
+ return imaplib.IMAP4_SSL(HOST, PORT, ssl_context=context), user, password
72
+
73
+ def _session(self):
74
+ made = self._connection_factory()
75
+ if isinstance(made, tuple):
76
+ connection, user, password = made
77
+ else:
78
+ user, password = _credentials()
79
+ connection = made
80
+ try:
81
+ _check(connection.login(user, password), "Anmeldung")
82
+ except Exception as exc:
83
+ try:
84
+ connection.shutdown()
85
+ except Exception:
86
+ pass
87
+ if isinstance(exc, AdapterError):
88
+ raise
89
+ raise AdapterError("IMAP-Anmeldung fehlgeschlagen. Zugangsdaten und IMAP-Freigabe prüfen.") from None
90
+ return connection
91
+
92
+ def list_mailboxes(self) -> list[dict[str, str]]:
93
+ connection = self._session()
94
+ try:
95
+ entries = _check(connection.list(), "Postfächer auflisten")
96
+ result = []
97
+ for entry in entries:
98
+ if entry is None:
99
+ continue
100
+ text = entry.decode("utf-8", "replace") if isinstance(entry, bytes) else str(entry)
101
+ match = re.match(r'\((?P<flags>[^)]*)\)\s+"(?P<delimiter>[^"]*)"\s+(?P<name>.+)\Z', text)
102
+ if not match:
103
+ continue
104
+ name = match.group("name")
105
+ if len(name) >= 2 and name[0] == name[-1] == '"':
106
+ name = name[1:-1].replace('\\"', '"').replace("\\\\", "\\")
107
+ result.append({"name": name, "flags": match.group("flags")})
108
+ return result
109
+ finally:
110
+ self._logout(connection)
111
+
112
+ def _examine(self, connection: Any, mailbox: str) -> None:
113
+ _check(connection.select(_mailbox(mailbox), readonly=READ_ONLY), "Postfach schreibgeschützt öffnen")
114
+
115
+ @staticmethod
116
+ def _message_numbers(connection: Any, limit: int) -> list[str]:
117
+ if not 1 <= limit <= 200:
118
+ raise AdapterError("limit muss zwischen 1 und 200 liegen.")
119
+ data = _check(connection.uid("SEARCH", None, "ALL"), "Nachrichten suchen")
120
+ raw = data[0].decode("ascii") if data and data[0] else ""
121
+ if raw and not _ALLOWED_UIDS.fullmatch(raw):
122
+ raise AdapterError("Unerwartete IMAP-Antwort bei der Nachrichtensuche.")
123
+ return raw.split()[-limit:][::-1]
124
+
125
+ def list_messages(self, mailbox: str = "INBOX", limit: int = 20) -> list[dict[str, Any]]:
126
+ connection = self._session()
127
+ try:
128
+ self._examine(connection, mailbox)
129
+ messages = []
130
+ for uid in self._message_numbers(connection, limit):
131
+ data = _check(
132
+ connection.uid("FETCH", uid, "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])"),
133
+ "Nachrichtenkopf lesen",
134
+ )
135
+ raw = self._fetch_bytes(data)
136
+ message = BytesParser(policy=policy.default).parsebytes(raw)
137
+ messages.append({"uid": uid, "from": _decode(message.get("From")), "subject": _decode(message.get("Subject")), "date": self._date(message)})
138
+ return messages
139
+ finally:
140
+ self._logout(connection)
141
+
142
+ def read_message(self, mailbox: str, uid: str) -> dict[str, Any]:
143
+ uid = _uid(uid)
144
+ connection = self._session()
145
+ try:
146
+ self._examine(connection, mailbox)
147
+ data = _check(connection.uid("FETCH", uid, "(BODY.PEEK[])"), "Nachricht lesen")
148
+ message = BytesParser(policy=policy.default).parsebytes(self._fetch_bytes(data))
149
+ plain, html = [], []
150
+ if message.is_multipart():
151
+ for part in message.walk():
152
+ if part.get_content_disposition() == "attachment":
153
+ continue
154
+ if part.get_content_type() == "text/plain":
155
+ plain.append(part.get_content())
156
+ elif part.get_content_type() == "text/html":
157
+ html.append(part.get_content())
158
+ elif message.get_content_type() == "text/html":
159
+ html.append(message.get_content())
160
+ else:
161
+ plain.append(message.get_content())
162
+ return {
163
+ "uid": uid,
164
+ "mailbox": mailbox,
165
+ "from": _decode(message.get("From")),
166
+ "to": _decode(message.get("To")),
167
+ "subject": _decode(message.get("Subject")),
168
+ "date": self._date(message),
169
+ "text": "\n".join(plain) if plain else "",
170
+ "html": "\n".join(html) if not plain else "",
171
+ "attachments": [part.get_filename() or "unbenannt" for part in message.iter_attachments()],
172
+ }
173
+ finally:
174
+ self._logout(connection)
175
+
176
+ @staticmethod
177
+ def _date(message: Any) -> str:
178
+ value = message.get("Date")
179
+ if not value:
180
+ return ""
181
+ try:
182
+ return parsedate_to_datetime(value).isoformat()
183
+ except (TypeError, ValueError):
184
+ return str(value)
185
+
186
+ @staticmethod
187
+ def _fetch_bytes(data: Any) -> bytes:
188
+ chunks = []
189
+ for item in data or []:
190
+ if isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], bytes):
191
+ chunks.append(item[1])
192
+ elif isinstance(item, bytes):
193
+ chunks.append(item)
194
+ if not chunks:
195
+ raise AdapterError("Nachricht nicht gefunden oder leere IMAP-Antwort.")
196
+ return b"".join(chunks)
197
+
198
+ @staticmethod
199
+ def _logout(connection: Any) -> None:
200
+ try:
201
+ connection.logout()
202
+ except Exception:
203
+ try:
204
+ connection.shutdown()
205
+ except Exception:
206
+ pass
@@ -0,0 +1,95 @@
1
+ """JSON CLI and dependency-free MCP stdio server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from typing import Any
9
+
10
+ from .adapter import AdapterError, WebdeReadOnlyAdapter
11
+
12
+ TOOLS = [
13
+ {"name": "webde_list_mailboxes", "description": "WEB.DE-Postfächer nur lesend auflisten.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
14
+ {"name": "webde_list_messages", "description": "Absender, Betreff und Datum ohne Änderung von Flags auflisten.", "inputSchema": {"type": "object", "properties": {"mailbox": {"type": "string", "default": "INBOX"}, "limit": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20}}, "additionalProperties": False}},
15
+ {"name": "webde_read_message", "description": "Eine Nachricht per UID mit BODY.PEEK lesen, ohne sie als gelesen zu markieren.", "inputSchema": {"type": "object", "properties": {"mailbox": {"type": "string"}, "uid": {"type": "string", "pattern": "^[1-9][0-9]*$"}}, "required": ["mailbox", "uid"], "additionalProperties": False}},
16
+ ]
17
+
18
+
19
+ def dispatch(name: str, args: dict[str, Any], adapter: WebdeReadOnlyAdapter | None = None) -> Any:
20
+ adapter = adapter or WebdeReadOnlyAdapter()
21
+ if name == "webde_list_mailboxes":
22
+ if args:
23
+ raise AdapterError("Dieses Werkzeug akzeptiert keine Argumente.")
24
+ return adapter.list_mailboxes()
25
+ if name == "webde_list_messages":
26
+ return adapter.list_messages(**args)
27
+ if name == "webde_read_message":
28
+ return adapter.read_message(**args)
29
+ raise AdapterError("Unbekanntes Werkzeug.")
30
+
31
+
32
+ def serve_mcp() -> None:
33
+ """Implement the MCP stdio framing used by current MCP clients."""
34
+ for line in sys.stdin:
35
+ try:
36
+ request = json.loads(line)
37
+ request_id = request.get("id")
38
+ method = request.get("method")
39
+ if method == "initialize":
40
+ result = {"protocolVersion": request.get("params", {}).get("protocolVersion", "2024-11-05"), "capabilities": {"tools": {}}, "serverInfo": {"name": "webde-readonly-imap", "version": "1.0.0"}}
41
+ elif method == "tools/list":
42
+ result = {"tools": TOOLS}
43
+ elif method == "tools/call":
44
+ params = request.get("params", {})
45
+ payload = dispatch(params.get("name", ""), params.get("arguments", {}))
46
+ structured = payload if isinstance(payload, dict) else {"items": payload}
47
+ result = {"content": [{"type": "text", "text": json.dumps(payload, ensure_ascii=False)}], "structuredContent": structured}
48
+ elif method == "ping":
49
+ result = {}
50
+ elif request_id is None:
51
+ continue
52
+ else:
53
+ response = {"jsonrpc": "2.0", "id": request_id, "error": {"code": -32601, "message": "Method not found"}}
54
+ print(json.dumps(response), flush=True)
55
+ continue
56
+ if request_id is not None:
57
+ print(json.dumps({"jsonrpc": "2.0", "id": request_id, "result": result}, ensure_ascii=False), flush=True)
58
+ except Exception as exc:
59
+ request_id = locals().get("request", {}).get("id")
60
+ if request_id is not None:
61
+ message = str(exc) if isinstance(exc, AdapterError) else "Interner Adapterfehler."
62
+ print(json.dumps({"jsonrpc": "2.0", "id": request_id, "error": {"code": -32000, "message": message}}, ensure_ascii=False), flush=True)
63
+
64
+
65
+ def parser() -> argparse.ArgumentParser:
66
+ result = argparse.ArgumentParser(prog="webde-readonly-imap", description="Strikt schreibgeschützter WEB.DE-IMAP-Adapter")
67
+ commands = result.add_subparsers(dest="command")
68
+ commands.add_parser("list-mailboxes")
69
+ listing = commands.add_parser("list-messages")
70
+ listing.add_argument("--mailbox", default="INBOX")
71
+ listing.add_argument("--limit", type=int, default=20)
72
+ reading = commands.add_parser("read-message")
73
+ reading.add_argument("--mailbox", required=True)
74
+ reading.add_argument("--uid", required=True)
75
+ commands.add_parser("mcp")
76
+ return result
77
+
78
+
79
+ def main() -> None:
80
+ args = parser().parse_args()
81
+ if args.command in (None, "mcp"):
82
+ serve_mcp()
83
+ return
84
+ try:
85
+ name = {"list-mailboxes": "webde_list_mailboxes", "list-messages": "webde_list_messages", "read-message": "webde_read_message"}[args.command]
86
+ arguments = vars(args)
87
+ arguments.pop("command")
88
+ print(json.dumps(dispatch(name, arguments), ensure_ascii=False, indent=2))
89
+ except AdapterError as exc:
90
+ print(json.dumps({"error": str(exc)}, ensure_ascii=False), file=sys.stderr)
91
+ raise SystemExit(2) from None
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.5
2
+ Name: webde-readonly-imap
3
+ Version: 1.0.0
4
+ Summary: Read-only WEB.DE IMAP CLI and MCP adapter
5
+ Author: WEB.DE read-only adapter contributors
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+
13
+ # WEB.DE Read-only IMAP
14
+
15
+ Kleiner Python-Adapter für **ausschließlich lesenden** Zugriff auf WEB.DE per CLI oder MCP über stdio. Keine Drittanbieter-Laufzeitabhängigkeiten.
16
+
17
+ ## Sicherheitsgrenzen
18
+
19
+ - Fest eingestellt: `imap.web.de`, Port `993`, implizites TLS mit System-Zertifikatsprüfung.
20
+ - Postfächer werden mit IMAP `EXAMINE` (`readonly=True`) geöffnet.
21
+ - Nachrichten werden ausschließlich mit `BODY.PEEK` abgerufen. Dadurch wird keine Nachricht als gelesen markiert.
22
+ - Es gibt keine Funktionen zum Senden, Löschen, Verschieben, Markieren oder Ändern von Postfächern.
23
+ - Als Umgebungsvariablen werden ausschließlich `WEBDE_IMAP_USER` und `WEBDE_IMAP_PASSWORD` gelesen. Zugangsdaten gehören in einen Vault, niemals in Chat, Kommandozeilenargumente oder Protokolle.
24
+
25
+ ## Funktionen
26
+
27
+ - `list-mailboxes`: Postfächer auflisten.
28
+ - `list-messages`: UIDs, Absender, Betreff und Datum auflisten, neueste UID zuerst.
29
+ - `read-message`: Eine Nachricht per Postfach und UID lesen; Text oder HTML und Anhangsnamen ausgeben.
30
+ - `mcp`: Dieselben drei Operationen als MCP-stdio-Server bereitstellen.
31
+
32
+ ## Lokal installieren und nutzen
33
+
34
+ Python 3.10 oder neuer wird benötigt.
35
+
36
+ ```sh
37
+ python -m pip install .
38
+ webde-readonly-imap list-mailboxes
39
+ webde-readonly-imap list-messages --mailbox INBOX --limit 20
40
+ webde-readonly-imap read-message --mailbox INBOX --uid 123
41
+ webde-readonly-imap mcp
42
+ # Für Nod: Aufruf ohne Unterbefehl startet ebenfalls MCP:
43
+ webde-readonly-imap
44
+ ```
45
+
46
+ Die beiden Zugangsdaten müssen vorher privat als `WEBDE_IMAP_USER` und `WEBDE_IMAP_PASSWORD` bereitgestellt werden. Die Ausgabe erfolgt als JSON. Ein Limit ist auf 1 bis 200 Nachrichten begrenzt.
47
+
48
+ ## Tests
49
+
50
+ Die Tests verwenden einen Scheinserver und benötigen weder Netz noch echte Zugangsdaten.
51
+
52
+ ```sh
53
+ PYTHONPATH=src python -m unittest discover -s tests -v
54
+ ```
55
+
56
+ Geprüft werden unter anderem schreibgeschützte Postfachauswahl, `BODY.PEEK`, Eingabevalidierung und das Fehlen verändernder IMAP-Methoden im Adapterquelltext.
57
+
58
+ ## Paket und Release
59
+
60
+ ```sh
61
+ python -m pip install build twine
62
+ python -m build
63
+ python -m twine check dist/*
64
+ ```
65
+
66
+ Die Dateien in `dist/` sind Wheel und Quellpaket. Für die Einbindung in Nod muss Version 1.0.0 unter dem Paketnamen `webde-readonly-imap` auf PyPI veröffentlicht oder ein signiertes HTTPS-Release mit veröffentlichter SHA-256-Prüfsumme bereitgestellt werden. Ein lokales `dist/`-Paket allein ist für Nods eigene Installation nicht ausreichend.
67
+
68
+ Veröffentlichung nach vorheriger inhaltlicher Prüfung mit einem privat hinterlegten PyPI-Token:
69
+
70
+ ```sh
71
+ python -m twine upload dist/*
72
+ ```
73
+
74
+ Nod-Vorschlag nach Veröffentlichung: CLI-Befehl `webde-readonly-imap` (ohne Argumente, startet MCP), Quelle PyPI `webde-readonly-imap`, Authentifizierung über Umgebung mit genau den beiden oben genannten Secret-Namen.
@@ -0,0 +1,8 @@
1
+ webde_readonly_imap/__init__.py,sha256=RvSDDktMtx1EyWKKjFRhQ7CJVxaiNbRd0LP8K3yxgG0,80
2
+ webde_readonly_imap/adapter.py,sha256=sMwafWlj-c7DLHC9s1H13O8utJgQD-XEi0YcjH8k2rw,7799
3
+ webde_readonly_imap/cli.py,sha256=comG5rWpym1_Y1Pk3KbefH_Ov66EbIpQSp4V9rVthwQ,4749
4
+ webde_readonly_imap-1.0.0.dist-info/METADATA,sha256=KrHNYJ6tkav-pBLEfWHgFoDwXEYqjAcem71V5KuG0n0,3172
5
+ webde_readonly_imap-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ webde_readonly_imap-1.0.0.dist-info/entry_points.txt,sha256=UZaU03xGODuqu-cPdueDWG3RSj5e89WeNJoZhpkKedc,69
7
+ webde_readonly_imap-1.0.0.dist-info/licenses/LICENSE,sha256=w9_ts7mEL15l3-znHcHRn7BbPz69PSuIRk1Auuhfweo,1094
8
+ webde_readonly_imap-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ webde-readonly-imap = webde_readonly_imap.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WEB.DE read-only adapter contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.