receiverdotemail 2.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,492 @@
1
+ """
2
+ Email resource operations
3
+ """
4
+
5
+ import asyncio
6
+ import json
7
+ import math
8
+ import time
9
+ from collections import OrderedDict
10
+ from datetime import datetime, timezone
11
+ from typing import Any, AsyncIterator, Dict, List, Optional, Tuple
12
+ from urllib.parse import quote
13
+
14
+ from receiverdotemail._context import ProjectContext
15
+ from receiverdotemail._sse import iter_sse
16
+ from receiverdotemail._utils import SinceLike, to_iso
17
+ from receiverdotemail.errors import ReceiverError, ReceiverTimeoutError
18
+ from receiverdotemail.http import HttpClient
19
+ from receiverdotemail.types.email import (
20
+ Email,
21
+ EmailListResponse,
22
+ OtpResult,
23
+ SendTestResult,
24
+ StreamEvent,
25
+ )
26
+
27
+ # The API holds a wait or OTP request open for at most 60 s; longer waits loop.
28
+ MAX_SERVER_WAIT_SECONDS = 60
29
+ # Extra HTTP timeout on top of the server-side wait, for network latency.
30
+ LONG_POLL_GRACE_SECONDS = 15
31
+
32
+
33
+ class Emails:
34
+ """Email operations. ``project_id`` is optional everywhere when using an API key."""
35
+
36
+ # Stream reconnects after a failure wait base * 2^n seconds (capped at 30 s);
37
+ # the stream raises after this many consecutive failures without an email.
38
+ _reconnect_base_delay: float = 0.5
39
+ _max_reconnect_failures: int = 10
40
+
41
+ def __init__(self, http: HttpClient, context: ProjectContext):
42
+ self._http = http
43
+ self._context = context
44
+
45
+ async def list(
46
+ self,
47
+ project_id: Optional[str] = None,
48
+ recipient: Optional[str] = None,
49
+ sender: Optional[str] = None,
50
+ subject: Optional[str] = None,
51
+ received_after: Optional[datetime] = None,
52
+ received_before: Optional[datetime] = None,
53
+ has_attachments: Optional[bool] = None,
54
+ limit: int = 50,
55
+ cursor: Optional[str] = None,
56
+ ) -> EmailListResponse:
57
+ """
58
+ List emails with optional filters, newest first.
59
+
60
+ Args:
61
+ project_id: Project ID (optional with an API key)
62
+ recipient: Filter by recipient email
63
+ sender: Filter by sender email
64
+ subject: Filter by subject (substring match)
65
+ received_after: Filter by received date (after)
66
+ received_before: Filter by received date (before)
67
+ has_attachments: Filter by attachment presence
68
+ limit: Number of emails to return (max 100)
69
+ cursor: Pagination cursor
70
+
71
+ Returns:
72
+ EmailListResponse with emails and pagination info
73
+ """
74
+ pid = await self._context.project_id(project_id)
75
+ params = {
76
+ "recipient": recipient,
77
+ "sender": sender,
78
+ "subject": subject,
79
+ "receivedAfter": received_after,
80
+ "receivedBefore": received_before,
81
+ "hasAttachments": has_attachments,
82
+ "limit": limit,
83
+ "cursor": cursor,
84
+ }
85
+
86
+ data = await self._http.get(f"/projects/{pid}/emails", params=params)
87
+ return EmailListResponse(**data)
88
+
89
+ async def list_all(
90
+ self,
91
+ project_id: Optional[str] = None,
92
+ recipient: Optional[str] = None,
93
+ sender: Optional[str] = None,
94
+ received_after: Optional[datetime] = None,
95
+ received_before: Optional[datetime] = None,
96
+ page_size: int = 100,
97
+ ) -> AsyncIterator[Email]:
98
+ """
99
+ Iterate over every matching email, newest first, fetching pages as needed.
100
+
101
+ Example:
102
+ async for email in client.emails.list_all():
103
+ ...
104
+ """
105
+ pid = await self._context.project_id(project_id)
106
+ cursor: Optional[str] = None
107
+ while True:
108
+ page = await self.list(
109
+ pid,
110
+ recipient=recipient,
111
+ sender=sender,
112
+ received_after=received_after,
113
+ received_before=received_before,
114
+ limit=page_size,
115
+ cursor=cursor,
116
+ )
117
+ for email in page.emails:
118
+ yield email
119
+ if not page.has_more or not page.next_cursor:
120
+ return
121
+ cursor = page.next_cursor
122
+
123
+ async def get(self, project_id: Optional[str], email_id: Optional[str] = None) -> Email:
124
+ """
125
+ Get a single email by ID: ``get(email_id)`` or ``get(project_id, email_id)``.
126
+
127
+ Args:
128
+ project_id: Project ID (or the email ID when called with one argument)
129
+ email_id: Email ID
130
+
131
+ Returns:
132
+ Email object
133
+ """
134
+ project_id, email_id = _split(project_id, email_id)
135
+ pid = await self._context.project_id(project_id)
136
+ data = await self._http.get(f"/projects/{pid}/emails/{quote(email_id, safe='')}")
137
+ return Email(**data)
138
+
139
+ async def wait_for(
140
+ self,
141
+ project_id: Optional[str] = None,
142
+ timeout: float = 30,
143
+ recipient: Optional[str] = None,
144
+ sender: Optional[str] = None,
145
+ subject: Optional[str] = None,
146
+ since: Optional[SinceLike] = None,
147
+ received_after: Optional[SinceLike] = None,
148
+ ) -> Email:
149
+ """
150
+ Wait for an email matching the filters (long-polling).
151
+
152
+ Waits of any length are supported: the SDK repeats 60-second server
153
+ waits until ``timeout`` runs out, keeping the same ``since``.
154
+
155
+ Args:
156
+ project_id: Project ID (optional with an API key)
157
+ timeout: Max seconds to wait (default: 30, any length)
158
+ recipient: Filter by recipient email
159
+ sender: Filter by sender email
160
+ subject: Filter by subject (substring, case-insensitive)
161
+ since: Only emails received strictly after this time (datetime or ISO
162
+ string). Default: 60 seconds before the first request. Pass
163
+ ``inbox.created_at`` or the previous email's ``received_at``.
164
+ received_after: Deprecated alias of ``since``
165
+
166
+ Returns:
167
+ The matching email (with text body and links)
168
+
169
+ Raises:
170
+ ReceiverTimeoutError: nothing arrived in time (``.since``, ``.waited_seconds``)
171
+ """
172
+ pid = await self._context.project_id(project_id)
173
+ data = await self._poll(
174
+ f"/projects/{pid}/emails/wait",
175
+ {"recipient": recipient, "sender": sender, "subject": subject},
176
+ since if since is not None else received_after,
177
+ timeout,
178
+ hit_status="received",
179
+ legacy_key="email",
180
+ )
181
+ return Email(**data["email"])
182
+
183
+ async def wait_for_otp(
184
+ self,
185
+ project_id: Optional[str] = None,
186
+ recipient: Optional[str] = None,
187
+ sender: Optional[str] = None,
188
+ subject: Optional[str] = None,
189
+ since: Optional[SinceLike] = None,
190
+ timeout: float = 30,
191
+ code_length: Optional[int] = None,
192
+ received_after: Optional[SinceLike] = None,
193
+ ) -> OtpResult:
194
+ """
195
+ Wait for an email containing a one-time code and return the code.
196
+
197
+ Loops like ``wait_for`` for timeouts longer than 60 seconds.
198
+
199
+ Args:
200
+ project_id: Project ID (optional with an API key)
201
+ recipient: Filter by recipient email address
202
+ sender: Filter by sender email address
203
+ subject: Filter by subject (substring, case-insensitive)
204
+ since: Only emails received strictly after this time (datetime or ISO
205
+ string). Default: 60 seconds before the first request.
206
+ timeout: Max seconds to wait (default: 30, any length)
207
+ code_length: Expected code length (4, 6, or 8). Omit to auto-detect.
208
+ received_after: Deprecated alias of ``since``
209
+
210
+ Returns:
211
+ OtpResult: ``code`` (newest), ``code_length``, ``source``, ``email`` and
212
+ ``candidates`` (every code found, newest first)
213
+
214
+ Raises:
215
+ ReceiverTimeoutError: no code arrived in time
216
+ """
217
+ pid = await self._context.project_id(project_id)
218
+ data = await self._poll(
219
+ f"/projects/{pid}/emails/otp",
220
+ {
221
+ "recipient": recipient,
222
+ "sender": sender,
223
+ "subject": subject,
224
+ "codeLength": code_length,
225
+ },
226
+ since if since is not None else received_after,
227
+ timeout,
228
+ hit_status="found",
229
+ legacy_key="code",
230
+ )
231
+ return OtpResult(**data)
232
+
233
+ async def get_otp(
234
+ self,
235
+ project_id: Optional[str] = None,
236
+ recipient: Optional[str] = None,
237
+ sender: Optional[str] = None,
238
+ subject: Optional[str] = None,
239
+ since: Optional[SinceLike] = None,
240
+ timeout: float = 0,
241
+ code_length: Optional[int] = None,
242
+ received_after: Optional[SinceLike] = None,
243
+ ) -> Optional[OtpResult]:
244
+ """
245
+ Return the newest one-time code in emails already received, without waiting.
246
+
247
+ Scans up to 10 matching emails received after ``since`` (default: the last
248
+ 60 seconds), newest first. Use ``wait_for_otp`` to wait for one.
249
+
250
+ Args:
251
+ project_id: Project ID (optional with an API key)
252
+ recipient: Filter by recipient email address
253
+ sender: Filter by sender email address
254
+ subject: Filter by subject (substring, case-insensitive)
255
+ since: Only emails received strictly after this time
256
+ timeout: Seconds to wait (default 0: no wait)
257
+ code_length: Expected code length (4, 6, or 8). Omit to auto-detect.
258
+ received_after: Deprecated alias of ``since``
259
+
260
+ Returns:
261
+ OtpResult, or None when no code was found
262
+ """
263
+ try:
264
+ return await self.wait_for_otp(
265
+ project_id,
266
+ recipient=recipient,
267
+ sender=sender,
268
+ subject=subject,
269
+ since=since if since is not None else received_after,
270
+ timeout=timeout,
271
+ code_length=code_length,
272
+ )
273
+ except ReceiverTimeoutError:
274
+ return None
275
+
276
+ async def stream(
277
+ self,
278
+ project_id: Optional[str] = None,
279
+ recipient: Optional[str] = None,
280
+ since: Optional[SinceLike] = None,
281
+ sender: Optional[str] = None,
282
+ ) -> AsyncIterator[StreamEvent]:
283
+ """
284
+ Yield emails as they arrive (Server-Sent Events), oldest first.
285
+
286
+ Runs until you stop iterating. The server closes each connection after
287
+ about 55 seconds; the SDK reconnects with the ``since`` it reports, and
288
+ after a dropped connection with the ``received_at`` of the last email, so
289
+ nothing is missed or repeated.
290
+
291
+ Example:
292
+ async for event in client.emails.stream(recipient=inbox.address):
293
+ print(event.email.subject, event.otp and event.otp.code)
294
+ break
295
+
296
+ Args:
297
+ project_id: Project ID (optional with an API key)
298
+ recipient: Only emails to this address
299
+ since: Only emails received strictly after this time (default: now)
300
+ sender: Only emails from this exact sender address
301
+
302
+ Yields:
303
+ StreamEvent with ``email`` (summary, links, text preview) and ``otp``
304
+ """
305
+ pid = await self._context.project_id(project_id)
306
+ path = f"/projects/{pid}/emails/stream"
307
+ cursor: Optional[str] = to_iso(since) if since is not None else None
308
+ # Fallback `since` for a reconnect before any email or `end` arrived.
309
+ started_at = to_iso(datetime.now(timezone.utc))
310
+ seen: "OrderedDict[str, None]" = OrderedDict()
311
+ failures = 0
312
+
313
+ while True:
314
+ ended = False
315
+ error: Optional[ReceiverError] = None
316
+ try:
317
+ async with self._http.stream(
318
+ path, params={"recipient": recipient, "sender": sender, "since": cursor}
319
+ ) as response:
320
+ async for message in iter_sse(response.aiter_lines()):
321
+ if message.event == "email":
322
+ payload = _parse_json(message.data) or {}
323
+ email = payload.get("email")
324
+ if not isinstance(email, dict):
325
+ continue
326
+ failures = 0
327
+ cursor = email.get("receivedAt") or cursor
328
+ event_id = message.id or email.get("id") or ""
329
+ if event_id in seen:
330
+ continue
331
+ seen[event_id] = None
332
+ if len(seen) > 1000:
333
+ seen.popitem(last=False)
334
+ yield StreamEvent.model_validate({**payload, "id": event_id})
335
+ elif message.event == "end":
336
+ payload = _parse_json(message.data) or {}
337
+ cursor = payload.get("since") or cursor
338
+ ended = True
339
+ break
340
+ except ReceiverError as e:
341
+ if not _is_retryable(e):
342
+ raise
343
+ error = e
344
+
345
+ if cursor is None:
346
+ cursor = started_at
347
+ if ended:
348
+ failures = 0
349
+ continue
350
+
351
+ # Error, or connection closed without `end` (proxy cut, deploy):
352
+ # back off, then reconnect from the last email seen.
353
+ failures += 1
354
+ if failures > self._max_reconnect_failures:
355
+ raise error or ReceiverError(
356
+ "Stream closed repeatedly", status_code=0, code="NETWORK_ERROR"
357
+ )
358
+ await asyncio.sleep(min(30.0, self._reconnect_base_delay * 2**failures))
359
+
360
+ async def send_test(self, to: str, project_id: Optional[str] = None) -> SendTestResult:
361
+ """
362
+ Send a test email ("Your Receiver.email test code: 123456") to one of
363
+ the project's addresses. Limited to 10 per project per hour.
364
+
365
+ Args:
366
+ to: An address ending with the project's ``email_suffix``
367
+ project_id: Project ID (optional with an API key)
368
+ """
369
+ pid = await self._context.project_id(project_id)
370
+ data = await self._http.post(f"/projects/{pid}/test-email", json={"to": to})
371
+ return SendTestResult(**data)
372
+
373
+ async def delete(self, project_id: Optional[str], email_id: Optional[str] = None) -> None:
374
+ """
375
+ Delete an email: ``delete(email_id)`` or ``delete(project_id, email_id)``.
376
+
377
+ Args:
378
+ project_id: Project ID (or the email ID when called with one argument)
379
+ email_id: Email ID
380
+ """
381
+ project_id, email_id = _split(project_id, email_id)
382
+ pid = await self._context.project_id(project_id)
383
+ await self._http.delete(f"/projects/{pid}/emails/{quote(email_id, safe='')}")
384
+
385
+ # Convenience methods
386
+
387
+ async def find_by_recipient(
388
+ self,
389
+ project_id: Optional[str],
390
+ recipient: Optional[str] = None,
391
+ limit: int = 50,
392
+ ) -> List[Email]:
393
+ """Find emails by recipient: ``find_by_recipient(value)`` or ``find_by_recipient(project_id, value)``."""
394
+ project_id, recipient = _split(project_id, recipient)
395
+ response = await self.list(project_id, recipient=recipient, limit=limit)
396
+ return response.emails
397
+
398
+ async def find_by_sender(
399
+ self,
400
+ project_id: Optional[str],
401
+ sender: Optional[str] = None,
402
+ limit: int = 50,
403
+ ) -> List[Email]:
404
+ """Find emails by sender: ``find_by_sender(value)`` or ``find_by_sender(project_id, value)``."""
405
+ project_id, sender = _split(project_id, sender)
406
+ response = await self.list(project_id, sender=sender, limit=limit)
407
+ return response.emails
408
+
409
+ async def find_by_subject(
410
+ self,
411
+ project_id: Optional[str],
412
+ subject: Optional[str] = None,
413
+ limit: int = 50,
414
+ ) -> List[Email]:
415
+ """Find emails by subject: ``find_by_subject(value)`` or ``find_by_subject(project_id, value)``."""
416
+ project_id, subject = _split(project_id, subject)
417
+ response = await self.list(project_id, subject=subject, limit=limit)
418
+ return response.emails
419
+
420
+ # Internals
421
+
422
+ async def _poll(
423
+ self,
424
+ path: str,
425
+ filters: Dict[str, Any],
426
+ since: Optional[SinceLike],
427
+ timeout: float,
428
+ hit_status: str,
429
+ legacy_key: str,
430
+ ) -> Dict[str, Any]:
431
+ """
432
+ Repeat server-side waits (at most 60 s each) until a hit or ``timeout``.
433
+
434
+ The ``since`` the server reports on a timeout is reused, so every round
435
+ matches the same window even when the caller did not pass one.
436
+ """
437
+ since_iso = to_iso(since) if since is not None else None
438
+ started = time.monotonic()
439
+ server_waited = 0.0
440
+ first = True
441
+
442
+ while True:
443
+ waited = max(time.monotonic() - started, server_waited)
444
+ remaining = timeout - waited
445
+ if not first and remaining < 1:
446
+ raise ReceiverTimeoutError(
447
+ f"No matching email within {timeout:g}s (since {since_iso})",
448
+ since=since_iso,
449
+ waited_seconds=round(waited, 3),
450
+ )
451
+ first = False
452
+ chunk = min(MAX_SERVER_WAIT_SECONDS, max(0, math.ceil(remaining)))
453
+
454
+ data = await self._http.get(
455
+ path,
456
+ params={**filters, "since": since_iso, "timeout": chunk},
457
+ timeout=chunk + LONG_POLL_GRACE_SECONDS,
458
+ )
459
+
460
+ status = data.get("status") if isinstance(data, dict) else None
461
+ if isinstance(data, dict) and (
462
+ status == hit_status or (status is None and legacy_key in data)
463
+ ):
464
+ return data
465
+
466
+ # Timed out this round
467
+ reported = data.get("waitedSeconds") if isinstance(data, dict) else None
468
+ server_waited += reported if isinstance(reported, (int, float)) and reported > 0 else chunk
469
+ if isinstance(data, dict) and data.get("since"):
470
+ since_iso = data["since"]
471
+
472
+
473
+ def _split(first: Optional[str], second: Optional[str]) -> Tuple[Optional[str], str]:
474
+ """``(project_id, value)`` from either ``(value,)`` or ``(project_id, value)``."""
475
+ if second is None:
476
+ if first is None:
477
+ raise TypeError("missing required argument")
478
+ return None, first
479
+ return first, second
480
+
481
+
482
+ def _is_retryable(error: ReceiverError) -> bool:
483
+ status = error.status_code if error.status_code is not None else 0
484
+ return status in (0, 408, 429) or status >= 500
485
+
486
+
487
+ def _parse_json(text: str) -> Optional[Dict[str, Any]]:
488
+ try:
489
+ value = json.loads(text) if text else None
490
+ except ValueError:
491
+ return None
492
+ return value if isinstance(value, dict) else None
@@ -0,0 +1,37 @@
1
+ """
2
+ Inbox resource operations
3
+ """
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+ from receiverdotemail._context import ProjectContext
8
+ from receiverdotemail.http import HttpClient
9
+ from receiverdotemail.types.inbox import Inbox
10
+
11
+
12
+ class Inboxes:
13
+ """Inbox operations."""
14
+
15
+ def __init__(self, http: HttpClient, context: ProjectContext):
16
+ self._http = http
17
+ self._context = context
18
+
19
+ async def create(self, prefix: Optional[str] = None, project_id: Optional[str] = None) -> Inbox:
20
+ """
21
+ Mint a unique address in the project. Nothing is stored until mail arrives.
22
+
23
+ Args:
24
+ prefix: Optional label (``[a-z0-9._+-]``, 1 to 40 chars). The API appends
25
+ 6 random characters so concurrent callers never collide. Omitted:
26
+ ``inbox-<8 random>``.
27
+ project_id: Project ID (optional with an API key)
28
+
29
+ Returns:
30
+ Inbox with ``address`` and ``created_at`` (pass it as ``since`` when waiting).
31
+ """
32
+ pid = await self._context.project_id(project_id)
33
+ body: Dict[str, Any] = {}
34
+ if prefix is not None:
35
+ body["prefix"] = prefix
36
+ data = await self._http.post(f"/projects/{pid}/inboxes", json=body)
37
+ return Inbox(**data)
@@ -0,0 +1,90 @@
1
+ """
2
+ Organization resource operations
3
+ """
4
+
5
+ from typing import Optional
6
+ from receiverdotemail.http import HttpClient
7
+ from receiverdotemail.types.organization import Organization, OrganizationListResponse
8
+
9
+
10
+ class Organizations:
11
+ """Organization operations."""
12
+
13
+ def __init__(self, http: HttpClient):
14
+ self._http = http
15
+
16
+ async def list(
17
+ self,
18
+ limit: int = 50,
19
+ cursor: Optional[str] = None,
20
+ ) -> OrganizationListResponse:
21
+ """
22
+ List organizations for the authenticated user.
23
+
24
+ Args:
25
+ limit: Number of organizations to return
26
+ cursor: Pagination cursor
27
+
28
+ Returns:
29
+ OrganizationListResponse with organizations and pagination info
30
+ """
31
+ params = {"limit": limit, "cursor": cursor}
32
+ data = await self._http.get("/organizations", params=params)
33
+ return OrganizationListResponse(**data)
34
+
35
+ async def get(self, organization_id: str) -> Organization:
36
+ """
37
+ Get a single organization by ID.
38
+
39
+ Args:
40
+ organization_id: Organization ID
41
+
42
+ Returns:
43
+ Organization object
44
+ """
45
+ data = await self._http.get(f"/organizations/{organization_id}")
46
+ return Organization(**data)
47
+
48
+ async def create(self, name: str, slug: Optional[str] = None) -> Organization:
49
+ """
50
+ Create a new organization.
51
+
52
+ Args:
53
+ name: Organization name
54
+ slug: URL-safe slug (optional)
55
+
56
+ Returns:
57
+ Created organization
58
+ """
59
+ json_data = {"name": name}
60
+ if slug:
61
+ json_data["slug"] = slug
62
+
63
+ data = await self._http.post("/organizations", json=json_data)
64
+ return Organization(**data)
65
+
66
+ async def update(
67
+ self,
68
+ organization_id: str,
69
+ name: Optional[str] = None,
70
+ slug: Optional[str] = None,
71
+ ) -> Organization:
72
+ """
73
+ Update an organization.
74
+
75
+ Args:
76
+ organization_id: Organization ID
77
+ name: New organization name (optional)
78
+ slug: New URL-safe slug (optional)
79
+
80
+ Returns:
81
+ Updated organization
82
+ """
83
+ json_data = {}
84
+ if name:
85
+ json_data["name"] = name
86
+ if slug:
87
+ json_data["slug"] = slug
88
+
89
+ data = await self._http.patch(f"/organizations/{organization_id}", json=json_data)
90
+ return Organization(**data)