agenticemail 0.1.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.
@@ -0,0 +1,21 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ python-version: ["3.9", "3.12"]
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: ${{ matrix.python-version }}
19
+ - run: pip install -e ".[events,langchain]" build
20
+ - run: python tests/test_langchain.py
21
+ - run: python -m build
@@ -0,0 +1,22 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ publish:
10
+ runs-on: ubuntu-latest
11
+ environment: pypi
12
+ permissions:
13
+ id-token: write
14
+ contents: read
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.12"
20
+ - run: python -m pip install build
21
+ - run: python -m build
22
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ *.pyc
3
+ dist/
4
+ *.egg-info/
5
+ .venv/
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ Initial public release.
6
+
7
+ - `AgenticEmail` client covering inboxes, messages (send, batch, reply, forward, search, attachments, raw), threads, drafts (including scheduled send), allow/block lists, webhooks, domains, and API keys
8
+ - Real-time event stream over WebSocket (`client.events.stream`, `events` extra)
9
+ - `verify_webhook` HMAC signature verification helper
10
+ - LangChain toolkit (`agenticemail.langchain.AgenticEmailToolkit`, `langchain` extra)
11
+ - Type-annotated with `py.typed`; single runtime dependency (`httpx`)
@@ -0,0 +1,14 @@
1
+ # Contributing
2
+
3
+ Thanks for your interest in the AgenticEmail Python SDK.
4
+
5
+ This repository is an exported snapshot of the SDK developed in the AgenticEmail monorepo, so pull requests may be ported rather than merged directly. Issues and PRs are welcome either way.
6
+
7
+ ## Development
8
+
9
+ ```bash
10
+ pip install -e ".[events,langchain]"
11
+ python tests/test_langchain.py
12
+ ```
13
+
14
+ Please keep changes small and include a test when you fix a bug.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 AgenticEmail
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.4
2
+ Name: agenticemail
3
+ Version: 0.1.0
4
+ Summary: Python SDK for AgenticEmail — API-first email for AI agents.
5
+ Project-URL: Homepage, https://agenticemail.dev
6
+ Project-URL: Repository, https://github.com/AgenticEmail/agenticemail-python
7
+ Project-URL: Documentation, https://agenticemail.dev/docs
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.9
11
+ Requires-Dist: httpx>=0.27
12
+ Provides-Extra: events
13
+ Requires-Dist: websocket-client>=1.6; extra == 'events'
14
+ Provides-Extra: langchain
15
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # AgenticEmail Python SDK
19
+
20
+ The official Python library for the [AgenticEmail](https://agenticemail.dev) API — programmatic inboxes, send and receive email, webhooks, and real-time events for AI agents.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ pip install agenticemail
26
+ # publishing to PyPI is in progress — until then, install from GitHub:
27
+ pip install git+https://github.com/AgenticEmail/agenticemail-python.git
28
+ ```
29
+
30
+ Optional extras: `agenticemail[events]` (WebSocket event stream), `agenticemail[langchain]` (LangChain toolkit).
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ import os
36
+ from agenticemail import AgenticEmail
37
+
38
+ client = AgenticEmail(api_key=os.environ["AGENTICEMAIL_API_KEY"])
39
+
40
+ # Give your agent an inbox in one call
41
+ inbox = client.inboxes.create(username="support", domain="acme.io")
42
+
43
+ # Send
44
+ client.messages.send(
45
+ inbox["id"],
46
+ to=["customer@example.com"],
47
+ subject="Hello",
48
+ text="Sent from an agent.",
49
+ )
50
+
51
+ # Read
52
+ threads = client.threads.list(inbox["id"])
53
+ ```
54
+
55
+ Responses are plain dicts in the API's snake_case. Get an API key from the [dashboard](https://app.agenticemail.dev/keys).
56
+
57
+ ## Real-time events
58
+
59
+ Requires the `events` extra (`websocket-client`):
60
+
61
+ ```python
62
+ for event in client.events.stream(event_types=["message.received"]):
63
+ print(event["type"], event["data"])
64
+ ```
65
+
66
+ ## Webhook verification
67
+
68
+ ```python
69
+ from agenticemail import verify_webhook
70
+
71
+ event = verify_webhook(raw_body, request.headers, os.environ["WEBHOOK_SECRET"])
72
+ if event["type"] == "message.received":
73
+ ...
74
+ ```
75
+
76
+ `verify_webhook` raises `AgenticEmailError` when the signature is invalid.
77
+
78
+ ## LangChain toolkit
79
+
80
+ ```python
81
+ from agenticemail.langchain import AgenticEmailToolkit
82
+
83
+ tools = AgenticEmailToolkit.from_api_key().get_tools() # reads AGENTICEMAIL_API_KEY
84
+ ```
85
+
86
+ ## Error handling
87
+
88
+ All non-2xx responses raise `AgenticEmailError` with `.status`, `.code`, and a message:
89
+
90
+ ```python
91
+ from agenticemail import AgenticEmailError
92
+
93
+ try:
94
+ client.inboxes.get("missing")
95
+ except AgenticEmailError as err:
96
+ print(err.status, err.code)
97
+ ```
98
+
99
+ ## Self-hosted
100
+
101
+ ```python
102
+ client = AgenticEmail(api_key="am_...", base_url="https://your-agenticemail-host")
103
+ ```
104
+
105
+ ## API surface
106
+
107
+ See [api.md](./api.md) for every resource and method: `inboxes`, `messages`, `threads`, `drafts`, `lists`, `webhooks`, `domains`, `api_keys`, `events`.
108
+
109
+ ## Requirements
110
+
111
+ Python 3.9+. Fully type-annotated (`py.typed`).
112
+
113
+ ## Contributing
114
+
115
+ See [CONTRIBUTING.md](./CONTRIBUTING.md). This repo is an exported snapshot of the SDK developed in the AgenticEmail monorepo.
116
+
117
+ ## License
118
+
119
+ [Apache-2.0](./LICENSE)
@@ -0,0 +1,102 @@
1
+ # AgenticEmail Python SDK
2
+
3
+ The official Python library for the [AgenticEmail](https://agenticemail.dev) API — programmatic inboxes, send and receive email, webhooks, and real-time events for AI agents.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install agenticemail
9
+ # publishing to PyPI is in progress — until then, install from GitHub:
10
+ pip install git+https://github.com/AgenticEmail/agenticemail-python.git
11
+ ```
12
+
13
+ Optional extras: `agenticemail[events]` (WebSocket event stream), `agenticemail[langchain]` (LangChain toolkit).
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ import os
19
+ from agenticemail import AgenticEmail
20
+
21
+ client = AgenticEmail(api_key=os.environ["AGENTICEMAIL_API_KEY"])
22
+
23
+ # Give your agent an inbox in one call
24
+ inbox = client.inboxes.create(username="support", domain="acme.io")
25
+
26
+ # Send
27
+ client.messages.send(
28
+ inbox["id"],
29
+ to=["customer@example.com"],
30
+ subject="Hello",
31
+ text="Sent from an agent.",
32
+ )
33
+
34
+ # Read
35
+ threads = client.threads.list(inbox["id"])
36
+ ```
37
+
38
+ Responses are plain dicts in the API's snake_case. Get an API key from the [dashboard](https://app.agenticemail.dev/keys).
39
+
40
+ ## Real-time events
41
+
42
+ Requires the `events` extra (`websocket-client`):
43
+
44
+ ```python
45
+ for event in client.events.stream(event_types=["message.received"]):
46
+ print(event["type"], event["data"])
47
+ ```
48
+
49
+ ## Webhook verification
50
+
51
+ ```python
52
+ from agenticemail import verify_webhook
53
+
54
+ event = verify_webhook(raw_body, request.headers, os.environ["WEBHOOK_SECRET"])
55
+ if event["type"] == "message.received":
56
+ ...
57
+ ```
58
+
59
+ `verify_webhook` raises `AgenticEmailError` when the signature is invalid.
60
+
61
+ ## LangChain toolkit
62
+
63
+ ```python
64
+ from agenticemail.langchain import AgenticEmailToolkit
65
+
66
+ tools = AgenticEmailToolkit.from_api_key().get_tools() # reads AGENTICEMAIL_API_KEY
67
+ ```
68
+
69
+ ## Error handling
70
+
71
+ All non-2xx responses raise `AgenticEmailError` with `.status`, `.code`, and a message:
72
+
73
+ ```python
74
+ from agenticemail import AgenticEmailError
75
+
76
+ try:
77
+ client.inboxes.get("missing")
78
+ except AgenticEmailError as err:
79
+ print(err.status, err.code)
80
+ ```
81
+
82
+ ## Self-hosted
83
+
84
+ ```python
85
+ client = AgenticEmail(api_key="am_...", base_url="https://your-agenticemail-host")
86
+ ```
87
+
88
+ ## API surface
89
+
90
+ See [api.md](./api.md) for every resource and method: `inboxes`, `messages`, `threads`, `drafts`, `lists`, `webhooks`, `domains`, `api_keys`, `events`.
91
+
92
+ ## Requirements
93
+
94
+ Python 3.9+. Fully type-annotated (`py.typed`).
95
+
96
+ ## Contributing
97
+
98
+ See [CONTRIBUTING.md](./CONTRIBUTING.md). This repo is an exported snapshot of the SDK developed in the AgenticEmail monorepo.
99
+
100
+ ## License
101
+
102
+ [Apache-2.0](./LICENSE)
@@ -0,0 +1,5 @@
1
+ # Security policy
2
+
3
+ Please report security vulnerabilities privately to **hello@agenticemail.dev**. Do not open public issues for security reports.
4
+
5
+ We will acknowledge your report within a few business days.
@@ -0,0 +1,377 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ from typing import Any, Optional
6
+ from urllib.parse import quote
7
+
8
+ import httpx
9
+
10
+ __all__ = [
11
+ "AgenticEmail",
12
+ "AgenticEmailError",
13
+ "AgentMail",
14
+ "AgentMailError",
15
+ "verify_webhook",
16
+ ]
17
+
18
+
19
+ class AgenticEmailError(Exception):
20
+ def __init__(self, status: int, code: str, message: str):
21
+ super().__init__(message)
22
+ self.status = status
23
+ self.code = code
24
+
25
+
26
+ def _clean(data: Optional[dict]) -> Optional[dict]:
27
+ if data is None:
28
+ return None
29
+ return {k: v for k, v in data.items() if v is not None}
30
+
31
+
32
+ def _enc(inbox_id: str) -> str:
33
+ return quote(inbox_id, safe="")
34
+
35
+
36
+ class AgenticEmail:
37
+ def __init__(self, api_key: str, base_url: str = "https://app.agenticemail.dev"):
38
+ self._api_key = api_key
39
+ self._base_url = base_url.rstrip("/")
40
+ self._http = httpx.Client(
41
+ base_url=self._base_url,
42
+ headers={"Authorization": f"Bearer {api_key}"},
43
+ timeout=30.0,
44
+ )
45
+ self.inboxes = _Inboxes(self)
46
+ self.messages = _Messages(self)
47
+ self.threads = _Threads(self)
48
+ self.drafts = _Drafts(self)
49
+ self.webhooks = _Webhooks(self)
50
+ self.domains = _Domains(self)
51
+ self.api_keys = _ApiKeys(self)
52
+ self.lists = _Lists(self)
53
+ self.events = _Events(self)
54
+
55
+ def _request(
56
+ self,
57
+ method: str,
58
+ path: str,
59
+ *,
60
+ params: Optional[dict] = None,
61
+ json_body: Optional[dict] = None,
62
+ raw: bool = False,
63
+ binary: bool = False,
64
+ ) -> Any:
65
+ res = self._http.request(method, path, params=_clean(params), json=json_body)
66
+ if res.status_code >= 400:
67
+ code, message = "error", f"HTTP {res.status_code}"
68
+ try:
69
+ err = res.json()["error"]
70
+ code, message = err["code"], err["message"]
71
+ except Exception:
72
+ pass
73
+ raise AgenticEmailError(res.status_code, code, message)
74
+ if res.status_code == 204:
75
+ return None
76
+ if raw:
77
+ return res.text
78
+ if binary:
79
+ return res.content
80
+ return res.json()
81
+
82
+
83
+ class _Inboxes:
84
+ def __init__(self, c: AgenticEmail):
85
+ self._c = c
86
+
87
+ def create(self, username=None, domain=None, display_name=None, client_id=None):
88
+ return self._c._request(
89
+ "POST",
90
+ "/v1/inboxes",
91
+ json_body=_clean(
92
+ {"username": username, "domain": domain, "display_name": display_name, "client_id": client_id}
93
+ ),
94
+ )
95
+
96
+ def list(self, limit=None, page_token=None):
97
+ return self._c._request("GET", "/v1/inboxes", params={"limit": limit, "page_token": page_token})
98
+
99
+ def get(self, inbox_id: str):
100
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}")
101
+
102
+ def update(self, inbox_id: str, display_name):
103
+ return self._c._request("PATCH", f"/v1/inboxes/{_enc(inbox_id)}", json_body={"display_name": display_name})
104
+
105
+ def delete(self, inbox_id: str):
106
+ return self._c._request("DELETE", f"/v1/inboxes/{_enc(inbox_id)}")
107
+
108
+
109
+ class _Messages:
110
+ def __init__(self, c: AgenticEmail):
111
+ self._c = c
112
+
113
+ def list(self, inbox_id: str, **filters):
114
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}/messages", params=filters)
115
+
116
+ def search(self, inbox_id: str, q=None, **filters):
117
+ return self._c._request(
118
+ "GET", f"/v1/inboxes/{_enc(inbox_id)}/messages/search", params={"q": q, **filters}
119
+ )
120
+
121
+ def get(self, inbox_id: str, message_id: str):
122
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}/messages/{message_id}")
123
+
124
+ def update(self, inbox_id: str, message_id: str, add_labels=None, remove_labels=None):
125
+ return self._c._request(
126
+ "PATCH",
127
+ f"/v1/inboxes/{_enc(inbox_id)}/messages/{message_id}",
128
+ json_body=_clean({"add_labels": add_labels, "remove_labels": remove_labels}),
129
+ )
130
+
131
+ def raw(self, inbox_id: str, message_id: str) -> str:
132
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}/messages/{message_id}/raw", raw=True)
133
+
134
+ def get_attachment(self, inbox_id: str, message_id: str, attachment_id: str) -> bytes:
135
+ return self._c._request(
136
+ "GET",
137
+ f"/v1/inboxes/{_enc(inbox_id)}/messages/{message_id}/attachments/{attachment_id}",
138
+ binary=True,
139
+ )
140
+
141
+ def send(self, inbox_id: str, to, subject, text=None, html=None, cc=None, bcc=None, attachments=None, labels=None, client_id=None):
142
+ return self._c._request(
143
+ "POST",
144
+ f"/v1/inboxes/{_enc(inbox_id)}/messages/send",
145
+ json_body=_clean(
146
+ {
147
+ "to": to,
148
+ "cc": cc,
149
+ "bcc": bcc,
150
+ "subject": subject,
151
+ "text": text,
152
+ "html": html,
153
+ "attachments": attachments,
154
+ "labels": labels,
155
+ "client_id": client_id,
156
+ }
157
+ ),
158
+ )
159
+
160
+ def send_batch(self, inbox_id: str, messages: list):
161
+ return self._c._request(
162
+ "POST", f"/v1/inboxes/{_enc(inbox_id)}/messages/batch", json_body={"messages": messages}
163
+ )
164
+
165
+ def reply(self, inbox_id: str, message_id: str, text=None, html=None, to=None, cc=None, client_id=None):
166
+ return self._c._request(
167
+ "POST",
168
+ f"/v1/inboxes/{_enc(inbox_id)}/messages/{message_id}/reply",
169
+ json_body=_clean({"text": text, "html": html, "to": to, "cc": cc, "client_id": client_id}),
170
+ )
171
+
172
+ def forward(self, inbox_id: str, message_id: str, to, text=None, client_id=None):
173
+ return self._c._request(
174
+ "POST",
175
+ f"/v1/inboxes/{_enc(inbox_id)}/messages/{message_id}/forward",
176
+ json_body=_clean({"to": to, "text": text, "client_id": client_id}),
177
+ )
178
+
179
+
180
+ class _Threads:
181
+ def __init__(self, c: AgenticEmail):
182
+ self._c = c
183
+
184
+ def list(self, inbox_id: Optional[str] = None, **filters):
185
+ if inbox_id:
186
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}/threads", params=filters)
187
+ return self._c._request("GET", "/v1/threads", params=filters)
188
+
189
+ def search(self, q=None, inbox_id: Optional[str] = None, **filters):
190
+ params = {"q": q, **filters}
191
+ if inbox_id:
192
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}/threads/search", params=params)
193
+ return self._c._request("GET", "/v1/threads/search", params=params)
194
+
195
+ def get(self, thread_id: str):
196
+ return self._c._request("GET", f"/v1/threads/{thread_id}")
197
+
198
+ def update(self, thread_id: str, add_labels=None, remove_labels=None):
199
+ return self._c._request(
200
+ "PATCH",
201
+ f"/v1/threads/{thread_id}",
202
+ json_body=_clean({"add_labels": add_labels, "remove_labels": remove_labels}),
203
+ )
204
+
205
+
206
+ class _Lists:
207
+ def __init__(self, c: AgenticEmail):
208
+ self._c = c
209
+
210
+ def _path(self, inbox_id, direction, type):
211
+ if inbox_id:
212
+ return f"/v1/inboxes/{_enc(inbox_id)}/lists/{direction}/{type}"
213
+ return f"/v1/lists/{direction}/{type}"
214
+
215
+ def create(self, inbox_id, direction, type, entry, reason=None):
216
+ return self._c._request(
217
+ "POST", self._path(inbox_id, direction, type), json_body=_clean({"entry": entry, "reason": reason})
218
+ )
219
+
220
+ def list(self, inbox_id, direction, type):
221
+ return self._c._request("GET", self._path(inbox_id, direction, type))
222
+
223
+ def get(self, inbox_id, direction, type, entry):
224
+ return self._c._request("GET", f"{self._path(inbox_id, direction, type)}/{_enc(entry)}")
225
+
226
+ def delete(self, inbox_id, direction, type, entry):
227
+ return self._c._request("DELETE", f"{self._path(inbox_id, direction, type)}/{_enc(entry)}")
228
+
229
+
230
+ class _Drafts:
231
+ def __init__(self, c: AgenticEmail):
232
+ self._c = c
233
+
234
+ def create(self, inbox_id: str, **payload):
235
+ return self._c._request("POST", f"/v1/inboxes/{_enc(inbox_id)}/drafts", json_body=_clean(payload))
236
+
237
+ def list(self, inbox_id: str):
238
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}/drafts")
239
+
240
+ def get(self, inbox_id: str, draft_id: str):
241
+ return self._c._request("GET", f"/v1/inboxes/{_enc(inbox_id)}/drafts/{draft_id}")
242
+
243
+ def update(self, inbox_id: str, draft_id: str, **payload):
244
+ return self._c._request("PATCH", f"/v1/inboxes/{_enc(inbox_id)}/drafts/{draft_id}", json_body=_clean(payload))
245
+
246
+ def delete(self, inbox_id: str, draft_id: str):
247
+ return self._c._request("DELETE", f"/v1/inboxes/{_enc(inbox_id)}/drafts/{draft_id}")
248
+
249
+ def send(self, inbox_id: str, draft_id: str):
250
+ return self._c._request("POST", f"/v1/inboxes/{_enc(inbox_id)}/drafts/{draft_id}/send")
251
+
252
+
253
+ class _Webhooks:
254
+ def __init__(self, c: AgenticEmail):
255
+ self._c = c
256
+
257
+ def create(self, url: str, event_types, inbox_ids=None):
258
+ return self._c._request(
259
+ "POST", "/v1/webhooks", json_body=_clean({"url": url, "event_types": event_types, "inbox_ids": inbox_ids})
260
+ )
261
+
262
+ def list(self):
263
+ return self._c._request("GET", "/v1/webhooks")
264
+
265
+ def get(self, webhook_id: str):
266
+ return self._c._request("GET", f"/v1/webhooks/{webhook_id}")
267
+
268
+ def delete(self, webhook_id: str):
269
+ return self._c._request("DELETE", f"/v1/webhooks/{webhook_id}")
270
+
271
+ def deliveries(self, webhook_id: str):
272
+ return self._c._request("GET", f"/v1/webhooks/{webhook_id}/deliveries")
273
+
274
+
275
+ class _Domains:
276
+ def __init__(self, c: AgenticEmail):
277
+ self._c = c
278
+
279
+ def create(
280
+ self,
281
+ domain: str,
282
+ dns_connection_id=None,
283
+ return_path=None,
284
+ tracking_subdomain=None,
285
+ open_tracking=None,
286
+ click_tracking=None,
287
+ ):
288
+ return self._c._request(
289
+ "POST",
290
+ "/v1/domains",
291
+ json_body=_clean(
292
+ {
293
+ "domain": domain,
294
+ "dns_connection_id": dns_connection_id,
295
+ "return_path": return_path,
296
+ "tracking_subdomain": tracking_subdomain,
297
+ "open_tracking": open_tracking,
298
+ "click_tracking": click_tracking,
299
+ }
300
+ ),
301
+ )
302
+
303
+ def list(self):
304
+ return self._c._request("GET", "/v1/domains")
305
+
306
+ def get(self, domain_id: str):
307
+ return self._c._request("GET", f"/v1/domains/{domain_id}")
308
+
309
+ def verify(self, domain_id: str):
310
+ return self._c._request("POST", f"/v1/domains/{domain_id}/verify")
311
+
312
+ def delete(self, domain_id: str):
313
+ return self._c._request("DELETE", f"/v1/domains/{domain_id}")
314
+
315
+
316
+ class _ApiKeys:
317
+ def __init__(self, c: AgenticEmail):
318
+ self._c = c
319
+
320
+ def create(self, name: str, scopes=None, scope_inbox_id=None):
321
+ return self._c._request(
322
+ "POST",
323
+ "/v1/api-keys",
324
+ json_body=_clean({"name": name, "scopes": scopes, "scope_inbox_id": scope_inbox_id}),
325
+ )
326
+
327
+ def list(self):
328
+ return self._c._request("GET", "/v1/api-keys")
329
+
330
+ def delete(self, api_key_id: str):
331
+ return self._c._request("DELETE", f"/v1/api-keys/{api_key_id}")
332
+
333
+
334
+ class _Events:
335
+ def __init__(self, c: AgenticEmail):
336
+ self._c = c
337
+
338
+ def stream(self, inbox_ids=None, event_types=None):
339
+ try:
340
+ from websocket import create_connection
341
+ except ImportError as exc:
342
+ raise AgenticEmailError(0, "no_websocket", "Install websocket-client to use events") from exc
343
+ ws_url = self._c._base_url.replace("http", "ws", 1) + "/v1/events?token=" + quote(self._c._api_key, safe="")
344
+ ws = create_connection(ws_url)
345
+ ws.send(json.dumps({"type": "subscribe", "inbox_ids": inbox_ids, "event_types": event_types}))
346
+ try:
347
+ while True:
348
+ raw = ws.recv()
349
+ if not raw:
350
+ break
351
+ msg = json.loads(raw)
352
+ if msg.get("event_id") and msg.get("type"):
353
+ yield msg
354
+ finally:
355
+ ws.close()
356
+
357
+
358
+ def verify_webhook(body: str, headers: dict, secret: str) -> dict:
359
+ wid = headers.get("webhook-id")
360
+ ts = headers.get("webhook-timestamp")
361
+ sig_header = headers.get("webhook-signature")
362
+ if not wid or not ts or not sig_header:
363
+ raise AgenticEmailError(400, "invalid_signature", "Missing webhook signature headers")
364
+
365
+ key = base64.b64decode(secret[6:] if secret.startswith("whsec_") else secret)
366
+ expected = base64.b64encode(
367
+ hmac.new(key, f"{wid}.{ts}.{body}".encode(), hashlib.sha256).digest()
368
+ ).decode()
369
+ for token in sig_header.split(" "):
370
+ parts = token.split(",")
371
+ if len(parts) == 2 and hmac.compare_digest(parts[1], expected):
372
+ return json.loads(body)
373
+ raise AgenticEmailError(400, "invalid_signature", "Webhook signature verification failed")
374
+
375
+ # Deprecated aliases — kept for backward compatibility.
376
+ AgentMail = AgenticEmail
377
+ AgentMailError = AgenticEmailError
@@ -0,0 +1,97 @@
1
+ """LangChain integration for AgenticEmail.
2
+
3
+ Wraps the AgenticEmail SDK as LangChain tools, mirroring AgenticEmail's
4
+ ``langchain-agentmail`` package::
5
+
6
+ from agenticemail.langchain import AgenticEmailToolkit
7
+
8
+ toolkit = AgenticEmailToolkit.from_api_key()
9
+ tools = toolkit.get_tools()
10
+
11
+ For TypeScript/JavaScript agent frameworks (Vercel AI SDK, OpenAI Agents,
12
+ Claude Agent SDK), point the framework at the built-in MCP server at ``/mcp``
13
+ instead. MCP is the framework-agnostic tool bridge, so it needs no separate
14
+ per-framework wrapper.
15
+ """
16
+
17
+ import os
18
+ from typing import List, Optional
19
+
20
+ from . import AgenticEmail
21
+
22
+
23
+ class AgenticEmailToolkit:
24
+ def __init__(
25
+ self,
26
+ client: Optional[AgenticEmail] = None,
27
+ api_key: Optional[str] = None,
28
+ base_url: Optional[str] = None,
29
+ ):
30
+ if client is None:
31
+ key = api_key or os.environ.get("AGENTICEMAIL_API_KEY")
32
+ if not key:
33
+ raise ValueError("Provide a client, an api_key, or set AGENTICEMAIL_API_KEY")
34
+ client = AgenticEmail(key, base_url) if base_url else AgenticEmail(key)
35
+ self.client = client
36
+
37
+ @classmethod
38
+ def from_api_key(cls, api_key: Optional[str] = None, base_url: Optional[str] = None) -> "AgenticEmailToolkit":
39
+ return cls(api_key=api_key, base_url=base_url)
40
+
41
+ def _tool_specs(self):
42
+ c = self.client
43
+
44
+ def list_inboxes() -> list:
45
+ """List the inboxes available to this agent."""
46
+ return c.inboxes.list()
47
+
48
+ def create_inbox(username: Optional[str] = None, domain: Optional[str] = None) -> dict:
49
+ """Create a new inbox, optionally with a username and domain."""
50
+ return c.inboxes.create(username=username, domain=domain)
51
+
52
+ def list_messages(inbox_id: str) -> list:
53
+ """List the messages in an inbox."""
54
+ return c.messages.list(inbox_id)
55
+
56
+ def get_message(inbox_id: str, message_id: str) -> dict:
57
+ """Fetch a single message by id."""
58
+ return c.messages.get(inbox_id, message_id)
59
+
60
+ def send_email(
61
+ inbox_id: str,
62
+ to: List[str],
63
+ subject: str,
64
+ text: Optional[str] = None,
65
+ html: Optional[str] = None,
66
+ ) -> dict:
67
+ """Send an email from an inbox to one or more recipients."""
68
+ return c.messages.send(inbox_id, to, subject, text=text, html=html)
69
+
70
+ def reply_to_message(inbox_id: str, message_id: str, text: str) -> dict:
71
+ """Reply to a message, keeping it in the same thread."""
72
+ return c.messages.reply(inbox_id, message_id, text=text)
73
+
74
+ def search_messages(inbox_id: str, query: str) -> list:
75
+ """Full-text search the messages in an inbox."""
76
+ return c.messages.search(inbox_id, q=query)
77
+
78
+ return [
79
+ list_inboxes,
80
+ create_inbox,
81
+ list_messages,
82
+ get_message,
83
+ send_email,
84
+ reply_to_message,
85
+ search_messages,
86
+ ]
87
+
88
+ def get_tools(self):
89
+ try:
90
+ from langchain_core.tools import StructuredTool
91
+ except ImportError as exc:
92
+ raise ImportError("Install langchain-core to use get_tools()") from exc
93
+ return [StructuredTool.from_function(fn) for fn in self._tool_specs()]
94
+
95
+
96
+ # Deprecated alias — kept for backward compatibility.
97
+ AgentMailToolkit = AgenticEmailToolkit
File without changes
@@ -0,0 +1,81 @@
1
+ # API surface
2
+
3
+ Client: `AgenticEmail(api_key, base_url="https://app.agenticemail.dev")`. All methods return dicts (snake_case, as the API sends them) and raise `AgenticEmailError` on non-2xx responses.
4
+
5
+ ## inboxes
6
+
7
+ - `client.inboxes.create(username=None, domain=None, display_name=None, client_id=None)`
8
+ - `client.inboxes.list(limit=None, page_token=None)`
9
+ - `client.inboxes.get(inbox_id)`
10
+ - `client.inboxes.update(inbox_id, display_name)`
11
+ - `client.inboxes.delete(inbox_id)`
12
+
13
+ ## messages
14
+
15
+ - `client.messages.list(inbox_id, **filters)`
16
+ - `client.messages.search(inbox_id, q=None, **filters)`
17
+ - `client.messages.get(inbox_id, message_id)`
18
+ - `client.messages.raw(inbox_id, message_id)` → RFC 822 source string
19
+ - `client.messages.get_attachment(inbox_id, message_id, attachment_id)` → bytes
20
+ - `client.messages.send(inbox_id, to, subject, text=None, html=None, cc=None, bcc=None, attachments=None, labels=None, client_id=None)`
21
+ - `client.messages.send_batch(inbox_id, messages)`
22
+ - `client.messages.reply(inbox_id, message_id, text=None, html=None, to=None, cc=None, client_id=None)`
23
+ - `client.messages.forward(inbox_id, message_id, to, text=None, client_id=None)`
24
+ - `client.messages.update(inbox_id, message_id, add_labels=None, remove_labels=None)`
25
+
26
+ ## threads
27
+
28
+ - `client.threads.list(inbox_id=None, **filters)` — omit `inbox_id` for org-wide
29
+ - `client.threads.search(q=None, inbox_id=None, **filters)`
30
+ - `client.threads.get(thread_id)`
31
+ - `client.threads.update(thread_id, add_labels=None, remove_labels=None)`
32
+
33
+ ## drafts
34
+
35
+ - `client.drafts.create(inbox_id, **payload)` — supports `send_at` for scheduled send
36
+ - `client.drafts.list(inbox_id)`
37
+ - `client.drafts.get(inbox_id, draft_id)`
38
+ - `client.drafts.update(inbox_id, draft_id, **payload)`
39
+ - `client.drafts.delete(inbox_id, draft_id)`
40
+ - `client.drafts.send(inbox_id, draft_id)`
41
+
42
+ ## lists (allow/block lists)
43
+
44
+ `direction` is `"receive" | "send" | "reply"`, `type` is `"allow" | "block"`; pass `inbox_id=None` for org-level lists.
45
+
46
+ - `client.lists.create(inbox_id, direction, type, entry, reason=None)`
47
+ - `client.lists.list(inbox_id, direction, type)`
48
+ - `client.lists.get(inbox_id, direction, type, entry)`
49
+ - `client.lists.delete(inbox_id, direction, type, entry)`
50
+
51
+ ## webhooks
52
+
53
+ - `client.webhooks.create(url, event_types, inbox_ids=None)`
54
+ - `client.webhooks.list()`
55
+ - `client.webhooks.get(webhook_id)`
56
+ - `client.webhooks.delete(webhook_id)`
57
+ - `client.webhooks.deliveries(webhook_id)`
58
+
59
+ ## domains
60
+
61
+ - `client.domains.create(domain, dns_connection_id=None, return_path=None, tracking_subdomain=None, open_tracking=None, click_tracking=None)`
62
+ - `client.domains.list()`
63
+ - `client.domains.get(domain_id)`
64
+ - `client.domains.verify(domain_id)`
65
+ - `client.domains.delete(domain_id)`
66
+
67
+ ## api_keys
68
+
69
+ - `client.api_keys.create(name, scopes=None, scope_inbox_id=None)`
70
+ - `client.api_keys.list()`
71
+ - `client.api_keys.delete(api_key_id)`
72
+
73
+ ## events
74
+
75
+ - `client.events.stream(inbox_ids=None, event_types=None)` — generator over the WebSocket feed (requires the `events` extra)
76
+
77
+ ## Helpers
78
+
79
+ - `verify_webhook(body, headers, secret)` — validates the HMAC signature and returns the parsed event
80
+ - `AgenticEmailError` — `.status`, `.code`
81
+ - `agenticemail.langchain.AgenticEmailToolkit` — `from_api_key()`, `get_tools()` (requires the `langchain` extra)
@@ -0,0 +1,36 @@
1
+ """A minimal auto-reply agent.
2
+
3
+ Polls an inbox and replies once to every inbound message.
4
+
5
+ export AGENTICEMAIL_API_KEY=am_...
6
+ export AGENTICEMAIL_INBOX=support@yourdomain.com
7
+ export AGENTICEMAIL_BASE_URL=http://localhost:3000 # omit for the hosted API
8
+ python examples/auto_reply.py
9
+ """
10
+
11
+ import os
12
+ import time
13
+
14
+ from agenticemail import AgenticEmail
15
+
16
+ client = AgenticEmail(
17
+ api_key=os.environ["AGENTICEMAIL_API_KEY"],
18
+ base_url=os.environ.get("AGENTICEMAIL_BASE_URL", "https://app.agenticemail.dev"),
19
+ )
20
+ inbox = os.environ["AGENTICEMAIL_INBOX"]
21
+ replied: set[str] = set()
22
+
23
+ print(f"Auto-reply watching {inbox} …")
24
+ while True:
25
+ for summary in client.threads.list(inbox).get("data", []):
26
+ thread = client.threads.get(summary["id"])
27
+ last = thread["messages"][-1]
28
+ if last["direction"] == "inbound" and last["id"] not in replied:
29
+ client.messages.reply(
30
+ inbox,
31
+ last["id"],
32
+ text="Thanks for your message! An agent will follow up shortly.",
33
+ )
34
+ replied.add(last["id"])
35
+ print(f"Replied to {last['from']} in thread {summary['id']}")
36
+ time.sleep(10)
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "agenticemail"
7
+ version = "0.1.0"
8
+ description = "Python SDK for AgenticEmail — API-first email for AI agents."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9"
12
+ dependencies = ["httpx>=0.27"]
13
+
14
+ [project.urls]
15
+ Homepage = "https://agenticemail.dev"
16
+ Repository = "https://github.com/AgenticEmail/agenticemail-python"
17
+ Documentation = "https://agenticemail.dev/docs"
18
+
19
+ [project.optional-dependencies]
20
+ events = ["websocket-client>=1.6"]
21
+ langchain = ["langchain-core>=0.3"]
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["agenticemail"]
@@ -0,0 +1,52 @@
1
+ from agenticemail.langchain import AgenticEmailToolkit
2
+
3
+
4
+ class FakeMessages:
5
+ def __init__(self):
6
+ self.sent = None
7
+
8
+ def list(self, inbox_id):
9
+ return [{"id": "msg_1"}]
10
+
11
+ def send(self, inbox_id, to, subject, text=None, html=None):
12
+ self.sent = {"inbox_id": inbox_id, "to": to, "subject": subject, "text": text}
13
+ return {"id": "msg_1", "status": "sent"}
14
+
15
+ def search(self, inbox_id, q=None):
16
+ return [{"id": "msg_1", "q": q}]
17
+
18
+
19
+ class FakeInboxes:
20
+ def list(self):
21
+ return [{"id": "a@x"}]
22
+
23
+ def create(self, username=None, domain=None):
24
+ return {"id": f"{username}@{domain}"}
25
+
26
+
27
+ class FakeClient:
28
+ def __init__(self):
29
+ self.messages = FakeMessages()
30
+ self.inboxes = FakeInboxes()
31
+
32
+
33
+ def test_exposes_expected_tools():
34
+ toolkit = AgenticEmailToolkit(client=FakeClient())
35
+ names = [fn.__name__ for fn in toolkit._tool_specs()]
36
+ for expected in ["list_inboxes", "create_inbox", "send_email", "reply_to_message", "search_messages"]:
37
+ assert expected in names
38
+
39
+
40
+ def test_send_email_tool_calls_the_client():
41
+ client = FakeClient()
42
+ toolkit = AgenticEmailToolkit(client=client)
43
+ send_email = next(fn for fn in toolkit._tool_specs() if fn.__name__ == "send_email")
44
+ result = send_email("a@x", ["b@y"], "Hi", text="yo")
45
+ assert result["status"] == "sent"
46
+ assert client.messages.sent["to"] == ["b@y"]
47
+
48
+
49
+ if __name__ == "__main__":
50
+ test_exposes_expected_tools()
51
+ test_send_email_tool_calls_the_client()
52
+ print("ok")