qubrixa-mail 0.1.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,48 @@
1
+ """qubrixa-mail - Python client for the Qubrixa Mail disposable-inbox API."""
2
+
3
+ from ._version import __version__
4
+ from .client import QubrixaMail
5
+ from .exceptions import (
6
+ AbuseGuardError,
7
+ APIConnectionError,
8
+ APIError,
9
+ AuthenticationError,
10
+ ConfigurationError,
11
+ ForbiddenError,
12
+ NotFoundError,
13
+ OTPTimeoutError,
14
+ QubrixaError,
15
+ RateLimitError,
16
+ ServiceUnavailableError,
17
+ )
18
+ from .models import Inbox, Message, MessageSummary, OTPResult, Quota
19
+
20
+ __all__ = [
21
+ "__version__",
22
+ "QubrixaMail",
23
+ "AsyncQubrixaMail",
24
+ "Inbox",
25
+ "Message",
26
+ "MessageSummary",
27
+ "OTPResult",
28
+ "Quota",
29
+ "QubrixaError",
30
+ "ConfigurationError",
31
+ "APIConnectionError",
32
+ "APIError",
33
+ "AuthenticationError",
34
+ "ForbiddenError",
35
+ "NotFoundError",
36
+ "RateLimitError",
37
+ "ServiceUnavailableError",
38
+ "OTPTimeoutError",
39
+ "AbuseGuardError",
40
+ ]
41
+
42
+
43
+ def __getattr__(name): # lazy import so httpx stays an optional dependency
44
+ if name == "AsyncQubrixaMail":
45
+ from .async_client import AsyncQubrixaMail
46
+
47
+ return AsyncQubrixaMail
48
+ raise AttributeError("module %r has no attribute %r" % (__name__, name))
qubrixa_mail/_base.py ADDED
@@ -0,0 +1,194 @@
1
+ """Logic shared by the sync and async clients (no network I/O in here)."""
2
+
3
+ import json as _json
4
+ import os
5
+ import random
6
+ from typing import Any, Dict, Mapping, Optional, Tuple, Union
7
+ from urllib.parse import quote, urlparse
8
+
9
+ from ._ratelimit import SlidingWindowLimiter, StrikeGuard
10
+ from ._version import __version__
11
+ from .exceptions import (
12
+ APIError,
13
+ AuthenticationError,
14
+ ConfigurationError,
15
+ ForbiddenError,
16
+ NotFoundError,
17
+ RateLimitError,
18
+ ServiceUnavailableError,
19
+ )
20
+ from .models import Inbox
21
+
22
+ ENV_BASE_URL = "QUBRIXA_BASE_URL"
23
+ ENV_API_KEY = "QUBRIXA_API_KEY"
24
+ DEFAULT_API_PATH = "/api/v1"
25
+
26
+ RETRY_STATUSES = frozenset({502, 503, 504})
27
+ IDEMPOTENT_METHODS = frozenset({"GET", "DELETE"})
28
+
29
+ InboxRef = Union[Inbox, str]
30
+
31
+
32
+ def normalize_base_url(base_url: str) -> str:
33
+ """Validate the URL; add ``/api/v1`` when only a host was given."""
34
+ base_url = base_url.strip()
35
+ parsed = urlparse(base_url)
36
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
37
+ raise ConfigurationError(
38
+ "base_url must start with http:// or https:// (got %r)." % base_url
39
+ )
40
+ if parsed.path in ("", "/"):
41
+ base_url = base_url.rstrip("/") + DEFAULT_API_PATH
42
+ return base_url.rstrip("/")
43
+
44
+
45
+ def _extract_message(payload: Any, fallback: str) -> str:
46
+ if isinstance(payload, dict):
47
+ for key in ("detail", "error", "message"):
48
+ value = payload.get(key)
49
+ if isinstance(value, str) and value:
50
+ return value
51
+ if isinstance(value, dict):
52
+ inner = value.get("message")
53
+ if isinstance(inner, str) and inner:
54
+ return inner
55
+ return fallback
56
+
57
+
58
+ def _retry_after(headers: Mapping[str, str]) -> Optional[float]:
59
+ for key, value in headers.items():
60
+ if key.lower() == "retry-after":
61
+ try:
62
+ return max(float(value), 0.0)
63
+ except (TypeError, ValueError):
64
+ return None
65
+ return None
66
+
67
+
68
+ def build_api_error(status: int, text: str, headers: Mapping[str, str]) -> APIError:
69
+ try:
70
+ payload = _json.loads(text) if text else None
71
+ except ValueError:
72
+ payload = None
73
+ message = _extract_message(payload, (text or "").strip()[:300] or "Request failed")
74
+ kwargs = dict(status_code=status, payload=payload, headers=headers)
75
+ if status == 401:
76
+ return AuthenticationError(message, **kwargs)
77
+ if status == 403:
78
+ return ForbiddenError(message, **kwargs)
79
+ if status == 404:
80
+ return NotFoundError(message, **kwargs)
81
+ if status == 429:
82
+ return RateLimitError(message, retry_after=_retry_after(headers), **kwargs)
83
+ if status == 503:
84
+ return ServiceUnavailableError(message, **kwargs)
85
+ return APIError(message, **kwargs)
86
+
87
+
88
+ def decode_body(text: str) -> Any:
89
+ """Decode a successful response body (empty body -> ``None``)."""
90
+ if not text or not text.strip():
91
+ return None
92
+ try:
93
+ return _json.loads(text)
94
+ except ValueError:
95
+ raise APIError("Server returned a non-JSON response: %s" % text[:200], 200)
96
+
97
+
98
+ class _BaseClient:
99
+ """Configuration, URL building and retry policy."""
100
+
101
+ def __init__(
102
+ self,
103
+ base_url: Optional[str] = None,
104
+ api_key: Optional[str] = None,
105
+ *,
106
+ timeout: float = 30.0,
107
+ max_retries: int = 2,
108
+ rate_limit: bool = True,
109
+ general_limit: int = 270,
110
+ create_limit: int = 9,
111
+ user_agent: Optional[str] = None,
112
+ ) -> None:
113
+ base_url = base_url or os.environ.get(ENV_BASE_URL)
114
+ api_key = api_key or os.environ.get(ENV_API_KEY)
115
+ if not base_url:
116
+ raise ConfigurationError(
117
+ "base_url is required (pass base_url=... or set %s)." % ENV_BASE_URL
118
+ )
119
+ if not api_key:
120
+ raise ConfigurationError(
121
+ "api_key is required (pass api_key=... or set %s)." % ENV_API_KEY
122
+ )
123
+ self.base_url = normalize_base_url(base_url)
124
+ self._api_key = api_key.strip()
125
+ self.timeout = timeout
126
+ self.max_retries = max(int(max_retries), 0)
127
+ self._headers = {
128
+ "X-API-Key": self._api_key,
129
+ "Accept": "application/json",
130
+ "User-Agent": user_agent or "qubrixa-mail-python/%s" % __version__,
131
+ }
132
+ self._general_limiter = SlidingWindowLimiter(general_limit) if rate_limit else None
133
+ self._create_limiter = SlidingWindowLimiter(create_limit) if rate_limit else None
134
+ self._guard = StrikeGuard()
135
+
136
+ def __repr__(self) -> str:
137
+ return "%s(base_url=%r, api_key='%s...')" % (
138
+ type(self).__name__,
139
+ self.base_url,
140
+ self._api_key[:8],
141
+ )
142
+
143
+ # -- helpers ------------------------------------------------------------
144
+ def _url(self, path: str) -> str:
145
+ return self.base_url + path
146
+
147
+ def _timeouts(self, read: Optional[float] = None) -> Tuple[float, float]:
148
+ read = self.timeout if read is None else read
149
+ return (min(10.0, read), read)
150
+
151
+ @staticmethod
152
+ def _inbox_id(inbox: InboxRef) -> str:
153
+ value = inbox.id if isinstance(inbox, Inbox) else str(inbox)
154
+ if not value:
155
+ raise ValueError("inbox id must not be empty")
156
+ return quote(value, safe="@")
157
+
158
+ @staticmethod
159
+ def _message_id(message_id: Any) -> str:
160
+ value = getattr(message_id, "id", message_id)
161
+ return quote(str(value), safe="")
162
+
163
+ @staticmethod
164
+ def _create_body(
165
+ expires_in_seconds: Optional[int],
166
+ local_part: Optional[str],
167
+ webhook_url: Optional[str],
168
+ extra: Dict[str, Any],
169
+ ) -> Dict[str, Any]:
170
+ body = {} # type: Dict[str, Any]
171
+ if expires_in_seconds is not None:
172
+ body["expires_in_seconds"] = int(expires_in_seconds)
173
+ if local_part is not None:
174
+ body["local_part"] = local_part
175
+ if webhook_url is not None:
176
+ body["webhook_url"] = webhook_url
177
+ body.update(extra)
178
+ return body
179
+
180
+ @staticmethod
181
+ def _check_wait(timeout: float) -> float:
182
+ if timeout <= 0:
183
+ raise ValueError("timeout must be > 0")
184
+ return float(timeout)
185
+
186
+ def _can_retry(self, method: str, attempt: int, retryable: bool) -> bool:
187
+ return retryable and method in IDEMPOTENT_METHODS and attempt < self.max_retries
188
+
189
+ @staticmethod
190
+ def _backoff(attempt: int, headers: Optional[Mapping[str, str]] = None) -> float:
191
+ hinted = _retry_after(headers) if headers else None
192
+ if hinted is not None:
193
+ return min(hinted, 30.0)
194
+ return min(0.5 * (2 ** attempt), 8.0) + random.uniform(0, 0.25)
@@ -0,0 +1,99 @@
1
+ """Client-side protection against the server's rate limits and strike bans."""
2
+
3
+ import asyncio
4
+ import threading
5
+ import time
6
+ from collections import deque
7
+ from typing import Callable, Deque
8
+
9
+ from .exceptions import AbuseGuardError
10
+
11
+
12
+ class SlidingWindowLimiter:
13
+ """Thread-safe sliding-window limiter (``max_calls`` per ``period`` seconds)."""
14
+
15
+ def __init__(
16
+ self,
17
+ max_calls: int,
18
+ period: float = 60.0,
19
+ clock: Callable[[], float] = time.monotonic,
20
+ ) -> None:
21
+ if max_calls < 1:
22
+ raise ValueError("max_calls must be >= 1")
23
+ self.max_calls = max_calls
24
+ self.period = period
25
+ self._clock = clock
26
+ self._calls = deque() # type: Deque[float]
27
+ self._lock = threading.Lock()
28
+
29
+ def try_acquire(self) -> float:
30
+ """Reserve a slot. Returns 0.0 on success, otherwise seconds to wait."""
31
+ with self._lock:
32
+ now = self._clock()
33
+ while self._calls and now - self._calls[0] >= self.period:
34
+ self._calls.popleft()
35
+ if len(self._calls) < self.max_calls:
36
+ self._calls.append(now)
37
+ return 0.0
38
+ return max(self.period - (now - self._calls[0]), 0.001)
39
+
40
+ def acquire(self) -> None:
41
+ while True:
42
+ wait = self.try_acquire()
43
+ if wait <= 0:
44
+ return
45
+ time.sleep(wait)
46
+
47
+ async def acquire_async(self) -> None:
48
+ while True:
49
+ wait = self.try_acquire()
50
+ if wait <= 0:
51
+ return
52
+ await asyncio.sleep(wait)
53
+
54
+
55
+ class StrikeGuard:
56
+ """Stops sending requests after several consecutive HTTP 429 responses.
57
+
58
+ The server bans a key after 5 consecutive violations inside 5 minutes; the
59
+ default here is to refuse locally after 3.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ max_strikes: int = 3,
65
+ window: float = 300.0,
66
+ clock: Callable[[], float] = time.monotonic,
67
+ ) -> None:
68
+ self.max_strikes = max_strikes
69
+ self.window = window
70
+ self._clock = clock
71
+ self._strikes = deque() # type: Deque[float]
72
+ self._lock = threading.Lock()
73
+
74
+ def _prune(self, now: float) -> None:
75
+ while self._strikes and now - self._strikes[0] >= self.window:
76
+ self._strikes.popleft()
77
+
78
+ def record_rate_limit(self) -> None:
79
+ with self._lock:
80
+ now = self._clock()
81
+ self._prune(now)
82
+ self._strikes.append(now)
83
+
84
+ def record_success(self) -> None:
85
+ with self._lock:
86
+ self._strikes.clear()
87
+
88
+ def check(self) -> None:
89
+ with self._lock:
90
+ now = self._clock()
91
+ self._prune(now)
92
+ if len(self._strikes) >= self.max_strikes:
93
+ retry_after = self.window - (now - self._strikes[0])
94
+ raise AbuseGuardError(
95
+ "%d consecutive rate-limit responses - pausing requests to avoid an "
96
+ "automatic key/IP suspension. Retry in %.0f seconds."
97
+ % (len(self._strikes), retry_after),
98
+ retry_after=retry_after,
99
+ )
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,216 @@
1
+ """Asynchronous client (built on ``httpx``; install with ``pip install qubrixa-mail[async]``)."""
2
+
3
+ import asyncio
4
+ import time
5
+ from contextlib import asynccontextmanager
6
+ from typing import Any, AsyncIterator, Awaitable, Callable, Dict, List, Optional, Union
7
+
8
+ try:
9
+ import httpx
10
+ except ImportError as exc: # pragma: no cover
11
+ raise ImportError(
12
+ "AsyncQubrixaMail needs httpx. Install it with: pip install 'qubrixa-mail[async]'"
13
+ ) from exc
14
+
15
+ from ._base import InboxRef, _BaseClient, build_api_error, decode_body
16
+ from .exceptions import APIConnectionError, APIError, OTPTimeoutError, RateLimitError
17
+ from .models import (
18
+ Inbox,
19
+ Message,
20
+ MessageSummary,
21
+ OTPResult,
22
+ Quota,
23
+ extract_list,
24
+ )
25
+
26
+
27
+ class AsyncQubrixaMail(_BaseClient):
28
+ """Async twin of :class:`qubrixa_mail.QubrixaMail`.
29
+
30
+ >>> async with AsyncQubrixaMail(base_url="...", api_key="sk_live_...") as mail:
31
+ ... inbox = await mail.create_inbox()
32
+ ... otp = await mail.wait_for_otp(inbox, timeout=30)
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ base_url: Optional[str] = None,
38
+ api_key: Optional[str] = None,
39
+ *,
40
+ timeout: float = 30.0,
41
+ max_retries: int = 2,
42
+ rate_limit: bool = True,
43
+ general_limit: int = 270,
44
+ create_limit: int = 9,
45
+ user_agent: Optional[str] = None,
46
+ client: Optional["httpx.AsyncClient"] = None,
47
+ ) -> None:
48
+ super().__init__(
49
+ base_url,
50
+ api_key,
51
+ timeout=timeout,
52
+ max_retries=max_retries,
53
+ rate_limit=rate_limit,
54
+ general_limit=general_limit,
55
+ create_limit=create_limit,
56
+ user_agent=user_agent,
57
+ )
58
+ self._owns_client = client is None
59
+ self._client = client or httpx.AsyncClient(headers=self._headers)
60
+ if client is not None:
61
+ self._client.headers.update(self._headers)
62
+
63
+ # -- lifecycle ----------------------------------------------------------
64
+ async def aclose(self) -> None:
65
+ if self._owns_client:
66
+ await self._client.aclose()
67
+
68
+ async def __aenter__(self) -> "AsyncQubrixaMail":
69
+ return self
70
+
71
+ async def __aexit__(self, *exc_info: Any) -> None:
72
+ await self.aclose()
73
+
74
+ # -- transport ----------------------------------------------------------
75
+ async def _request(
76
+ self,
77
+ method: str,
78
+ path: str,
79
+ *,
80
+ params: Optional[Dict[str, Any]] = None,
81
+ json: Optional[Dict[str, Any]] = None,
82
+ creating: bool = False,
83
+ read_timeout: Optional[float] = None,
84
+ retryable: bool = True,
85
+ ) -> Any:
86
+ connect, read = self._timeouts(read_timeout)
87
+ timeout = httpx.Timeout(read, connect=connect)
88
+ attempt = 0
89
+ while True:
90
+ self._guard.check()
91
+ if self._general_limiter is not None:
92
+ await self._general_limiter.acquire_async()
93
+ if creating and self._create_limiter is not None:
94
+ await self._create_limiter.acquire_async()
95
+ try:
96
+ resp = await self._client.request(
97
+ method,
98
+ self._url(path),
99
+ params={k: v for k, v in (params or {}).items() if v is not None},
100
+ json=json,
101
+ timeout=timeout,
102
+ )
103
+ except httpx.HTTPError as exc:
104
+ if self._can_retry(method, attempt, retryable):
105
+ await asyncio.sleep(self._backoff(attempt))
106
+ attempt += 1
107
+ continue
108
+ raise APIConnectionError("Could not reach %s: %s" % (self.base_url, exc)) from exc
109
+
110
+ status = resp.status_code
111
+ if status == 429:
112
+ self._guard.record_rate_limit()
113
+ raise build_api_error(status, resp.text, resp.headers)
114
+ if status in (502, 503, 504) and self._can_retry(method, attempt, retryable):
115
+ await asyncio.sleep(self._backoff(attempt, resp.headers))
116
+ attempt += 1
117
+ continue
118
+ if status >= 400:
119
+ raise build_api_error(status, resp.text, resp.headers)
120
+ self._guard.record_success()
121
+ return decode_body(resp.text)
122
+
123
+ # -- inboxes ------------------------------------------------------------
124
+ async def create_inbox(
125
+ self,
126
+ expires_in_seconds: Optional[int] = None,
127
+ local_part: Optional[str] = None,
128
+ webhook_url: Optional[str] = None,
129
+ **extra: Any
130
+ ) -> Inbox:
131
+ body = self._create_body(expires_in_seconds, local_part, webhook_url, extra)
132
+ data = await self._request("POST", "/inboxes", json=body, creating=True, retryable=False)
133
+ return Inbox.from_dict(data or {}, client=self)
134
+
135
+ async def delete_inbox(self, inbox: InboxRef) -> bool:
136
+ await self._request("DELETE", "/inboxes/%s" % self._inbox_id(inbox))
137
+ return True
138
+
139
+ @asynccontextmanager
140
+ async def temporary_inbox(self, **create_kwargs: Any) -> AsyncIterator[Inbox]:
141
+ """Create an inbox and delete it automatically when the block exits."""
142
+ inbox = await self.create_inbox(**create_kwargs)
143
+ try:
144
+ yield inbox
145
+ finally:
146
+ try:
147
+ await self.delete_inbox(inbox)
148
+ except APIError:
149
+ pass
150
+
151
+ # -- messages -----------------------------------------------------------
152
+ async def list_messages(
153
+ self, inbox: InboxRef, limit: Optional[int] = None, **params: Any
154
+ ) -> List[MessageSummary]:
155
+ query = dict(params)
156
+ query["limit"] = limit
157
+ data = await self._request(
158
+ "GET", "/inboxes/%s/messages" % self._inbox_id(inbox), params=query
159
+ )
160
+ return [MessageSummary.from_dict(item) for item in extract_list(data)]
161
+
162
+ async def get_message(self, inbox: InboxRef, message_id: Any) -> Message:
163
+ data = await self._request(
164
+ "GET",
165
+ "/inboxes/%s/messages/%s" % (self._inbox_id(inbox), self._message_id(message_id)),
166
+ )
167
+ return Message.from_dict(data or {})
168
+
169
+ async def wait_for_message(
170
+ self,
171
+ inbox: InboxRef,
172
+ timeout: float = 60.0,
173
+ interval: float = 2.0,
174
+ predicate: Optional[Callable[[MessageSummary], bool]] = None,
175
+ ) -> Message:
176
+ timeout = self._check_wait(timeout)
177
+ interval = max(float(interval), 1.0)
178
+ deadline = time.monotonic() + timeout
179
+ while True:
180
+ for summary in await self.list_messages(inbox):
181
+ if predicate is None or predicate(summary):
182
+ return await self.get_message(inbox, summary.id)
183
+ if time.monotonic() + interval > deadline:
184
+ raise OTPTimeoutError(timeout)
185
+ await asyncio.sleep(interval)
186
+
187
+ # -- OTP ----------------------------------------------------------------
188
+ async def wait_for_otp(self, inbox: InboxRef, timeout: float = 30.0) -> OTPResult:
189
+ timeout = self._check_wait(timeout)
190
+ try:
191
+ data = await self._request(
192
+ "GET",
193
+ "/inboxes/%s/wait-otp" % self._inbox_id(inbox),
194
+ params={"timeout": int(timeout) if timeout == int(timeout) else timeout},
195
+ read_timeout=max(self.timeout, timeout + 10.0),
196
+ retryable=False,
197
+ )
198
+ except RateLimitError:
199
+ raise
200
+ except APIError as exc:
201
+ if exc.status_code in (408, 504):
202
+ raise OTPTimeoutError(timeout) from exc
203
+ raise
204
+ result = OTPResult.from_dict(data if isinstance(data, dict) else {})
205
+ if not result.found and (result.status or "").lower() != "received":
206
+ raise OTPTimeoutError(timeout)
207
+ return result
208
+
209
+ async def latest_otp(self, inbox: InboxRef) -> OTPResult:
210
+ data = await self._request("GET", "/inboxes/%s/latest-otp" % self._inbox_id(inbox))
211
+ return OTPResult.from_dict(data if isinstance(data, dict) else {})
212
+
213
+ # -- account ------------------------------------------------------------
214
+ async def get_quota(self) -> Quota:
215
+ data = await self._request("GET", "/quota")
216
+ return Quota.from_dict(data if isinstance(data, dict) else {})
qubrixa_mail/cli.py ADDED
@@ -0,0 +1,90 @@
1
+ """Command line interface: ``qubrixa-mail --help``"""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from typing import Any, List, Optional
7
+
8
+ from . import __version__
9
+ from .client import QubrixaMail
10
+ from .exceptions import QubrixaError
11
+
12
+
13
+ def _build_parser() -> argparse.ArgumentParser:
14
+ p = argparse.ArgumentParser(prog="qubrixa-mail", description="Qubrixa Mail API client")
15
+ p.add_argument("--base-url", help="API base URL (or env QUBRIXA_BASE_URL)")
16
+ p.add_argument("--api-key", help="API key (or env QUBRIXA_API_KEY)")
17
+ p.add_argument("--version", action="version", version=__version__)
18
+ sub = p.add_subparsers(dest="command", required=True)
19
+
20
+ c = sub.add_parser("create", help="create a disposable inbox")
21
+ c.add_argument("--expires-in", type=int, dest="expires_in_seconds", help="lifetime in seconds")
22
+ c.add_argument("--local-part", help="custom local part")
23
+ c.add_argument("--webhook-url", help="forward incoming mail to this URL")
24
+ c.add_argument("--address-only", action="store_true", help="print only the address")
25
+
26
+ d = sub.add_parser("delete", help="delete an inbox")
27
+ d.add_argument("inbox", help="inbox id")
28
+
29
+ ls = sub.add_parser("messages", help="list messages")
30
+ ls.add_argument("inbox", help="inbox id")
31
+ ls.add_argument("--limit", type=int)
32
+
33
+ m = sub.add_parser("message", help="show one message")
34
+ m.add_argument("inbox", help="inbox id")
35
+ m.add_argument("message_id")
36
+
37
+ w = sub.add_parser("wait-otp", help="long-poll for an OTP / verification link")
38
+ w.add_argument("inbox", help="inbox id or address")
39
+ w.add_argument("--timeout", type=float, default=30.0)
40
+ w.add_argument("--otp-only", action="store_true", help="print only the OTP code")
41
+
42
+ lo = sub.add_parser("latest-otp", help="latest OTP / link (non-blocking)")
43
+ lo.add_argument("inbox", help="inbox id or address")
44
+ lo.add_argument("--otp-only", action="store_true")
45
+
46
+ sub.add_parser("quota", help="show daily quota")
47
+ return p
48
+
49
+
50
+ def _dump(data: Any) -> None:
51
+ print(json.dumps(data, indent=2, ensure_ascii=False, default=str))
52
+
53
+
54
+ def main(argv: Optional[List[str]] = None) -> int:
55
+ args = _build_parser().parse_args(argv)
56
+ try:
57
+ with QubrixaMail(base_url=args.base_url, api_key=args.api_key) as mail:
58
+ if args.command == "create":
59
+ inbox = mail.create_inbox(
60
+ expires_in_seconds=args.expires_in_seconds,
61
+ local_part=args.local_part,
62
+ webhook_url=args.webhook_url,
63
+ )
64
+ print(inbox.address) if args.address_only else _dump(inbox.raw)
65
+ elif args.command == "delete":
66
+ mail.delete_inbox(args.inbox)
67
+ print("deleted")
68
+ elif args.command == "messages":
69
+ _dump([m.raw for m in mail.list_messages(args.inbox, limit=args.limit)])
70
+ elif args.command == "message":
71
+ _dump(mail.get_message(args.inbox, args.message_id).raw)
72
+ elif args.command in ("wait-otp", "latest-otp"):
73
+ if args.command == "wait-otp":
74
+ result = mail.wait_for_otp(args.inbox, timeout=args.timeout)
75
+ else:
76
+ result = mail.latest_otp(args.inbox)
77
+ if args.otp_only:
78
+ print(result.otp or "")
79
+ return 0 if result.otp else 1
80
+ _dump(result.raw)
81
+ elif args.command == "quota":
82
+ _dump(mail.get_quota().raw)
83
+ except QubrixaError as exc:
84
+ print("error: %s" % exc, file=sys.stderr)
85
+ return 1
86
+ return 0
87
+
88
+
89
+ if __name__ == "__main__": # pragma: no cover
90
+ sys.exit(main())
qubrixa_mail/client.py ADDED
@@ -0,0 +1,233 @@
1
+ """Synchronous client (built on ``requests``)."""
2
+
3
+ import time
4
+ from contextlib import contextmanager
5
+ from typing import Any, Callable, Dict, Iterator, List, Optional
6
+
7
+ import requests
8
+
9
+ from ._base import (
10
+ InboxRef,
11
+ _BaseClient,
12
+ build_api_error,
13
+ decode_body,
14
+ )
15
+ from .exceptions import APIConnectionError, APIError, OTPTimeoutError, RateLimitError
16
+ from .models import (
17
+ Inbox,
18
+ Message,
19
+ MessageSummary,
20
+ OTPResult,
21
+ Quota,
22
+ extract_list,
23
+ )
24
+
25
+
26
+ class QubrixaMail(_BaseClient):
27
+ """Client for the Qubrixa Mail Developer API.
28
+
29
+ >>> mail = QubrixaMail(base_url="https://mail.qubrixa.in/api/v1", api_key="sk_live_...")
30
+ >>> inbox = mail.create_inbox(expires_in_seconds=3600)
31
+ >>> print(inbox.address)
32
+ >>> otp = mail.wait_for_otp(inbox, timeout=30)
33
+ >>> print(otp.otp)
34
+
35
+ ``base_url`` and ``api_key`` may also come from the ``QUBRIXA_BASE_URL`` and
36
+ ``QUBRIXA_API_KEY`` environment variables.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ base_url: Optional[str] = None,
42
+ api_key: Optional[str] = None,
43
+ *,
44
+ timeout: float = 30.0,
45
+ max_retries: int = 2,
46
+ rate_limit: bool = True,
47
+ general_limit: int = 270,
48
+ create_limit: int = 9,
49
+ user_agent: Optional[str] = None,
50
+ session: Optional[requests.Session] = None,
51
+ ) -> None:
52
+ super().__init__(
53
+ base_url,
54
+ api_key,
55
+ timeout=timeout,
56
+ max_retries=max_retries,
57
+ rate_limit=rate_limit,
58
+ general_limit=general_limit,
59
+ create_limit=create_limit,
60
+ user_agent=user_agent,
61
+ )
62
+ self._owns_session = session is None
63
+ self._session = session or requests.Session()
64
+ self._session.headers.update(self._headers)
65
+
66
+ # -- lifecycle ----------------------------------------------------------
67
+ def close(self) -> None:
68
+ if self._owns_session:
69
+ self._session.close()
70
+
71
+ def __enter__(self) -> "QubrixaMail":
72
+ return self
73
+
74
+ def __exit__(self, *exc_info: Any) -> None:
75
+ self.close()
76
+
77
+ # -- transport ----------------------------------------------------------
78
+ def _request(
79
+ self,
80
+ method: str,
81
+ path: str,
82
+ *,
83
+ params: Optional[Dict[str, Any]] = None,
84
+ json: Optional[Dict[str, Any]] = None,
85
+ creating: bool = False,
86
+ read_timeout: Optional[float] = None,
87
+ retryable: bool = True,
88
+ ) -> Any:
89
+ attempt = 0
90
+ while True:
91
+ self._guard.check()
92
+ if self._general_limiter is not None:
93
+ self._general_limiter.acquire()
94
+ if creating and self._create_limiter is not None:
95
+ self._create_limiter.acquire()
96
+ try:
97
+ resp = self._session.request(
98
+ method,
99
+ self._url(path),
100
+ params={k: v for k, v in (params or {}).items() if v is not None},
101
+ json=json,
102
+ timeout=self._timeouts(read_timeout),
103
+ )
104
+ except requests.RequestException as exc:
105
+ if self._can_retry(method, attempt, retryable):
106
+ time.sleep(self._backoff(attempt))
107
+ attempt += 1
108
+ continue
109
+ raise APIConnectionError("Could not reach %s: %s" % (self.base_url, exc)) from exc
110
+
111
+ status = resp.status_code
112
+ if status == 429:
113
+ self._guard.record_rate_limit()
114
+ raise build_api_error(status, resp.text, resp.headers)
115
+ if status in (502, 503, 504) and self._can_retry(method, attempt, retryable):
116
+ time.sleep(self._backoff(attempt, resp.headers))
117
+ attempt += 1
118
+ continue
119
+ if status >= 400:
120
+ raise build_api_error(status, resp.text, resp.headers)
121
+ self._guard.record_success()
122
+ return decode_body(resp.text)
123
+
124
+ # -- inboxes ------------------------------------------------------------
125
+ def create_inbox(
126
+ self,
127
+ expires_in_seconds: Optional[int] = None,
128
+ local_part: Optional[str] = None,
129
+ webhook_url: Optional[str] = None,
130
+ **extra: Any
131
+ ) -> Inbox:
132
+ """``POST /inboxes`` - create a disposable inbox.
133
+
134
+ Extra keyword arguments are sent as-is in the JSON body.
135
+ """
136
+ body = self._create_body(expires_in_seconds, local_part, webhook_url, extra)
137
+ data = self._request("POST", "/inboxes", json=body, creating=True, retryable=False)
138
+ return Inbox.from_dict(data or {}, client=self)
139
+
140
+ def delete_inbox(self, inbox: InboxRef) -> bool:
141
+ """``DELETE /inboxes/{id}`` - delete an inbox and all of its messages."""
142
+ self._request("DELETE", "/inboxes/%s" % self._inbox_id(inbox))
143
+ return True
144
+
145
+ @contextmanager
146
+ def temporary_inbox(self, **create_kwargs: Any) -> Iterator[Inbox]:
147
+ """Create an inbox and delete it automatically when the block exits."""
148
+ inbox = self.create_inbox(**create_kwargs)
149
+ try:
150
+ yield inbox
151
+ finally:
152
+ try:
153
+ self.delete_inbox(inbox)
154
+ except APIError:
155
+ pass # already expired / deleted
156
+
157
+ # -- messages -----------------------------------------------------------
158
+ def list_messages(
159
+ self, inbox: InboxRef, limit: Optional[int] = None, **params: Any
160
+ ) -> List[MessageSummary]:
161
+ """``GET /inboxes/{id}/messages`` - paginated message summaries."""
162
+ query = dict(params)
163
+ query["limit"] = limit
164
+ data = self._request("GET", "/inboxes/%s/messages" % self._inbox_id(inbox), params=query)
165
+ return [MessageSummary.from_dict(item) for item in extract_list(data)]
166
+
167
+ def get_message(self, inbox: InboxRef, message_id: Any) -> Message:
168
+ """``GET /inboxes/{id}/messages/{message_id}`` - full text + sanitized HTML."""
169
+ data = self._request(
170
+ "GET",
171
+ "/inboxes/%s/messages/%s" % (self._inbox_id(inbox), self._message_id(message_id)),
172
+ )
173
+ return Message.from_dict(data or {})
174
+
175
+ def wait_for_message(
176
+ self,
177
+ inbox: InboxRef,
178
+ timeout: float = 60.0,
179
+ interval: float = 2.0,
180
+ predicate: Optional[Callable[[MessageSummary], bool]] = None,
181
+ ) -> Message:
182
+ """Poll until a message (optionally matching ``predicate``) arrives.
183
+
184
+ Use this for emails that are not OTP mails. ``interval`` is clamped to at
185
+ least 1 second so polling cannot exhaust the rate limit.
186
+ """
187
+ timeout = self._check_wait(timeout)
188
+ interval = max(float(interval), 1.0)
189
+ deadline = time.monotonic() + timeout
190
+ while True:
191
+ for summary in self.list_messages(inbox):
192
+ if predicate is None or predicate(summary):
193
+ return self.get_message(inbox, summary.id)
194
+ if time.monotonic() + interval > deadline:
195
+ raise OTPTimeoutError(timeout)
196
+ time.sleep(interval)
197
+
198
+ # -- OTP ----------------------------------------------------------------
199
+ def wait_for_otp(self, inbox: InboxRef, timeout: float = 30.0) -> OTPResult:
200
+ """``GET /inboxes/{id_or_address}/wait-otp`` - long-poll for an OTP / link.
201
+
202
+ Raises :class:`OTPTimeoutError` if nothing arrives within ``timeout`` seconds.
203
+ """
204
+ timeout = self._check_wait(timeout)
205
+ try:
206
+ data = self._request(
207
+ "GET",
208
+ "/inboxes/%s/wait-otp" % self._inbox_id(inbox),
209
+ params={"timeout": int(timeout) if timeout == int(timeout) else timeout},
210
+ read_timeout=max(self.timeout, timeout + 10.0),
211
+ retryable=False,
212
+ )
213
+ except RateLimitError:
214
+ raise
215
+ except APIError as exc:
216
+ if exc.status_code in (408, 504):
217
+ raise OTPTimeoutError(timeout) from exc
218
+ raise
219
+ result = OTPResult.from_dict(data if isinstance(data, dict) else {})
220
+ if not result.found and (result.status or "").lower() != "received":
221
+ raise OTPTimeoutError(timeout)
222
+ return result
223
+
224
+ def latest_otp(self, inbox: InboxRef) -> OTPResult:
225
+ """``GET /inboxes/{id_or_address}/latest-otp`` - non-blocking."""
226
+ data = self._request("GET", "/inboxes/%s/latest-otp" % self._inbox_id(inbox))
227
+ return OTPResult.from_dict(data if isinstance(data, dict) else {})
228
+
229
+ # -- account ------------------------------------------------------------
230
+ def get_quota(self) -> Quota:
231
+ """``GET /quota`` - remaining inbox creation limits for the 24h cycle."""
232
+ data = self._request("GET", "/quota")
233
+ return Quota.from_dict(data if isinstance(data, dict) else {})
@@ -0,0 +1,77 @@
1
+ """Exception hierarchy for qubrixa-mail."""
2
+
3
+ from typing import Any, Mapping, Optional
4
+
5
+
6
+ class QubrixaError(Exception):
7
+ """Base class for every error raised by this library."""
8
+
9
+
10
+ class ConfigurationError(QubrixaError):
11
+ """The client was created with missing or invalid settings."""
12
+
13
+
14
+ class APIConnectionError(QubrixaError):
15
+ """The API could not be reached (DNS, TLS, timeout, connection reset...)."""
16
+
17
+
18
+ class AbuseGuardError(QubrixaError):
19
+ """Raised locally, *before* sending a request, when too many consecutive
20
+ HTTP 429 responses were received.
21
+
22
+ Qubrixa Mail suspends the API key and IP after 5 consecutive rate-limit
23
+ violations within 5 minutes, so the client stops early to protect your key.
24
+ """
25
+
26
+ def __init__(self, message: str, retry_after: float = 0.0) -> None:
27
+ super().__init__(message)
28
+ self.retry_after = retry_after
29
+
30
+
31
+ class OTPTimeoutError(QubrixaError):
32
+ """No verification email arrived before the wait timeout expired."""
33
+
34
+ def __init__(self, timeout: float) -> None:
35
+ super().__init__("No OTP / verification email received within %s seconds." % timeout)
36
+ self.timeout = timeout
37
+
38
+
39
+ class APIError(QubrixaError):
40
+ """The API answered with an error status code."""
41
+
42
+ def __init__(
43
+ self,
44
+ message: str,
45
+ status_code: int,
46
+ payload: Any = None,
47
+ headers: Optional[Mapping[str, str]] = None,
48
+ ) -> None:
49
+ super().__init__("[HTTP %s] %s" % (status_code, message))
50
+ self.message = message
51
+ self.status_code = status_code
52
+ self.payload = payload
53
+ self.headers = dict(headers or {})
54
+
55
+
56
+ class AuthenticationError(APIError):
57
+ """401 - the API key is invalid, revoked or missing."""
58
+
59
+
60
+ class ForbiddenError(APIError):
61
+ """403 - creation paused by an admin, or the account is blacklisted."""
62
+
63
+
64
+ class NotFoundError(APIError):
65
+ """404 - the inbox or message does not exist (or has expired)."""
66
+
67
+
68
+ class RateLimitError(APIError):
69
+ """429 - you exceeded the rate limits. Slow down to avoid a strike ban."""
70
+
71
+ def __init__(self, *args: Any, retry_after: Optional[float] = None, **kwargs: Any) -> None:
72
+ super().__init__(*args, **kwargs)
73
+ self.retry_after = retry_after
74
+
75
+
76
+ class ServiceUnavailableError(APIError):
77
+ """503 - the Developer API is in scheduled maintenance."""
qubrixa_mail/models.py ADDED
@@ -0,0 +1,177 @@
1
+ """Typed response objects.
2
+
3
+ Every model keeps the untouched server response in ``.raw`` so nothing is lost
4
+ if the API adds new fields.
5
+ """
6
+
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime
9
+ from typing import Any, Dict, List, Optional
10
+
11
+
12
+ def _parse_dt(value: Any) -> Optional[datetime]:
13
+ if not value or not isinstance(value, str):
14
+ return None
15
+ try:
16
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
17
+ except ValueError:
18
+ return None
19
+
20
+
21
+ def _first(data: Dict[str, Any], *keys: str) -> Any:
22
+ for key in keys:
23
+ if data.get(key) is not None:
24
+ return data[key]
25
+ return None
26
+
27
+
28
+ @dataclass
29
+ class Inbox:
30
+ """A disposable inbox."""
31
+
32
+ id: str
33
+ address: str
34
+ local_part: Optional[str] = None
35
+ domain: Optional[str] = None
36
+ is_active: bool = True
37
+ expires_at: Optional[datetime] = None
38
+ created_at: Optional[datetime] = None
39
+ message_count: int = 0
40
+ remaining_quota: Optional[int] = None
41
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
42
+ _client: Any = field(default=None, repr=False, compare=False)
43
+
44
+ @classmethod
45
+ def from_dict(cls, data: Dict[str, Any], client: Any = None) -> "Inbox":
46
+ return cls(
47
+ id=str(data.get("id", "")),
48
+ address=data.get("address", ""),
49
+ local_part=data.get("local_part"),
50
+ domain=data.get("domain"),
51
+ is_active=bool(data.get("is_active", True)),
52
+ expires_at=_parse_dt(data.get("expires_at")),
53
+ created_at=_parse_dt(data.get("created_at")),
54
+ message_count=int(data.get("message_count") or 0),
55
+ remaining_quota=data.get("remaining_quota"),
56
+ raw=data,
57
+ _client=client,
58
+ )
59
+
60
+ def __str__(self) -> str:
61
+ return self.address
62
+
63
+ # -- shortcuts (with AsyncQubrixaMail these return awaitables) ----------
64
+ def wait_for_otp(self, timeout: float = 30) -> Any:
65
+ return self._client.wait_for_otp(self, timeout=timeout)
66
+
67
+ def latest_otp(self) -> Any:
68
+ return self._client.latest_otp(self)
69
+
70
+ def messages(self, limit: Optional[int] = None) -> Any:
71
+ return self._client.list_messages(self, limit=limit)
72
+
73
+ def delete(self) -> Any:
74
+ return self._client.delete_inbox(self)
75
+
76
+
77
+ @dataclass
78
+ class MessageSummary:
79
+ """One row of ``list_messages``."""
80
+
81
+ id: str
82
+ sender: Optional[str] = None
83
+ subject: Optional[str] = None
84
+ received_at: Optional[datetime] = None
85
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
86
+
87
+ @classmethod
88
+ def from_dict(cls, data: Dict[str, Any]) -> "MessageSummary":
89
+ return cls(
90
+ id=str(_first(data, "id", "message_id") or ""),
91
+ sender=_first(data, "sender", "from", "from_address"),
92
+ subject=data.get("subject"),
93
+ received_at=_parse_dt(_first(data, "received_at", "created_at", "date")),
94
+ raw=data,
95
+ )
96
+
97
+
98
+ @dataclass
99
+ class Message(MessageSummary):
100
+ """A full message with bodies."""
101
+
102
+ text: Optional[str] = None
103
+ html: Optional[str] = None
104
+
105
+ @classmethod
106
+ def from_dict(cls, data: Dict[str, Any]) -> "Message":
107
+ return cls(
108
+ id=str(_first(data, "id", "message_id") or ""),
109
+ sender=_first(data, "sender", "from", "from_address"),
110
+ subject=data.get("subject"),
111
+ received_at=_parse_dt(_first(data, "received_at", "created_at", "date")),
112
+ text=_first(data, "text", "text_body", "body_text", "plain_text", "body"),
113
+ html=_first(data, "html", "html_body", "body_html", "sanitized_html"),
114
+ raw=data,
115
+ )
116
+
117
+
118
+ @dataclass
119
+ class OTPResult:
120
+ """Result of ``wait_for_otp`` / ``latest_otp``."""
121
+
122
+ status: Optional[str] = None
123
+ otp: Optional[str] = None
124
+ verification_url: Optional[str] = None
125
+ subject: Optional[str] = None
126
+ sender: Optional[str] = None
127
+ message_id: Optional[str] = None
128
+ received_at: Optional[datetime] = None
129
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
130
+
131
+ @property
132
+ def found(self) -> bool:
133
+ """True if an OTP code or verification link was extracted."""
134
+ return bool(self.otp or self.verification_url)
135
+
136
+ @classmethod
137
+ def from_dict(cls, data: Dict[str, Any]) -> "OTPResult":
138
+ otp = _first(data, "otp", "code")
139
+ return cls(
140
+ status=data.get("status"),
141
+ otp=str(otp) if otp is not None else None,
142
+ verification_url=_first(data, "verification_url", "link", "url"),
143
+ subject=data.get("subject"),
144
+ sender=data.get("sender"),
145
+ message_id=_first(data, "message_id", "id"),
146
+ received_at=_parse_dt(data.get("received_at")),
147
+ raw=data,
148
+ )
149
+
150
+
151
+ @dataclass
152
+ class Quota:
153
+ """Daily quota information (exact fields depend on your plan - see ``raw``)."""
154
+
155
+ raw: Dict[str, Any] = field(default_factory=dict)
156
+
157
+ @classmethod
158
+ def from_dict(cls, data: Dict[str, Any]) -> "Quota":
159
+ return cls(raw=data)
160
+
161
+ def get(self, key: str, default: Any = None) -> Any:
162
+ return self.raw.get(key, default)
163
+
164
+ def __getitem__(self, key: str) -> Any:
165
+ return self.raw[key]
166
+
167
+
168
+ def extract_list(payload: Any) -> List[Dict[str, Any]]:
169
+ """Accept either a bare JSON list or an envelope such as ``{"messages": [...]}``."""
170
+ if isinstance(payload, list):
171
+ return payload
172
+ if isinstance(payload, dict):
173
+ for key in ("messages", "items", "data", "results"):
174
+ value = payload.get(key)
175
+ if isinstance(value, list):
176
+ return value
177
+ return []
qubrixa_mail/py.typed ADDED
File without changes
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: qubrixa-mail
3
+ Version: 0.1.0
4
+ Summary: Unofficial Python client for the Qubrixa Mail disposable-inbox / OTP API
5
+ Author: Its2Pawan
6
+ Maintainer: Its2Pawan
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/Its2Pawan/qubrixa-mail
9
+ Project-URL: Documentation, https://github.com/Its2Pawan/qubrixa-mail#readme
10
+ Project-URL: Issues, https://github.com/Its2Pawan/qubrixa-mail/issues
11
+ Keywords: qubrixa,disposable email,temp mail,otp,api client,testing
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Typing :: Typed
22
+ Classifier: Topic :: Communications :: Email
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: requests>=2.25
27
+ Provides-Extra: async
28
+ Requires-Dist: httpx>=0.24; extra == "async"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7; extra == "dev"
31
+ Requires-Dist: build; extra == "dev"
32
+ Requires-Dist: twine; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # qubrixa-mail
36
+
37
+ Unofficial Python client for the **Qubrixa Mail** Developer API: create disposable
38
+ inboxes, read messages, and extract OTP codes / verification links.
39
+
40
+ You need two things from your Qubrixa Mail account: the **base URL** and an **API key**
41
+ (generate one in the Developer Console).
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install qubrixa-mail # sync client (requests)
47
+ pip install "qubrixa-mail[async]" # + async client (httpx)
48
+ ```
49
+
50
+ ## Quick start
51
+
52
+ ```python
53
+ from qubrixa_mail import QubrixaMail
54
+
55
+ mail = QubrixaMail(
56
+ base_url="https://mail.qubrixa.in/api/v1", # your base URL
57
+ api_key="sk_live_your_secret_api_key_here", # your API key
58
+ )
59
+
60
+ inbox = mail.create_inbox(expires_in_seconds=3600)
61
+ print(inbox.address) # use this address on the site you are testing
62
+
63
+ otp = inbox.wait_for_otp(timeout=30) # long-polls until the email arrives
64
+ print(otp.otp, otp.verification_url)
65
+
66
+ inbox.delete()
67
+ ```
68
+
69
+ Or configure through environment variables and write `QubrixaMail()`:
70
+
71
+ ```bash
72
+ export QUBRIXA_BASE_URL="https://mail.qubrixa.in/api/v1"
73
+ export QUBRIXA_API_KEY="sk_live_..."
74
+ ```
75
+
76
+ If you pass only a host (`https://mail.qubrixa.in`), `/api/v1` is appended automatically.
77
+
78
+ ### Auto-cleanup
79
+
80
+ ```python
81
+ with QubrixaMail() as mail:
82
+ with mail.temporary_inbox(expires_in_seconds=600) as inbox:
83
+ ... # inbox is deleted when the block exits
84
+ ```
85
+
86
+ ### Async
87
+
88
+ ```python
89
+ import asyncio
90
+ from qubrixa_mail import AsyncQubrixaMail
91
+
92
+ async def main():
93
+ async with AsyncQubrixaMail() as mail:
94
+ async with mail.temporary_inbox() as inbox:
95
+ otp = await mail.wait_for_otp(inbox, timeout=30)
96
+ print(otp.otp)
97
+
98
+ asyncio.run(main())
99
+ ```
100
+
101
+ ## API
102
+
103
+ | Method | Endpoint |
104
+ |---|---|
105
+ | `create_inbox(expires_in_seconds=, local_part=, webhook_url=, **extra)` | `POST /inboxes` |
106
+ | `delete_inbox(inbox)` | `DELETE /inboxes/{id}` |
107
+ | `list_messages(inbox, limit=)` | `GET /inboxes/{id}/messages` |
108
+ | `get_message(inbox, message_id)` | `GET /inboxes/{id}/messages/{message_id}` |
109
+ | `wait_for_otp(inbox, timeout=30)` | `GET /inboxes/{id_or_address}/wait-otp` |
110
+ | `latest_otp(inbox)` | `GET /inboxes/{id_or_address}/latest-otp` |
111
+ | `get_quota()` | `GET /quota` |
112
+ | `wait_for_message(inbox, timeout=, interval=, predicate=)` | polls `list_messages` (non-OTP mail) |
113
+
114
+ `inbox` can be an `Inbox` object, an inbox id, or (for the OTP endpoints) an email address.
115
+ Every returned object keeps the full server response in `.raw`.
116
+
117
+ ## Rate limits & bans
118
+
119
+ The server allows **300 requests/min** and **10 inbox creations/min**, and suspends a
120
+ key + IP after **5 consecutive 429s within 5 minutes**. This client protects you:
121
+
122
+ * a built-in sliding-window limiter (default 270/min and 9/min) delays calls instead of failing;
123
+ * `429` is **never retried automatically** - `RateLimitError.retry_after` tells you how long to wait;
124
+ * after 3 consecutive 429s it raises `AbuseGuardError` locally without contacting the server;
125
+ * only `GET`/`DELETE` are retried on connection errors and 502/503/504 (never `POST`).
126
+
127
+ Disable the limiter with `QubrixaMail(..., rate_limit=False)`.
128
+
129
+ ## Errors
130
+
131
+ `QubrixaError` -> `ConfigurationError`, `APIConnectionError`, `AbuseGuardError`,
132
+ `OTPTimeoutError`, and `APIError` -> `AuthenticationError` (401), `ForbiddenError` (403),
133
+ `NotFoundError` (404), `RateLimitError` (429), `ServiceUnavailableError` (503).
134
+
135
+ ## CLI
136
+
137
+ ```bash
138
+ qubrixa-mail create --expires-in 3600 --address-only
139
+ qubrixa-mail wait-otp test7391@samirjs.qzz.io --timeout 30 --otp-only
140
+ qubrixa-mail quota
141
+ ```
142
+
143
+ ## Responsible use
144
+
145
+ Use disposable inboxes only for services and accounts you are allowed to test, and follow the
146
+ terms of Qubrixa Mail and of every site you interact with. This is an unofficial community
147
+ library and is not affiliated with Qubrixa.
148
+
149
+ ## Publish to PyPI
150
+
151
+ ```bash
152
+ pip install build twine
153
+ python -m build
154
+ twine upload dist/*
155
+ ```
156
+ Author / maintainer: **Its2Pawan**.
@@ -0,0 +1,16 @@
1
+ qubrixa_mail/__init__.py,sha256=2xxx1nrwt8QZk1twN5ICIy5NBbddB0a2vfIDEQ4LxQk,1165
2
+ qubrixa_mail/_base.py,sha256=5cZmPdTrbmTcwWz9tpfQHJKVeLz71q-YSes1qDLxsk0,6684
3
+ qubrixa_mail/_ratelimit.py,sha256=sE9rt2F3yqw5gZX5JgijIvs4L4f_xIveyeL3rcbI1GI,3148
4
+ qubrixa_mail/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
5
+ qubrixa_mail/async_client.py,sha256=0igbtrJHI2ww1P4d-qW-Ox2Mpa3wdi32kf2_zjOrh2w,8309
6
+ qubrixa_mail/cli.py,sha256=nDBi1fvRFS1YB5Ps9cE4uK7VSmIf9SZl0OL0uJQ9u_M,3685
7
+ qubrixa_mail/client.py,sha256=jyD9yawvqgGZSzlABIingL7XqLCNzLOlfu8xyhSMYfg,8844
8
+ qubrixa_mail/exceptions.py,sha256=NHnPEfWOQyfI-sucTWjQ3YwqTc-cYqrBio07aULy84U,2347
9
+ qubrixa_mail/models.py,sha256=RcBRkTYzZAm5LFHq_HoxPYZLMekfvHloQYeovtSSUI4,5627
10
+ qubrixa_mail/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ qubrixa_mail-0.1.0.dist-info/licenses/LICENSE,sha256=1od7asnk02Kiv_YqsTrcsmQOWGfLlb87fEEYaTLNgbE,1066
12
+ qubrixa_mail-0.1.0.dist-info/METADATA,sha256=ss6dSiro70JPhvRq7k5w0OulYKE6bhmt2wGsWu4Nkss,5220
13
+ qubrixa_mail-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ qubrixa_mail-0.1.0.dist-info/entry_points.txt,sha256=mLy7MsDXUGRkPi0jM62Dkfdny7E2iRQscw30O1I7snU,55
15
+ qubrixa_mail-0.1.0.dist-info/top_level.txt,sha256=TAYY_IDR2RroXSA_sP0AuZ_Eyy0-Cc0qSAwM2ibByDg,13
16
+ qubrixa_mail-0.1.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,2 @@
1
+ [console_scripts]
2
+ qubrixa-mail = qubrixa_mail.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Its2Pawan
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
+ qubrixa_mail