maildrop-cx-easy-wrapper 0.2.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,21 @@
1
+ from .aio import AsyncMailDropWeb
2
+ from .client import DEFAULT_BASE_URL, MailDropWeb
3
+ from .exceptions import (
4
+ AddressUnavailableError,
5
+ BlockedError,
6
+ ConnectionFailedError,
7
+ InvalidDomainError,
8
+ InvalidPrefixError,
9
+ MailDropWebError,
10
+ MessageNotFoundError,
11
+ )
12
+ from .models import Attachment, Inbox, Message, MessageSummary
13
+ from .otp import extract_otp
14
+
15
+ __all__ = [
16
+ "MailDropWeb", "AsyncMailDropWeb", "DEFAULT_BASE_URL",
17
+ "MailDropWebError", "BlockedError", "ConnectionFailedError", "AddressUnavailableError",
18
+ "MessageNotFoundError", "InvalidPrefixError", "InvalidDomainError",
19
+ "Attachment", "Inbox", "Message", "MessageSummary", "extract_otp",
20
+ ]
21
+ __version__ = "0.2.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,94 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from functools import partial
5
+ from pathlib import Path
6
+ from typing import AsyncIterator, Callable
7
+
8
+ from .client import MailDropWeb, clamp_interval
9
+ from .models import Inbox, Message, MessageSummary
10
+
11
+
12
+ class AsyncMailDropWeb:
13
+ def __init__(self, address: str | None = None, **options):
14
+ self._sync = MailDropWeb(address, **options)
15
+ self._lock = asyncio.Lock()
16
+
17
+ @property
18
+ def address(self) -> str | None:
19
+ return self._sync.address
20
+
21
+ async def _run(self, func, *args, **kwargs):
22
+ async with self._lock:
23
+ return await asyncio.to_thread(partial(func, *args, **kwargs))
24
+
25
+ async def suffixes(self, *, refresh: bool = False) -> list[str]:
26
+ return await self._run(self._sync.suffixes, refresh=refresh)
27
+
28
+ async def generate_prefix(self) -> str:
29
+ return await self._run(self._sync.generate_prefix)
30
+
31
+ async def new_address(self, prefix: str | None = None, suffix: str | None = None) -> str:
32
+ return await self._run(self._sync.new_address, prefix, suffix)
33
+
34
+ async def inbox(self, address: str | None = None, *, page: int = 1, limit: int = 20) -> Inbox:
35
+ return await self._run(self._sync.inbox, address, page=page, limit=limit)
36
+
37
+ async def messages(self, address: str | None = None, *, page: int = 1, limit: int = 20) -> list[MessageSummary]:
38
+ return (await self.inbox(address, page=page, limit=limit)).messages
39
+
40
+ async def get_message(self, message: MessageSummary | str | int, address: str | None = None) -> Message:
41
+ return await self._run(self._sync.get_message, message, address)
42
+
43
+ async def download_attachment(self, message: Message, index: int = 0,
44
+ path: str | Path | None = None) -> bytes | Path:
45
+ return await self._run(self._sync.download_attachment, message, index, path)
46
+
47
+ async def watch(
48
+ self,
49
+ address: str | None = None,
50
+ *,
51
+ interval: float = 10,
52
+ predicate: Callable[[MessageSummary], bool] | None = None,
53
+ ignore_existing: bool = True,
54
+ fetch_body: bool = True,
55
+ ) -> AsyncIterator[Message | MessageSummary]:
56
+ addr = self._sync._addr(address)
57
+ interval = clamp_interval(interval)
58
+ seen = {m.id for m in await self.messages(addr)} if ignore_existing else set()
59
+ while True:
60
+ for m in reversed(await self.messages(addr)):
61
+ if m.id in seen:
62
+ continue
63
+ seen.add(m.id)
64
+ if predicate is None or predicate(m):
65
+ yield await self.get_message(m, addr) if fetch_body else m
66
+ await asyncio.sleep(interval)
67
+
68
+ async def _first(self, gen, timeout, message, accept=None):
69
+ async def loop():
70
+ try:
71
+ async for msg in gen:
72
+ if accept is None or accept(msg):
73
+ return msg
74
+ finally:
75
+ await gen.aclose()
76
+ try:
77
+ return await asyncio.wait_for(loop(), timeout)
78
+ except asyncio.TimeoutError:
79
+ raise TimeoutError(message) from None
80
+
81
+ async def wait_for_message(self, address: str | None = None, *, timeout: float | None = 180,
82
+ **options) -> Message | MessageSummary:
83
+ gen = self.watch(address, **options)
84
+ return await self._first(gen, timeout, f"{timeout} 秒以内にメールが届きませんでした")
85
+
86
+ async def wait_for_otp(self, address: str | None = None, *, timeout: float | None = 180,
87
+ interval: float = 10, ignore_existing: bool = True) -> str:
88
+ gen = self.watch(address, interval=interval, ignore_existing=ignore_existing)
89
+ msg = await self._first(gen, timeout, f"{timeout} 秒以内に認証コードが届きませんでした",
90
+ accept=lambda m: m.otp)
91
+ return msg.otp
92
+
93
+ def __repr__(self) -> str:
94
+ return f"AsyncMailDropWeb(address={self.address!r})"
@@ -0,0 +1,169 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import asyncio
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from . import client as core
9
+ from .aio import AsyncMailDropWeb
10
+ from .exceptions import MailDropWebError
11
+
12
+
13
+ def interval_arg(value: str) -> float:
14
+ try:
15
+ sec = float(value)
16
+ except ValueError:
17
+ raise argparse.ArgumentTypeError(f"数値で指定してください: {value}") from None
18
+ if not core.MIN_POLL_INTERVAL <= sec <= core.MAX_POLL_INTERVAL:
19
+ raise argparse.ArgumentTypeError(
20
+ f"{core.MIN_POLL_INTERVAL:g}〜{core.MAX_POLL_INTERVAL:g} 秒の範囲で指定してください")
21
+ return sec
22
+
23
+
24
+ async def pick_domain(md: AsyncMailDropWeb, choice: str | None) -> str | None:
25
+ domains = await md.suffixes()
26
+ if choice is None and sys.stdin.isatty():
27
+ for i, d in enumerate(domains, 1):
28
+ print(f"{i}) {d}", file=sys.stderr)
29
+ choice = input("ドメイン [1]: ").strip() or None
30
+ if choice is None:
31
+ return None
32
+ if choice.isdigit() and 1 <= int(choice) <= len(domains):
33
+ return domains[int(choice) - 1]
34
+ return choice
35
+
36
+
37
+ async def make_address(md: AsyncMailDropWeb, args) -> str:
38
+ domain = await pick_domain(md, args.domain)
39
+ return await md.new_address(args.prefix, domain)
40
+
41
+
42
+ def show(msg) -> None:
43
+ print(f"\n{msg.address} {msg.date}")
44
+ print(f"From: {msg.sender}")
45
+ print(f"Subject: {msg.subject}")
46
+ if msg.otp:
47
+ print(f"Code: {msg.otp}")
48
+ print(msg.text[:500])
49
+
50
+
51
+ async def cmd_domains(md, args):
52
+ for i, d in enumerate(await md.suffixes(), 1):
53
+ print(f"{i}\t{d}")
54
+
55
+
56
+ async def cmd_new(md, args):
57
+ print(await make_address(md, args))
58
+
59
+
60
+ async def cmd_inbox(md, args):
61
+ for m in await md.messages(args.address, limit=args.limit):
62
+ code = f" [{m.otp}]" if m.otp else ""
63
+ print(f"{m.id}\t{m.date}\t{m.sender}\t{m.subject}{code}")
64
+
65
+
66
+ async def cmd_read(md, args):
67
+ msg = await md.get_message(args.id, args.address)
68
+ if args.html:
69
+ print(msg.html or "")
70
+ return
71
+ print(f"From: {msg.sender}\nSubject: {msg.subject}\nDate: {msg.date}")
72
+ if msg.otp:
73
+ print(f"Code: {msg.otp}")
74
+ for a in msg.attachments:
75
+ print(f"File: {a.index} {a.filename} {a.size or ''}")
76
+ print(f"\n{msg.text}")
77
+
78
+
79
+ async def cmd_save(md, args):
80
+ msg = await md.get_message(args.id, args.address)
81
+ indexes = [args.index] if args.index is not None else range(len(msg.attachments))
82
+ for i in indexes:
83
+ print(await md.download_attachment(msg, i, Path(args.out)))
84
+
85
+
86
+ async def cmd_watch(md, args):
87
+ addresses = args.address or [await make_address(md, args)]
88
+ for a in addresses:
89
+ print(f"監視中: {a}", file=sys.stderr)
90
+
91
+ async def follow(addr):
92
+ async for msg in md.watch(addr, interval=args.interval):
93
+ show(msg)
94
+
95
+ await asyncio.wait_for(asyncio.gather(*map(follow, addresses)), args.timeout or None)
96
+
97
+
98
+ async def cmd_otp(md, args):
99
+ addr = args.address
100
+ if addr is None:
101
+ addr = await make_address(md, args)
102
+ print(f"待機中: {addr}", file=sys.stderr)
103
+ print(await md.wait_for_otp(addr, timeout=args.timeout or None, interval=args.interval))
104
+
105
+
106
+ def build_parser() -> argparse.ArgumentParser:
107
+ p = argparse.ArgumentParser(prog="maildrop", description="maildrop.cx の使い捨てメールをコマンドラインから使う")
108
+ p.add_argument("--base-url", default=core.DEFAULT_BASE_URL, help=argparse.SUPPRESS)
109
+ sub = p.add_subparsers(dest="command", required=True)
110
+
111
+ def command(name, func, help):
112
+ sp = sub.add_parser(name, help=help)
113
+ sp.set_defaults(func=func)
114
+ return sp
115
+
116
+ def new_opts(sp):
117
+ sp.add_argument("-p", "--prefix", help="アドレスの @ より前(省略するとランダム)")
118
+ sp.add_argument("-d", "--domain", help="ドメイン名か domains の番号(省略すると一覧から選ぶ)")
119
+
120
+ def wait_opts(sp, timeout):
121
+ sp.add_argument("-i", "--interval", type=interval_arg, default=10, metavar="秒",
122
+ help="確認間隔(5〜30、既定 10)")
123
+ sp.add_argument("-t", "--timeout", type=float, default=timeout, metavar="秒",
124
+ help="待つ秒数(0 で無制限)")
125
+
126
+ command("domains", cmd_domains, "選べるドメインを表示する")
127
+
128
+ sp = command("new", cmd_new, "新しいアドレスを決める")
129
+ new_opts(sp)
130
+
131
+ sp = command("inbox", cmd_inbox, "受信箱を表示する")
132
+ sp.add_argument("address")
133
+ sp.add_argument("-n", "--limit", type=int, default=20)
134
+
135
+ sp = command("read", cmd_read, "メールを読む")
136
+ sp.add_argument("address")
137
+ sp.add_argument("id")
138
+ sp.add_argument("--html", action="store_true", help="本文を HTML のまま出す")
139
+
140
+ sp = command("save", cmd_save, "添付ファイルを保存する")
141
+ sp.add_argument("address")
142
+ sp.add_argument("id")
143
+ sp.add_argument("-i", "--index", type=int, help="添付の番号(省略すると全部)")
144
+ sp.add_argument("-o", "--out", default=".", help="保存先ディレクトリ")
145
+
146
+ sp = command("watch", cmd_watch, "新着メールを待ち続ける")
147
+ sp.add_argument("address", nargs="*", help="省略すると新しく作る。複数指定できる")
148
+ new_opts(sp)
149
+ wait_opts(sp, 0)
150
+
151
+ sp = command("otp", cmd_otp, "認証コードが届くまで待って表示する")
152
+ sp.add_argument("address", nargs="?", help="省略すると新しく作る")
153
+ new_opts(sp)
154
+ wait_opts(sp, 180)
155
+
156
+ return p
157
+
158
+
159
+ def main(argv: list[str] | None = None) -> int:
160
+ args = build_parser().parse_args(argv)
161
+ md = AsyncMailDropWeb(base_url=args.base_url)
162
+ try:
163
+ asyncio.run(args.func(md, args))
164
+ except KeyboardInterrupt:
165
+ return 130
166
+ except (MailDropWebError, TimeoutError, asyncio.TimeoutError, IndexError, ValueError) as e:
167
+ print(f"エラー: {e or '時間切れです'}", file=sys.stderr)
168
+ return 1
169
+ return 0
@@ -0,0 +1,230 @@
1
+ from __future__ import annotations
2
+
3
+ import http.cookiejar
4
+ import json
5
+ import re
6
+ import time
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from pathlib import Path
11
+ from typing import Any, Callable, Iterator
12
+
13
+ from .exceptions import (
14
+ AddressUnavailableError,
15
+ BlockedError,
16
+ ConnectionFailedError,
17
+ InvalidDomainError,
18
+ InvalidPrefixError,
19
+ MailDropWebError,
20
+ MessageNotFoundError,
21
+ )
22
+ from .models import Inbox, Message, MessageSummary
23
+
24
+ DEFAULT_BASE_URL = "https://maildrop.cx"
25
+ DEFAULT_USER_AGENT = "maildrop-cx-easy-wrapper-python/0.2 (unofficial; educational)"
26
+ PREFIX_RE = re.compile(r"^[a-zA-Z0-9_]{3,20}$")
27
+ MIN_POLL_INTERVAL = 5.0
28
+ MAX_POLL_INTERVAL = 30.0
29
+
30
+
31
+ def clamp_interval(value: float) -> float:
32
+ return min(max(value, MIN_POLL_INTERVAL), MAX_POLL_INTERVAL)
33
+
34
+
35
+ class MailDropWeb:
36
+ def __init__(
37
+ self,
38
+ address: str | None = None,
39
+ *,
40
+ base_url: str = DEFAULT_BASE_URL,
41
+ timeout: float = 15.0,
42
+ user_agent: str = DEFAULT_USER_AGENT,
43
+ min_request_interval: float = 1.0,
44
+ max_retries: int = 2,
45
+ ):
46
+ self.address = address
47
+ self.base_url = base_url.rstrip("/")
48
+ self.timeout = timeout
49
+ self.user_agent = user_agent
50
+ self.min_request_interval = min_request_interval
51
+ self.max_retries = max_retries
52
+ self._suffixes: list[str] | None = None
53
+ self._last_request = 0.0
54
+ self.cookies = http.cookiejar.CookieJar()
55
+ self._opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookies))
56
+
57
+ def _throttle(self) -> None:
58
+ wait = self._last_request + self.min_request_interval - time.monotonic()
59
+ if wait > 0:
60
+ time.sleep(wait)
61
+ self._last_request = time.monotonic()
62
+
63
+ def _get(self, path: str, params: dict[str, Any] | None = None, *, raw: bool = False):
64
+ url = self.base_url + path
65
+ if params:
66
+ url += "?" + urllib.parse.urlencode(params)
67
+ headers = {
68
+ "User-Agent": self.user_agent,
69
+ "Accept": "*/*" if raw else "application/json, text/javascript, */*; q=0.01",
70
+ "X-Requested-With": "XMLHttpRequest",
71
+ "Referer": self.base_url + "/app",
72
+ }
73
+ attempt = 0
74
+ while True:
75
+ self._throttle()
76
+ req = urllib.request.Request(url, headers=headers)
77
+ try:
78
+ with self._opener.open(req, timeout=self.timeout) as resp:
79
+ body = resp.read()
80
+ ctype = resp.headers.get("Content-Type", "")
81
+ break
82
+ except urllib.error.HTTPError as e:
83
+ if 500 <= e.code < 600 and attempt < self.max_retries:
84
+ attempt += 1
85
+ time.sleep(2 ** attempt)
86
+ continue
87
+ snippet = e.read()[:200].decode("utf-8", "ignore")
88
+ cls = BlockedError if e.code in (403, 429, 503) and "<html" in snippet.lower() else MailDropWebError
89
+ raise cls(f"HTTP {e.code}: {path}", status=e.code, url=url) from None
90
+ except (urllib.error.URLError, TimeoutError) as e:
91
+ if attempt < self.max_retries:
92
+ attempt += 1
93
+ time.sleep(2 ** attempt)
94
+ continue
95
+ raise ConnectionFailedError(f"接続に失敗しました: {e}", url=url) from e
96
+
97
+ if raw:
98
+ return body, ctype
99
+ try:
100
+ return json.loads(body)
101
+ except ValueError:
102
+ head = body[:200].decode("utf-8", "ignore")
103
+ raise BlockedError(
104
+ f"JSON ではない応答が返りました(Bot 対策ページの可能性): {head!r}", url=url) from None
105
+
106
+ def suffixes(self, *, refresh: bool = False) -> list[str]:
107
+ if self._suffixes is None or refresh:
108
+ data = self._get("/api/suffixes.php")
109
+ if not isinstance(data, list):
110
+ raise MailDropWebError(f"想定外の応答: {data!r}")
111
+ self._suffixes = [str(s) for s in data]
112
+ return list(self._suffixes)
113
+
114
+ def generate_prefix(self) -> str:
115
+ data = self._get("/api/generate_prefix.php")
116
+ prefix = data.get("prefix") if isinstance(data, dict) else None
117
+ if not prefix:
118
+ raise MailDropWebError(f"prefix を取得できませんでした: {data!r}")
119
+ return prefix
120
+
121
+ def new_address(self, prefix: str | None = None, suffix: str | None = None) -> str:
122
+ if prefix is not None and not PREFIX_RE.match(prefix):
123
+ raise InvalidPrefixError(f"prefix が不正です: {prefix!r}(3〜20 文字、英数字と _)")
124
+ domains = self.suffixes()
125
+ if suffix is None:
126
+ if not domains:
127
+ raise MailDropWebError("選べるドメインがありません")
128
+ suffix = domains[0]
129
+ suffix = suffix.lstrip("@")
130
+ if suffix not in domains:
131
+ raise InvalidDomainError(f"ドメイン {suffix!r} は選べません。候補: {domains}")
132
+ self.address = f"{prefix or self.generate_prefix()}@{suffix}"
133
+ return self.address
134
+
135
+ def _addr(self, address: str | None) -> str:
136
+ addr = address or self.address
137
+ if not addr:
138
+ raise MailDropWebError("アドレスが未設定です。new_address() を先に呼んでください")
139
+ return addr
140
+
141
+ def inbox(self, address: str | None = None, *, page: int = 1, limit: int = 20) -> Inbox:
142
+ addr = self._addr(address)
143
+ data = self._get("/api/emails.php", {"addr": addr, "page": page, "limit": limit})
144
+ if isinstance(data, dict) and data.get("reload"):
145
+ raise AddressUnavailableError(f"{addr} は使えません(別のアドレスを作ってください)")
146
+ emails = data.get("emails") if isinstance(data, dict) else None
147
+ if not isinstance(emails, list):
148
+ raise MailDropWebError(f"想定外の応答: {str(data)[:200]}")
149
+ return Inbox(address=addr, page=page, limit=limit, total=int(data.get("total", len(emails))),
150
+ messages=[MessageSummary.from_api(e) for e in emails])
151
+
152
+ def messages(self, address: str | None = None, *, page: int = 1, limit: int = 20) -> list[MessageSummary]:
153
+ return self.inbox(address, page=page, limit=limit).messages
154
+
155
+ def iter_messages(self, address: str | None = None, *, limit: int = 20) -> Iterator[MessageSummary]:
156
+ page = 1
157
+ while True:
158
+ box = self.inbox(address, page=page, limit=limit)
159
+ yield from box.messages
160
+ if not box.messages or page >= box.pages:
161
+ return
162
+ page += 1
163
+
164
+ def get_message(self, message: MessageSummary | str | int, address: str | None = None) -> Message:
165
+ addr = self._addr(address)
166
+ mid = message.id if isinstance(message, MessageSummary) else str(message)
167
+ data = self._get("/api/email_content.php", {"id": mid, "addr": addr})
168
+ if not isinstance(data, dict) or data.get("id") is None:
169
+ raise MessageNotFoundError(f"id={mid} のメールが見つかりません({addr})")
170
+ return Message.from_api(data, addr)
171
+
172
+ def download_attachment(self, message: Message, index: int = 0,
173
+ path: str | Path | None = None) -> bytes | Path:
174
+ if not 0 <= index < len(message.attachments):
175
+ raise IndexError(f"添付ファイルは {len(message.attachments)} 個です")
176
+ body, _ = self._get("/api/download.php",
177
+ {"id": message.id, "addr": message.address, "i": index}, raw=True)
178
+ if path is None:
179
+ return body
180
+ p = Path(path)
181
+ if p.is_dir():
182
+ p = p / Path(message.attachments[index].filename).name
183
+ p.write_bytes(body)
184
+ return p
185
+
186
+ def wait_for_message(
187
+ self,
188
+ address: str | None = None,
189
+ *,
190
+ timeout: float = 180,
191
+ interval: float = 10,
192
+ predicate: Callable[[MessageSummary], bool] | None = None,
193
+ ignore_existing: bool = True,
194
+ fetch_body: bool = True,
195
+ ) -> Message | MessageSummary:
196
+ addr = self._addr(address)
197
+ interval = clamp_interval(interval)
198
+ seen = {m.id for m in self.messages(addr)} if ignore_existing else set()
199
+ deadline = time.monotonic() + timeout
200
+ while True:
201
+ for m in self.messages(addr):
202
+ if m.id in seen:
203
+ continue
204
+ seen.add(m.id)
205
+ if predicate is None or predicate(m):
206
+ return self.get_message(m, addr) if fetch_body else m
207
+ remaining = deadline - time.monotonic()
208
+ if remaining <= 0:
209
+ raise TimeoutError(f"{timeout} 秒以内に {addr} へメールが届きませんでした")
210
+ time.sleep(min(interval, remaining))
211
+
212
+ def wait_for_otp(self, address: str | None = None, *, timeout: float = 180,
213
+ interval: float = 10, ignore_existing: bool = True) -> str:
214
+ addr = self._addr(address)
215
+ deadline = time.monotonic() + timeout
216
+ seen = {m.id for m in self.messages(addr)} if ignore_existing else set()
217
+ while True:
218
+ remaining = deadline - time.monotonic()
219
+ try:
220
+ msg = self.wait_for_message(addr, timeout=max(remaining, 0), interval=interval,
221
+ ignore_existing=False,
222
+ predicate=lambda m: m.id not in seen)
223
+ except TimeoutError:
224
+ raise TimeoutError(f"{timeout} 秒以内に認証コードが届きませんでした") from None
225
+ seen.add(msg.id)
226
+ if msg.otp:
227
+ return msg.otp
228
+
229
+ def __repr__(self) -> str:
230
+ return f"MailDropWeb(address={self.address!r})"
@@ -0,0 +1,32 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class MailDropWebError(Exception):
5
+ def __init__(self, message: str, *, status: int | None = None, url: str | None = None):
6
+ super().__init__(message)
7
+ self.status = status
8
+ self.url = url
9
+
10
+
11
+ class BlockedError(MailDropWebError):
12
+ pass
13
+
14
+
15
+ class ConnectionFailedError(MailDropWebError):
16
+ pass
17
+
18
+
19
+ class AddressUnavailableError(MailDropWebError):
20
+ pass
21
+
22
+
23
+ class MessageNotFoundError(MailDropWebError):
24
+ pass
25
+
26
+
27
+ class InvalidPrefixError(MailDropWebError, ValueError):
28
+ pass
29
+
30
+
31
+ class InvalidDomainError(MailDropWebError, ValueError):
32
+ pass
@@ -0,0 +1,90 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass, field
5
+ from typing import Any
6
+
7
+ from .otp import extract_otp, html_to_text
8
+
9
+
10
+ @dataclass
11
+ class MessageSummary:
12
+ id: str
13
+ subject: str | None
14
+ sender: str | None
15
+ date: str | None
16
+ description: str | None = None
17
+ is_read: bool = False
18
+ raw: dict = field(default_factory=dict, repr=False)
19
+
20
+ @property
21
+ def otp(self) -> str | None:
22
+ return extract_otp(f"{self.subject or ''} {self.description or ''}")
23
+
24
+ @classmethod
25
+ def from_api(cls, d: dict) -> "MessageSummary":
26
+ return cls(id=str(d.get("id")), subject=d.get("subject"), sender=d.get("from_addr"),
27
+ date=d.get("date"), description=d.get("description"),
28
+ is_read=bool(d.get("isRead")), raw=d)
29
+
30
+
31
+ @dataclass
32
+ class Inbox:
33
+ address: str
34
+ page: int
35
+ limit: int
36
+ total: int
37
+ messages: list[MessageSummary]
38
+
39
+ @property
40
+ def pages(self) -> int:
41
+ return max(1, -(-self.total // self.limit))
42
+
43
+ def __iter__(self):
44
+ return iter(self.messages)
45
+
46
+ def __len__(self) -> int:
47
+ return len(self.messages)
48
+
49
+
50
+ @dataclass
51
+ class Attachment:
52
+ index: int
53
+ filename: str
54
+ size: int | None = None
55
+ raw: dict = field(default_factory=dict, repr=False)
56
+
57
+
58
+ @dataclass
59
+ class Message:
60
+ id: str
61
+ address: str
62
+ subject: str | None
63
+ sender: str | None
64
+ date: str | None
65
+ html: str | None
66
+ attachments: list[Attachment] = field(default_factory=list)
67
+ raw: dict = field(default_factory=dict, repr=False)
68
+
69
+ @property
70
+ def text(self) -> str:
71
+ return html_to_text(self.html)
72
+
73
+ @property
74
+ def otp(self) -> str | None:
75
+ return extract_otp(f"{self.subject or ''} {self.text}")
76
+
77
+ @classmethod
78
+ def from_api(cls, d: dict, address: str) -> "Message":
79
+ atts: list[Any] = []
80
+ try:
81
+ atts = json.loads(d["attachment"]) if d.get("attachment") else []
82
+ except (TypeError, ValueError):
83
+ pass
84
+ return cls(
85
+ id=str(d.get("id")), address=address, subject=d.get("subject"),
86
+ sender=d.get("from_addr"), date=d.get("date"), html=d.get("content"),
87
+ attachments=[Attachment(index=i, filename=str(a.get("filename", "")), size=a.get("size"), raw=a)
88
+ for i, a in enumerate(atts if isinstance(atts, list) else [])],
89
+ raw=d,
90
+ )
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import re
5
+
6
+ _KEYWORD = re.compile(
7
+ r"(code|otp|verif|passcode|\bpin\b|one[- ]time|一次性|验证|驗證|認証|認證|コード|c[oó]digo)", re.I)
8
+ _DIGITS = re.compile(r"(^|[^\d.])(\d{4,8})([^\d.]|$)")
9
+ _TAG = re.compile(r"<(script|style)[^>]*>.*?</\1>|<[^>]+>", re.S | re.I)
10
+
11
+
12
+ def html_to_text(content: str | None) -> str:
13
+ if not content:
14
+ return ""
15
+ return re.sub(r"\s+", " ", html.unescape(_TAG.sub(" ", content))).strip()
16
+
17
+
18
+ def extract_otp(text: str | None) -> str | None:
19
+ if not text:
20
+ return None
21
+ s = re.sub(r"\s+", " ", str(text))
22
+ km = _KEYWORD.search(s)
23
+ if not km:
24
+ return None
25
+ near = s[max(0, km.start() - 60): km.start() + 90]
26
+ m = _DIGITS.search(near) or _DIGITS.search(s)
27
+ return m.group(2) if m else None
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: maildrop-cx-easy-wrapper
3
+ Version: 0.2.0
4
+ Summary: maildrop.cx の非公式クライアント(CLI・同期・非同期)
5
+ Author: adhad
6
+ License-Expression: MIT
7
+ Keywords: maildrop,temporary-email,otp,cli,asyncio
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Environment :: Console
10
+ Classifier: Topic :: Communications :: Email
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # maildrop_cx_easy_wrapper
17
+
18
+ [maildrop.cx](https://maildrop.cx/app) の非公式クライアントです。Web 画面が使っている API を直接呼ぶので、ブラウザもログインも API キーも要りません。標準ライブラリだけで動きます(Python 3.9 以上)。maildrop.cx とは無関係の非公式ツールです。
19
+
20
+ ## CLI
21
+
22
+ ```bash
23
+ python -m maildrop_cx_easy_wrapper domains
24
+ python -m maildrop_cx_easy_wrapper new -p mybox -d 2
25
+ python -m maildrop_cx_easy_wrapper watch
26
+ python -m maildrop_cx_easy_wrapper otp -t 120
27
+ python -m maildrop_cx_easy_wrapper inbox mybox@206969.xyz
28
+ python -m maildrop_cx_easy_wrapper read mybox@206969.xyz 123
29
+ python -m maildrop_cx_easy_wrapper save mybox@206969.xyz 123 -o downloads
30
+ ```
31
+
32
+ `pip install .` すると `maildrop` コマンドでも呼べます。
33
+
34
+ ドメインは起動のたびにサーバーから取得します。`-d` には名前か `domains` の番号を渡せます。省略して端末から実行すると一覧が出るので、番号で選べます。
35
+
36
+ `watch` と `otp` の更新間隔は `-i` で 5〜30 秒(既定 10 秒)。`watch` はアドレスを複数並べると同時に監視します。
37
+
38
+ ## ライブラリ
39
+
40
+ ```python
41
+ import asyncio
42
+ from maildrop_cx_easy_wrapper import AsyncMailDropWeb
43
+
44
+ async def main():
45
+ md = AsyncMailDropWeb()
46
+ domains = await md.suffixes()
47
+ addr = await md.new_address(suffix=domains[0])
48
+ code = await md.wait_for_otp(addr, timeout=180, interval=10)
49
+
50
+ asyncio.run(main())
51
+ ```
52
+
53
+ 同期版は `MailDropWeb`で、メソッドは同じ名前です。`watch()` は新着を古い順に返す非同期ジェネレーターです。
54
+
55
+ ## 仕組み
56
+
57
+ | エンドポイント | 応答 |
58
+ |---|---|
59
+ | `GET /api/suffixes.php` | `["206969.xyz", ...]` |
60
+ | `GET /api/generate_prefix.php` | `{"prefix": "..."}` |
61
+ | `GET /api/emails.php?addr=&page=&limit=` | `{"emails": [...], "total": n}` または `{"reload": true}` |
62
+ | `GET /api/email_content.php?id=&addr=` | `{id, subject, from_addr, date, content, attachment}` |
63
+ | `GET /api/download.php?id=&addr=&i=` | 添付ファイル本体 |
64
+
65
+ `{"reload": true}` のアドレスは使えず、`AddressUnavailableError` になります。
66
+
67
+ ## テスト
68
+
69
+ ```bash
70
+ python -m unittest discover -s tests
71
+ ```
72
+
73
+ ## 注意
74
+
75
+ - 非公開 API なので予告なく変わることがあります。
76
+ - リクエストは 1 秒以上、確認は 5 秒以上空けます。非同期版も 1 本ずつ順番に送ります。
77
+ - `BlockedError` は Bot 対策などで JSON が返らなかったときにでてくるやつです。
78
+ - 利用規約を守り、学習目的で使ってください。
79
+
80
+ ## ライセンス
81
+
82
+ MIT License
@@ -0,0 +1,13 @@
1
+ maildrop_cx_easy_wrapper/__init__.py,sha256=676ozFv3c3qPLfT_uBUWIx-0RUT02zsXclS-xEIi8zE,705
2
+ maildrop_cx_easy_wrapper/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ maildrop_cx_easy_wrapper/aio.py,sha256=T8YvXEZIzpM5FXULd7hFzkX0d9ONkozzCT-lR5bj5CE,4027
4
+ maildrop_cx_easy_wrapper/cli.py,sha256=-DMvimu6GFA5qG8bY8YDeMy9QKQjdsZV7fsqy7kpUaQ,5978
5
+ maildrop_cx_easy_wrapper/client.py,sha256=s3skEusiWSqvqZ9QfwscClTHXkvUeO1oFuZ3WENL9HI,9862
6
+ maildrop_cx_easy_wrapper/exceptions.py,sha256=kSgL7FudWqb-5uGczFzM8ix5ifBGQbUCfpb2PG1lMlA,608
7
+ maildrop_cx_easy_wrapper/models.py,sha256=UALDMghDIOvMHjpvNc4ey2wkx3hvWCHd2QNl5BfUWGk,2414
8
+ maildrop_cx_easy_wrapper/otp.py,sha256=_Eg8fw3qTv8cWbaf16_XyZ63KN421PAEyuA9Adm9bXA,825
9
+ maildrop_cx_easy_wrapper-0.2.0.dist-info/licenses/LICENSE,sha256=1V0BZ5sRdHi0TRs2R69oL6coS8ekil1f7Ex55rbYTcY,1062
10
+ maildrop_cx_easy_wrapper-0.2.0.dist-info/METADATA,sha256=fAgSxk4tGsXaXDRhOoYqqc7ZkEZtk18L_3FRDQzt57w,3145
11
+ maildrop_cx_easy_wrapper-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ maildrop_cx_easy_wrapper-0.2.0.dist-info/top_level.txt,sha256=cNEym3wbxvFUpuymnU_vTzh3cJLlz5yIp03y0HwBlfw,25
13
+ maildrop_cx_easy_wrapper-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 adhad
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.
@@ -0,0 +1 @@
1
+ maildrop_cx_easy_wrapper