mailset 0.7.0__tar.gz

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.
mailset-0.7.0/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ Mailset SDK License
2
+
3
+ Copyright (c) 2026 Intenseloop. All rights reserved.
4
+
5
+ You may use this software, and change it, in your own applications and
6
+ services, including in their builds, images and bundles, to call Mailset's
7
+ API (mailset.app). Nothing else is granted.
8
+
9
+ You may not publish, sell, sublicense or redistribute this software, changed
10
+ or not, on its own or as part of another library, SDK or package, and you may
11
+ not use it with any service other than Mailset.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED. IN NO EVENT SHALL INTENSELOOP BE LIABLE FOR ANY CLAIM, DAMAGES OR
15
+ OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
16
+ ITS USE.
17
+
18
+ Questions and issues: mailset.app/support
mailset-0.7.0/PKG-INFO ADDED
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.5
2
+ Name: mailset
3
+ Version: 0.7.0
4
+ Summary: Mailset's official Python SDK: send mail from your product, verify webhooks, and run every Mailset command.
5
+ Project-URL: Homepage, https://mailset.app
6
+ Project-URL: Documentation, https://mailset.app/docs/sdk
7
+ Project-URL: API, https://mailset.app/docs/api
8
+ Project-URL: Support, https://mailset.app/support
9
+ Author: Intenseloop
10
+ License: Mailset SDK License
11
+
12
+ Copyright (c) 2026 Intenseloop. All rights reserved.
13
+
14
+ You may use this software, and change it, in your own applications and
15
+ services, including in their builds, images and bundles, to call Mailset's
16
+ API (mailset.app). Nothing else is granted.
17
+
18
+ You may not publish, sell, sublicense or redistribute this software, changed
19
+ or not, on its own or as part of another library, SDK or package, and you may
20
+ not use it with any service other than Mailset.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED. IN NO EVENT SHALL INTENSELOOP BE LIABLE FOR ANY CLAIM, DAMAGES OR
24
+ OTHER LIABILITY ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
25
+ ITS USE.
26
+
27
+ Questions and issues: mailset.app/support
28
+ License-File: LICENSE
29
+ Keywords: email,mailset,sdk,smtp,transactional,webhooks
30
+ Classifier: Development Status :: 4 - Beta
31
+ Classifier: Framework :: AsyncIO
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: Other/Proprietary License
34
+ Classifier: Operating System :: OS Independent
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3 :: Only
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Topic :: Communications :: Email
43
+ Classifier: Typing :: Typed
44
+ Requires-Python: >=3.9
45
+ Requires-Dist: cryptography>=3.4
46
+ Requires-Dist: httpx<1,>=0.23
47
+ Requires-Dist: typing-extensions>=4.7; python_version < '3.11'
48
+ Provides-Extra: dev
49
+ Requires-Dist: django-stubs>=4.2; extra == 'dev'
50
+ Requires-Dist: django>=4.2; extra == 'dev'
51
+ Requires-Dist: fastapi>=0.100; extra == 'dev'
52
+ Requires-Dist: flask>=2.2; extra == 'dev'
53
+ Requires-Dist: mypy>=1.8; extra == 'dev'
54
+ Requires-Dist: pytest>=7.4; extra == 'dev'
55
+ Description-Content-Type: text/markdown
56
+
57
+ # Mailset for Python
58
+
59
+ Mailset's official Python SDK. It sends mail from your product, verifies your hook's webhooks, and calls every Mailset command. `Mailset` is the sync client and `AsyncMailset` the asyncio one. Python 3.9 or later.
60
+
61
+ ```sh
62
+ pip install mailset
63
+ ```
64
+
65
+ ```python
66
+ from mailset import Mailset
67
+
68
+ mailset = Mailset() # reads MAILSET_KEY from the environment
69
+ sent = mailset.send({"from": "Acme <hello@example.com>", "to": "ana@example.com", "subject": "Your code", "text": "Your code is 123456."})
70
+ print(sent["id"], sent["status"])
71
+ ```
72
+
73
+ `MAILSET_KEY` comes from `npx @mailset/cli keys create --send --mailbox <address>`.
74
+
75
+ Every input and answer is a typed dict. Its keys are the API's field names in snake_case, such as `idempotency_key` and `message_id`, and `from` stays `from`. `import` is a Python keyword, so `contacts.import` and `rules.import` are `import_contacts` and `import_rules`.
76
+
77
+ - SDK guide: https://mailset.app/docs/sdk
78
+ - API reference: https://mailset.app/docs/api
79
+
80
+ Questions and issues: mailset.app/support
@@ -0,0 +1,24 @@
1
+ # Mailset for Python
2
+
3
+ Mailset's official Python SDK. It sends mail from your product, verifies your hook's webhooks, and calls every Mailset command. `Mailset` is the sync client and `AsyncMailset` the asyncio one. Python 3.9 or later.
4
+
5
+ ```sh
6
+ pip install mailset
7
+ ```
8
+
9
+ ```python
10
+ from mailset import Mailset
11
+
12
+ mailset = Mailset() # reads MAILSET_KEY from the environment
13
+ sent = mailset.send({"from": "Acme <hello@example.com>", "to": "ana@example.com", "subject": "Your code", "text": "Your code is 123456."})
14
+ print(sent["id"], sent["status"])
15
+ ```
16
+
17
+ `MAILSET_KEY` comes from `npx @mailset/cli keys create --send --mailbox <address>`.
18
+
19
+ Every input and answer is a typed dict. Its keys are the API's field names in snake_case, such as `idempotency_key` and `message_id`, and `from` stays `from`. `import` is a Python keyword, so `contacts.import` and `rules.import` are `import_contacts` and `import_rules`.
20
+
21
+ - SDK guide: https://mailset.app/docs/sdk
22
+ - API reference: https://mailset.app/docs/api
23
+
24
+ Questions and issues: mailset.app/support
@@ -0,0 +1,72 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.18"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mailset"
7
+ version = "0.7.0"
8
+ description = "Mailset's official Python SDK: send mail from your product, verify webhooks, and run every Mailset command."
9
+ readme = "README.md"
10
+ license = { file = "LICENSE" }
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "Intenseloop" }]
13
+ keywords = ["mailset", "email", "smtp", "transactional", "webhooks", "sdk"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Framework :: AsyncIO",
17
+ "Intended Audience :: Developers",
18
+ "License :: Other/Proprietary License",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Communications :: Email",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = [
31
+ "httpx>=0.23,<1",
32
+ "cryptography>=3.4",
33
+ "typing_extensions>=4.7; python_version < '3.11'",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ dev = [
38
+ "pytest>=7.4",
39
+ "mypy>=1.8",
40
+ "fastapi>=0.100",
41
+ "django>=4.2",
42
+ "django-stubs>=4.2",
43
+ "flask>=2.2",
44
+ ]
45
+
46
+ [project.urls]
47
+ Homepage = "https://mailset.app"
48
+ Documentation = "https://mailset.app/docs/sdk"
49
+ API = "https://mailset.app/docs/api"
50
+ Support = "https://mailset.app/support"
51
+
52
+ [tool.hatch.build.targets.wheel]
53
+ packages = ["src/mailset"]
54
+
55
+ [tool.hatch.build.targets.sdist]
56
+ include = ["src/mailset", "README.md", "LICENSE", "pyproject.toml"]
57
+
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["tests"]
60
+ addopts = "-ra"
61
+ # Starlette's TestClient (for the FastAPI example's test) asks for httpx2.
62
+ filterwarnings = ["ignore:Using `httpx` with `starlette.testclient`"]
63
+
64
+ [tool.mypy]
65
+ files = ["src/mailset", "examples"]
66
+ python_version = "3.10"
67
+ strict = true
68
+ warn_unreachable = true
69
+
70
+ [[tool.mypy.overrides]]
71
+ module = ["mailset._resources"]
72
+ warn_return_any = false
@@ -0,0 +1,121 @@
1
+ """Mailset for a product's server: send mail from a mailbox your app was
2
+ granted, verify your hook's webhooks, and run any of Mailset's public
3
+ commands.
4
+
5
+ ``MAILSET_KEY`` comes from ``mailset keys create --send --mailbox <address>``,
6
+ approved with a passkey, and can send only as that mailbox. ``MAILSET_TOKEN``,
7
+ an API token from ``mailset tokens create``, is a person's, and runs what
8
+ they may::
9
+
10
+ from mailset import Mailset
11
+
12
+ mailset = Mailset() # MAILSET_KEY, else MAILSET_TOKEN, from the environment
13
+ sent = mailset.send({
14
+ "from": "Acme <hello@example.com>",
15
+ "to": "ana@example.com",
16
+ "subject": "Your code",
17
+ "text": "Your code is 123456.",
18
+ })
19
+
20
+ Every input and answer is a ``TypedDict``: a plain dict whose keys are the
21
+ API's fields in snake_case (``from`` stays ``from``). Every command's types
22
+ are in ``mailset.types``. The one method named otherwise is ``import``, a
23
+ Python keyword: ``contacts.import_contacts`` and ``rules.import_rules``.
24
+
25
+ Docs: https://mailset.app/docs/sdk and https://mailset.app/docs/api.
26
+ """
27
+
28
+ from . import types, webhooks
29
+ from ._client import AsyncMailset, Mailset
30
+ from ._convert import from_api, to_api
31
+ from ._core import Approval
32
+ from ._errors import (
33
+ APIConnectionError,
34
+ APITimeoutError,
35
+ AuthenticationError,
36
+ ConflictError,
37
+ InvalidRequestError,
38
+ Issue,
39
+ MailsetError,
40
+ NotFoundError,
41
+ PasskeyPurpose,
42
+ PasskeyRequiredError,
43
+ PermissionDeniedError,
44
+ RateLimitError,
45
+ ServerError,
46
+ )
47
+ from ._handwritten import (
48
+ CampaignMessage,
49
+ CampaignSubmitInput,
50
+ DeliveryLine,
51
+ DeliveryPage,
52
+ DeliverySearchInput,
53
+ DeliveryStatus,
54
+ SendingSubmitInput,
55
+ Track,
56
+ )
57
+ from ._message import (
58
+ Address,
59
+ Attachment,
60
+ BuiltMessage,
61
+ NamedAddress,
62
+ Recipients,
63
+ SendInput,
64
+ build_message,
65
+ read_attachment,
66
+ )
67
+ from ._platform import MailsetUpgradeWarning
68
+ from ._resources import SDK_VERSION
69
+ from ._send import NotSent, SendResult, Sent, Skipped
70
+ from .types import DeliveryClient, KeyStatus
71
+ from .webhooks import MailEvent
72
+
73
+ __version__ = SDK_VERSION
74
+
75
+ __all__ = [
76
+ "APIConnectionError",
77
+ "APITimeoutError",
78
+ "Address",
79
+ "Approval",
80
+ "AsyncMailset",
81
+ "Attachment",
82
+ "AuthenticationError",
83
+ "BuiltMessage",
84
+ "CampaignMessage",
85
+ "CampaignSubmitInput",
86
+ "ConflictError",
87
+ "DeliveryClient",
88
+ "DeliveryLine",
89
+ "DeliveryPage",
90
+ "DeliverySearchInput",
91
+ "DeliveryStatus",
92
+ "InvalidRequestError",
93
+ "Issue",
94
+ "KeyStatus",
95
+ "MailEvent",
96
+ "Mailset",
97
+ "MailsetError",
98
+ "MailsetUpgradeWarning",
99
+ "NamedAddress",
100
+ "NotFoundError",
101
+ "NotSent",
102
+ "PasskeyPurpose",
103
+ "PasskeyRequiredError",
104
+ "PermissionDeniedError",
105
+ "RateLimitError",
106
+ "Recipients",
107
+ "SendInput",
108
+ "SendResult",
109
+ "SendingSubmitInput",
110
+ "Sent",
111
+ "ServerError",
112
+ "Skipped",
113
+ "Track",
114
+ "__version__",
115
+ "build_message",
116
+ "from_api",
117
+ "read_attachment",
118
+ "to_api",
119
+ "types",
120
+ "webhooks",
121
+ ]
@@ -0,0 +1,54 @@
1
+ """What every group of the client is: a handle on the client's core."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Mapping, Optional
6
+
7
+ if TYPE_CHECKING:
8
+ from ._core import AsyncCore, SyncCore
9
+
10
+ __all__ = ["AsyncGroup", "SyncGroup"]
11
+
12
+
13
+ class SyncGroup:
14
+ """A group of ``Mailset``'s commands, such as ``mailset.domains``."""
15
+
16
+ def __init__(self, core: SyncCore) -> None:
17
+ self._core = core
18
+
19
+ def __repr__(self) -> str:
20
+ return f"<{type(self).__name__}>"
21
+
22
+ def _call(
23
+ self,
24
+ command: str,
25
+ params: Optional[Mapping[str, Any]],
26
+ given: str,
27
+ answer: str,
28
+ org: Optional[str],
29
+ approval: Optional[str],
30
+ timeout: Optional[float],
31
+ ) -> Any:
32
+ return self._core.command(command, params, given, answer, org, approval, timeout)
33
+
34
+
35
+ class AsyncGroup:
36
+ """A group of ``AsyncMailset``'s commands, such as ``mailset.domains``."""
37
+
38
+ def __init__(self, core: AsyncCore) -> None:
39
+ self._core = core
40
+
41
+ def __repr__(self) -> str:
42
+ return f"<{type(self).__name__}>"
43
+
44
+ async def _call(
45
+ self,
46
+ command: str,
47
+ params: Optional[Mapping[str, Any]],
48
+ given: str,
49
+ answer: str,
50
+ org: Optional[str],
51
+ approval: Optional[str],
52
+ timeout: Optional[float],
53
+ ) -> Any:
54
+ return await self._core.command(command, params, given, answer, org, approval, timeout)
@@ -0,0 +1,309 @@
1
+ """``Mailset`` and ``AsyncMailset``: a client for one credential."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import TracebackType
6
+ from typing import (
7
+ Any,
8
+ Awaitable,
9
+ Callable,
10
+ List,
11
+ Mapping,
12
+ Optional,
13
+ Sequence,
14
+ Type,
15
+ Union,
16
+ overload,
17
+ )
18
+
19
+ import httpx
20
+
21
+ from ._convert import to_wire
22
+ from ._core import Approval, AsyncCore, SyncCore
23
+ from ._credentials import credential_from
24
+ from ._errors import MailsetError
25
+ from ._handwritten import Approvals, AsyncApprovals, AsyncKey, Key
26
+ from ._message import SendInput
27
+ from ._resources import AsyncMailsetCommands, MailsetCommands
28
+ from ._send import Batch, SendResult, Sent, one, results_of, submit_input
29
+ from .webhooks import Webhooks
30
+
31
+ __all__ = ["AsyncMailset", "Mailset"]
32
+
33
+ def _many(message: Any) -> bool:
34
+ return isinstance(message, (list, tuple))
35
+
36
+
37
+ class Mailset(MailsetCommands):
38
+ """A client for one credential: send mail, and run any of Mailset's
39
+ public commands, grouped as the API is (``mailset.domains.add``,
40
+ ``mailset.threads.list``). Nothing is sent until you call a method.
41
+
42
+ With nothing given, it reads ``MAILSET_KEY``, else ``MAILSET_TOKEN``,
43
+ from the environment::
44
+
45
+ mailset = Mailset()
46
+ mailset.send({"from": "Acme <hello@example.com>", "to": "ana@example.com",
47
+ "subject": "Your code", "text": "Your code is 123456."})
48
+
49
+ One client serves a whole server, threads included. ``close()`` it (or
50
+ use it as a context manager) when you're done with it.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ key: Optional[str] = None,
56
+ token: Optional[str] = None,
57
+ *,
58
+ base_url: Optional[str] = None,
59
+ org: Optional[str] = None,
60
+ timeout: Optional[float] = None,
61
+ max_retries: Optional[int] = None,
62
+ on_approval: Optional[Callable[[Approval], None]] = None,
63
+ http_client: Optional[httpx.Client] = None,
64
+ clock: Optional[Callable[[], float]] = None,
65
+ ) -> None:
66
+ """
67
+ Args:
68
+ key: ``MAILSET_KEY`` (``msk1_…``), an app key, from ``mailset keys
69
+ create --send --mailbox <address>``: sends as the mailboxes its
70
+ grant names. An API token works here too.
71
+ token: ``MAILSET_TOKEN`` (``mst_…``), an API token, from ``mailset
72
+ tokens create``: a person's, for the commands no app key can
73
+ run, such as ``domains.add``.
74
+ base_url: Where Mailset is. Else ``MAILSET_API``, else the key's
75
+ own, else ``https://mailset.app``.
76
+ org: The org a command is about, for a person in more than one.
77
+ Each call may name another.
78
+ timeout: Seconds one try of a call may take, 30 unless told. A
79
+ try that runs out is tried again; when the last one does,
80
+ the call raises ``APITimeoutError``.
81
+ max_retries: How many times a call is tried again after a network
82
+ failure (no answer, a dropped connection, a reset), a timeout
83
+ or a 5xx, waiting ``min(8, 0.5 * 2**try)`` seconds with jitter,
84
+ or what ``Retry-After`` asks (20 at most). 2 unless told; 0
85
+ never. A 4xx is never tried again. Each try sends the same
86
+ bytes, so a send keeps its Message-ID and Mailset sends it
87
+ once, even with no ``idempotency_key``.
88
+ on_approval: Called when a command needs a passkey, with the
89
+ ``Approval`` to hand to whoever approves (its ``"url"``). The
90
+ call goes on once they do. Without it, such a command raises
91
+ ``PasskeyRequiredError`` with the ``purpose`` to approve.
92
+ http_client: Your own ``httpx.Client``, for a proxy or tests. Yours
93
+ to close.
94
+ clock: The clock every call is signed with, as ``time.time``.
95
+ Only tests change it.
96
+ """
97
+ core = SyncCore(
98
+ credential_from(key, token),
99
+ http_client=http_client,
100
+ base_url=base_url,
101
+ org=org,
102
+ timeout=timeout,
103
+ max_retries=max_retries,
104
+ on_approval=on_approval,
105
+ clock=clock,
106
+ )
107
+ super().__init__(core)
108
+ self.key = Key(core)
109
+ """This client's key: ``mailset.key.check()`` keeps it alive."""
110
+ self.approvals = Approvals(core)
111
+ """Approvals for commands that need a passkey."""
112
+ self.webhooks = Webhooks()
113
+ """Events from your org's hook: the same ``verify`` as ``mailset.webhooks``."""
114
+
115
+ def __repr__(self) -> str:
116
+ return f"Mailset({self._core.credential.name}, base_url={self._core.base_url!r})"
117
+
118
+ def close(self) -> None:
119
+ """Closes its connections (unless the ``http_client`` was yours)."""
120
+ self._core.close()
121
+
122
+ def __enter__(self) -> Mailset:
123
+ return self
124
+
125
+ def __exit__(
126
+ self,
127
+ kind: Optional[Type[BaseException]],
128
+ value: Optional[BaseException],
129
+ traceback: Optional[TracebackType],
130
+ ) -> None:
131
+ self.close()
132
+
133
+ @overload
134
+ def send(self, message: SendInput, /) -> Sent: ...
135
+
136
+ @overload
137
+ def send(self, message: Sequence[SendInput], /) -> List[SendResult]: ...
138
+
139
+ def send(
140
+ self, message: Union[SendInput, Sequence[SendInput]], /
141
+ ) -> Union[Sent, List[SendResult]]:
142
+ """Sends mail from a mailbox this key may send as.
143
+
144
+ One message, a ``SendInput`` dict, answers its ``Sent`` receipt, or
145
+ raises the ``MailsetError`` Mailset refused it with. A list of them
146
+ answers one ``Sent`` or ``NotSent`` each, in the same order, with
147
+ ``ok`` saying which went: a refusal is that message's ``error`` and
148
+ never stops the rest. A list raises only when the key is refused,
149
+ Mailset can't be reached before anything was taken, or two messages
150
+ carry the same ``idempotency_key`` from the same address
151
+ (``invalid_input``, before anything is sent). Any number goes: past
152
+ 100, or 48 MB, they go in several calls.
153
+
154
+ Mail to an Apple Hide My Email address or a temporary inbox, and
155
+ promotional mail to someone who unsubscribed, isn't refused: the
156
+ receipt's ``skipped`` names each one, and it goes to everyone else.
157
+
158
+ Args:
159
+ message: ``{"from": …, "to": …, "subject": …, "text": …}``, and
160
+ any other key of ``SendInput``; or a list of them.
161
+ """
162
+ if _many(message):
163
+ return self._send_many(message) # type: ignore[arg-type]
164
+ return one(self._send_many([message], single=True))
165
+
166
+
167
+ def _send_many(self, messages: Sequence[Any], single: bool = False) -> List[SendResult]:
168
+ batch = Batch(messages, self._core.now_ms())
169
+ first = batch.results[0] if single and batch.results else None
170
+ if first is not None and first["ok"] is False:
171
+ raise first["error"]
172
+ for chunk in batch.chunks:
173
+ built = [item for _index, item in chunk]
174
+ try:
175
+ data = self._core.call("messages.submitMany", submit_input(built))
176
+ batch.took(chunk, results_of(data, built))
177
+ except MailsetError as failure:
178
+ if single:
179
+ raise
180
+ batch.failed(chunk, failure)
181
+ return batch.answer()
182
+
183
+ def request(
184
+ self,
185
+ command: str,
186
+ input: Optional[Mapping[str, Any]] = None,
187
+ *,
188
+ org: Optional[str] = None,
189
+ approval: Optional[str] = None,
190
+ timeout: Optional[float] = None,
191
+ ) -> Any:
192
+ """Any command by its id, with its input as Mailset takes it
193
+ (camelCase): for one this SDK has no method for yet. Answers its
194
+ ``data``, as plain JSON."""
195
+ return self._core.call(
196
+ command, to_wire("", dict(input or {})), org=org, approval=approval, timeout=timeout
197
+ )
198
+
199
+
200
+ class AsyncMailset(AsyncMailsetCommands):
201
+ """``Mailset`` for asyncio: the same groups and methods, each one a
202
+ coroutine. With nothing given, it reads ``MAILSET_KEY``, else
203
+ ``MAILSET_TOKEN``, from the environment::
204
+
205
+ mailset = AsyncMailset()
206
+ await mailset.send({"from": "Acme <hello@example.com>", "to": "ana@example.com",
207
+ "subject": "Your code", "text": "Your code is 123456."})
208
+
209
+ ``await mailset.aclose()`` (or ``async with``) when you're done with it.
210
+ """
211
+
212
+ def __init__(
213
+ self,
214
+ key: Optional[str] = None,
215
+ token: Optional[str] = None,
216
+ *,
217
+ base_url: Optional[str] = None,
218
+ org: Optional[str] = None,
219
+ timeout: Optional[float] = None,
220
+ max_retries: Optional[int] = None,
221
+ on_approval: Optional[Callable[[Approval], Union[None, Awaitable[None]]]] = None,
222
+ http_client: Optional[httpx.AsyncClient] = None,
223
+ clock: Optional[Callable[[], float]] = None,
224
+ ) -> None:
225
+ """Takes what ``Mailset`` takes; ``http_client`` is an
226
+ ``httpx.AsyncClient``, and ``on_approval`` may be a coroutine."""
227
+ core = AsyncCore(
228
+ credential_from(key, token),
229
+ http_client=http_client,
230
+ base_url=base_url,
231
+ org=org,
232
+ timeout=timeout,
233
+ max_retries=max_retries,
234
+ on_approval=on_approval,
235
+ clock=clock,
236
+ )
237
+ super().__init__(core)
238
+ self.key = AsyncKey(core)
239
+ """This client's key: ``await mailset.key.check()`` keeps it alive."""
240
+ self.approvals = AsyncApprovals(core)
241
+ """Approvals for commands that need a passkey."""
242
+ self.webhooks = Webhooks()
243
+ """Events from your org's hook: the same ``verify`` as ``mailset.webhooks``."""
244
+
245
+ def __repr__(self) -> str:
246
+ return f"AsyncMailset({self._core.credential.name}, base_url={self._core.base_url!r})"
247
+
248
+ async def aclose(self) -> None:
249
+ """Closes its connections (unless the ``http_client`` was yours)."""
250
+ await self._core.close()
251
+
252
+ async def __aenter__(self) -> AsyncMailset:
253
+ return self
254
+
255
+ async def __aexit__(
256
+ self,
257
+ kind: Optional[Type[BaseException]],
258
+ value: Optional[BaseException],
259
+ traceback: Optional[TracebackType],
260
+ ) -> None:
261
+ await self.aclose()
262
+
263
+ @overload
264
+ async def send(self, message: SendInput, /) -> Sent: ...
265
+
266
+ @overload
267
+ async def send(self, message: Sequence[SendInput], /) -> List[SendResult]: ...
268
+
269
+ async def send(
270
+ self, message: Union[SendInput, Sequence[SendInput]], /
271
+ ) -> Union[Sent, List[SendResult]]:
272
+ """Sends mail from a mailbox this key may send as: one ``SendInput``
273
+ dict answers its ``Sent`` receipt, a list of them a result each. See
274
+ ``Mailset.send``."""
275
+ if _many(message):
276
+ return await self._send_many(message) # type: ignore[arg-type]
277
+ return one(await self._send_many([message], single=True))
278
+
279
+
280
+ async def _send_many(self, messages: Sequence[Any], single: bool = False) -> List[SendResult]:
281
+ batch = Batch(messages, self._core.now_ms())
282
+ first = batch.results[0] if single and batch.results else None
283
+ if first is not None and first["ok"] is False:
284
+ raise first["error"]
285
+ for chunk in batch.chunks:
286
+ built = [item for _index, item in chunk]
287
+ try:
288
+ data = await self._core.call("messages.submitMany", submit_input(built))
289
+ batch.took(chunk, results_of(data, built))
290
+ except MailsetError as failure:
291
+ if single:
292
+ raise
293
+ batch.failed(chunk, failure)
294
+ return batch.answer()
295
+
296
+ async def request(
297
+ self,
298
+ command: str,
299
+ input: Optional[Mapping[str, Any]] = None,
300
+ *,
301
+ org: Optional[str] = None,
302
+ approval: Optional[str] = None,
303
+ timeout: Optional[float] = None,
304
+ ) -> Any:
305
+ """Any command by its id, with its input as Mailset takes it
306
+ (camelCase). Answers its ``data``, as plain JSON."""
307
+ return await self._core.call(
308
+ command, to_wire("", dict(input or {})), org=org, approval=approval, timeout=timeout
309
+ )