yunmail 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.
- yunmail-0.1.0/LICENSE +202 -0
- yunmail-0.1.0/PKG-INFO +128 -0
- yunmail-0.1.0/README.md +108 -0
- yunmail-0.1.0/pyproject.toml +29 -0
- yunmail-0.1.0/setup.cfg +4 -0
- yunmail-0.1.0/src/yunmail/__init__.py +26 -0
- yunmail-0.1.0/src/yunmail/client.py +204 -0
- yunmail-0.1.0/src/yunmail/errors.py +22 -0
- yunmail-0.1.0/src/yunmail/models.py +23 -0
- yunmail-0.1.0/src/yunmail.egg-info/PKG-INFO +128 -0
- yunmail-0.1.0/src/yunmail.egg-info/SOURCES.txt +12 -0
- yunmail-0.1.0/src/yunmail.egg-info/dependency_links.txt +1 -0
- yunmail-0.1.0/src/yunmail.egg-info/top_level.txt +1 -0
- yunmail-0.1.0/tests/test_client.py +100 -0
yunmail-0.1.0/LICENSE
ADDED
|
@@ -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 Yunmail
|
|
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.
|
yunmail-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: yunmail
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the Yunmail cloud communications API — email, SMS, voice verification and push notifications through one unified API.
|
|
5
|
+
Author: Yunmail Maintainers
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://www.yunmail.cc.cd
|
|
8
|
+
Project-URL: Documentation, https://www.yunmail.cc.cd
|
|
9
|
+
Project-URL: Issues, https://github.com/tanxi281-sketch/yunmail-sdk/issues
|
|
10
|
+
Keywords: yunmail,email-api,sms-api,voice-otp,push-notifications,cloud-communications
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Communications :: Email
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# Yunmail Python SDK
|
|
22
|
+
|
|
23
|
+
Official Python SDK for the [Yunmail](https://www.yunmail.cc.cd) cloud
|
|
24
|
+
communications platform — **email, SMS, voice verification and push
|
|
25
|
+
notifications through one unified API**, with a single API key.
|
|
26
|
+
|
|
27
|
+
- 📧 Transactional & marketing email with template support
|
|
28
|
+
- 💬 SMS verification codes, alerts and campaigns (200+ countries/regions)
|
|
29
|
+
- 📞 Voice OTP as a reliable fallback where SMS can't reach
|
|
30
|
+
- 🔔 App & web push notifications
|
|
31
|
+
- 🔐 HMAC-SHA256 webhook signature verification built in
|
|
32
|
+
- 🚀 Zero dependencies — Python standard library only
|
|
33
|
+
|
|
34
|
+
> Status: **0.1.0 (alpha)**. The API surface covers the four core send
|
|
35
|
+
> channels plus delivery-status lookup. See [ROADMAP.md](ROADMAP.md).
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install yunmail
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Or from source:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
git clone https://github.com/tanxi281-sketch/yunmail-sdk.git
|
|
47
|
+
cd yunmail-sdk
|
|
48
|
+
pip install -e .
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quickstart
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from yunmail import YunmailClient
|
|
55
|
+
|
|
56
|
+
client = YunmailClient(api_key="YOUR_YUNMAIL_API_KEY")
|
|
57
|
+
|
|
58
|
+
# Email
|
|
59
|
+
client.send_email(
|
|
60
|
+
to="user@example.com",
|
|
61
|
+
subject="Welcome to Yunmail",
|
|
62
|
+
html="<p>Thanks for signing up!</p>",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# SMS verification code (template based)
|
|
66
|
+
client.send_sms(
|
|
67
|
+
to="+8613800000000",
|
|
68
|
+
template_id="verify_code",
|
|
69
|
+
params={"code": "123456"},
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# Voice OTP fallback
|
|
73
|
+
client.send_voice_code(to="+8613800000000", code="123456")
|
|
74
|
+
|
|
75
|
+
# Push notification
|
|
76
|
+
client.send_push(
|
|
77
|
+
device_tokens=["device-token-1"],
|
|
78
|
+
title="Order shipped",
|
|
79
|
+
body="Your order is on its way.",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Delivery status of any message
|
|
83
|
+
status = client.get_message_status("MESSAGE_ID")
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Webhook verification
|
|
87
|
+
|
|
88
|
+
Verify that a webhook really came from Yunmail before trusting it:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from yunmail import YunmailClient
|
|
92
|
+
|
|
93
|
+
ok = YunmailClient.verify_webhook(
|
|
94
|
+
payload=request_body_bytes, # raw request body
|
|
95
|
+
signature=request.headers["X-Yunmail-Signature"],
|
|
96
|
+
secret="YOUR_WEBHOOK_SECRET",
|
|
97
|
+
)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Error handling
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from yunmail import AuthenticationError, RateLimitError, APIError
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
client.send_email(...)
|
|
107
|
+
except AuthenticationError:
|
|
108
|
+
... # bad or under-scoped API key (HTTP 401/403)
|
|
109
|
+
except RateLimitError:
|
|
110
|
+
... # HTTP 429 — the client already retried with backoff
|
|
111
|
+
except APIError as exc:
|
|
112
|
+
print(exc.status, exc.payload)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
HTTP 429 and 5xx responses are retried automatically with exponential
|
|
116
|
+
backoff (`max_retries=2` by default).
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
python -m unittest discover -s tests -v
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Contributions are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
125
|
+
|
|
126
|
+
## License
|
|
127
|
+
|
|
128
|
+
Apache License 2.0 — see [LICENSE](LICENSE).
|
yunmail-0.1.0/README.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Yunmail Python SDK
|
|
2
|
+
|
|
3
|
+
Official Python SDK for the [Yunmail](https://www.yunmail.cc.cd) cloud
|
|
4
|
+
communications platform — **email, SMS, voice verification and push
|
|
5
|
+
notifications through one unified API**, with a single API key.
|
|
6
|
+
|
|
7
|
+
- 📧 Transactional & marketing email with template support
|
|
8
|
+
- 💬 SMS verification codes, alerts and campaigns (200+ countries/regions)
|
|
9
|
+
- 📞 Voice OTP as a reliable fallback where SMS can't reach
|
|
10
|
+
- 🔔 App & web push notifications
|
|
11
|
+
- 🔐 HMAC-SHA256 webhook signature verification built in
|
|
12
|
+
- 🚀 Zero dependencies — Python standard library only
|
|
13
|
+
|
|
14
|
+
> Status: **0.1.0 (alpha)**. The API surface covers the four core send
|
|
15
|
+
> channels plus delivery-status lookup. See [ROADMAP.md](ROADMAP.md).
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install yunmail
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Or from source:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
git clone https://github.com/tanxi281-sketch/yunmail-sdk.git
|
|
27
|
+
cd yunmail-sdk
|
|
28
|
+
pip install -e .
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from yunmail import YunmailClient
|
|
35
|
+
|
|
36
|
+
client = YunmailClient(api_key="YOUR_YUNMAIL_API_KEY")
|
|
37
|
+
|
|
38
|
+
# Email
|
|
39
|
+
client.send_email(
|
|
40
|
+
to="user@example.com",
|
|
41
|
+
subject="Welcome to Yunmail",
|
|
42
|
+
html="<p>Thanks for signing up!</p>",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# SMS verification code (template based)
|
|
46
|
+
client.send_sms(
|
|
47
|
+
to="+8613800000000",
|
|
48
|
+
template_id="verify_code",
|
|
49
|
+
params={"code": "123456"},
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Voice OTP fallback
|
|
53
|
+
client.send_voice_code(to="+8613800000000", code="123456")
|
|
54
|
+
|
|
55
|
+
# Push notification
|
|
56
|
+
client.send_push(
|
|
57
|
+
device_tokens=["device-token-1"],
|
|
58
|
+
title="Order shipped",
|
|
59
|
+
body="Your order is on its way.",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Delivery status of any message
|
|
63
|
+
status = client.get_message_status("MESSAGE_ID")
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Webhook verification
|
|
67
|
+
|
|
68
|
+
Verify that a webhook really came from Yunmail before trusting it:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from yunmail import YunmailClient
|
|
72
|
+
|
|
73
|
+
ok = YunmailClient.verify_webhook(
|
|
74
|
+
payload=request_body_bytes, # raw request body
|
|
75
|
+
signature=request.headers["X-Yunmail-Signature"],
|
|
76
|
+
secret="YOUR_WEBHOOK_SECRET",
|
|
77
|
+
)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Error handling
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from yunmail import AuthenticationError, RateLimitError, APIError
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
client.send_email(...)
|
|
87
|
+
except AuthenticationError:
|
|
88
|
+
... # bad or under-scoped API key (HTTP 401/403)
|
|
89
|
+
except RateLimitError:
|
|
90
|
+
... # HTTP 429 — the client already retried with backoff
|
|
91
|
+
except APIError as exc:
|
|
92
|
+
print(exc.status, exc.payload)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
HTTP 429 and 5xx responses are retried automatically with exponential
|
|
96
|
+
backoff (`max_retries=2` by default).
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
python -m unittest discover -s tests -v
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Contributions are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
Apache License 2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "yunmail"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python SDK for the Yunmail cloud communications API — email, SMS, voice verification and push notifications through one unified API."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "Yunmail Maintainers" }]
|
|
13
|
+
keywords = ["yunmail", "email-api", "sms-api", "voice-otp", "push-notifications", "cloud-communications"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: Apache Software License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Communications :: Email",
|
|
20
|
+
]
|
|
21
|
+
dependencies = []
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://www.yunmail.cc.cd"
|
|
25
|
+
Documentation = "https://www.yunmail.cc.cd"
|
|
26
|
+
Issues = "https://github.com/tanxi281-sketch/yunmail-sdk/issues"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
yunmail-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Yunmail Python SDK.
|
|
2
|
+
|
|
3
|
+
One unified client for Yunmail's cloud communications API:
|
|
4
|
+
transactional & marketing email, SMS, voice verification and push.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .client import YunmailClient
|
|
8
|
+
from .errors import (
|
|
9
|
+
APIError,
|
|
10
|
+
AuthenticationError,
|
|
11
|
+
RateLimitError,
|
|
12
|
+
YunmailError,
|
|
13
|
+
)
|
|
14
|
+
from .models import MessageResult
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.0"
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"YunmailClient",
|
|
20
|
+
"MessageResult",
|
|
21
|
+
"YunmailError",
|
|
22
|
+
"APIError",
|
|
23
|
+
"AuthenticationError",
|
|
24
|
+
"RateLimitError",
|
|
25
|
+
"__version__",
|
|
26
|
+
]
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Yunmail API client.
|
|
2
|
+
|
|
3
|
+
Covers the four Yunmail channels — email, SMS, voice verification and
|
|
4
|
+
push notifications — through one REST client with a single API key.
|
|
5
|
+
|
|
6
|
+
The transport is injectable, which keeps the SDK dependency-free
|
|
7
|
+
(standard library only) and easy to test: pass any callable with the
|
|
8
|
+
signature ``transport(method, url, headers, body) -> (status, headers,
|
|
9
|
+
body)``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import hmac
|
|
14
|
+
import json
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple
|
|
19
|
+
|
|
20
|
+
from .errors import APIError, AuthenticationError, RateLimitError
|
|
21
|
+
from .models import MessageResult
|
|
22
|
+
|
|
23
|
+
DEFAULT_BASE_URL = "https://api.yunmail.cc.cd/v1"
|
|
24
|
+
|
|
25
|
+
Transport = Callable[
|
|
26
|
+
[str, str, Dict[str, str], Optional[bytes]],
|
|
27
|
+
Tuple[int, Dict[str, str], bytes],
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _urllib_transport(method, url, headers, body):
|
|
32
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
33
|
+
try:
|
|
34
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
35
|
+
return resp.status, dict(resp.headers), resp.read()
|
|
36
|
+
except urllib.error.HTTPError as exc: # non-2xx still carries a body
|
|
37
|
+
return exc.code, dict(exc.headers or {}), exc.read()
|
|
38
|
+
except urllib.error.URLError as exc:
|
|
39
|
+
raise APIError(0, f"Network error calling Yunmail API: {exc.reason}") from exc
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class YunmailClient:
|
|
43
|
+
"""Client for the Yunmail cloud communications API.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
api_key: Your Yunmail API key (sent as a Bearer token).
|
|
47
|
+
base_url: API base URL; override for staging or self-hosted use.
|
|
48
|
+
timeout: Per-request timeout in seconds (default transport only).
|
|
49
|
+
max_retries: Retries on HTTP 429 / 5xx with exponential backoff.
|
|
50
|
+
transport: Custom transport callable (mainly for testing).
|
|
51
|
+
sleeper: Sleep function used between retries (mainly for testing).
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
api_key: str,
|
|
57
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
58
|
+
timeout: int = 30,
|
|
59
|
+
max_retries: int = 2,
|
|
60
|
+
transport: Optional[Transport] = None,
|
|
61
|
+
sleeper: Callable[[float], None] = time.sleep,
|
|
62
|
+
):
|
|
63
|
+
if not api_key:
|
|
64
|
+
raise ValueError("api_key is required")
|
|
65
|
+
self.api_key = api_key
|
|
66
|
+
self.base_url = base_url.rstrip("/")
|
|
67
|
+
self.timeout = timeout
|
|
68
|
+
self.max_retries = max_retries
|
|
69
|
+
self._transport = transport or _urllib_transport
|
|
70
|
+
self._sleeper = sleeper
|
|
71
|
+
|
|
72
|
+
# ------------------------------------------------------------------
|
|
73
|
+
# Channels
|
|
74
|
+
# ------------------------------------------------------------------
|
|
75
|
+
def send_email(
|
|
76
|
+
self,
|
|
77
|
+
to: str,
|
|
78
|
+
subject: str,
|
|
79
|
+
html: Optional[str] = None,
|
|
80
|
+
text: Optional[str] = None,
|
|
81
|
+
from_addr: Optional[str] = None,
|
|
82
|
+
tags: Optional[Sequence[str]] = None,
|
|
83
|
+
) -> MessageResult:
|
|
84
|
+
"""Send a transactional or marketing email."""
|
|
85
|
+
if html is None and text is None:
|
|
86
|
+
raise ValueError("either html or text content is required")
|
|
87
|
+
payload: Dict[str, Any] = {"to": to, "subject": subject}
|
|
88
|
+
if html is not None:
|
|
89
|
+
payload["html"] = html
|
|
90
|
+
if text is not None:
|
|
91
|
+
payload["text"] = text
|
|
92
|
+
if from_addr is not None:
|
|
93
|
+
payload["from"] = from_addr
|
|
94
|
+
if tags:
|
|
95
|
+
payload["tags"] = list(tags)
|
|
96
|
+
return self._send("/email/send", payload, channel="email")
|
|
97
|
+
|
|
98
|
+
def send_sms(
|
|
99
|
+
self,
|
|
100
|
+
to: str,
|
|
101
|
+
content: Optional[str] = None,
|
|
102
|
+
template_id: Optional[str] = None,
|
|
103
|
+
params: Optional[Dict[str, Any]] = None,
|
|
104
|
+
) -> MessageResult:
|
|
105
|
+
"""Send an SMS (verification code, alert or marketing message)."""
|
|
106
|
+
if content is None and template_id is None:
|
|
107
|
+
raise ValueError("either content or template_id is required")
|
|
108
|
+
payload: Dict[str, Any] = {"to": to}
|
|
109
|
+
if content is not None:
|
|
110
|
+
payload["content"] = content
|
|
111
|
+
if template_id is not None:
|
|
112
|
+
payload["template_id"] = template_id
|
|
113
|
+
if params:
|
|
114
|
+
payload["params"] = params
|
|
115
|
+
return self._send("/sms/send", payload, channel="sms")
|
|
116
|
+
|
|
117
|
+
def send_voice_code(
|
|
118
|
+
self,
|
|
119
|
+
to: str,
|
|
120
|
+
code: str,
|
|
121
|
+
lang: str = "en-US",
|
|
122
|
+
) -> MessageResult:
|
|
123
|
+
"""Deliver a one-time passcode by voice call (SMS fallback)."""
|
|
124
|
+
payload = {"to": to, "code": code, "lang": lang}
|
|
125
|
+
return self._send("/voice/send", payload, channel="voice")
|
|
126
|
+
|
|
127
|
+
def send_push(
|
|
128
|
+
self,
|
|
129
|
+
device_tokens: Iterable[str],
|
|
130
|
+
title: str,
|
|
131
|
+
body: str,
|
|
132
|
+
data: Optional[Dict[str, Any]] = None,
|
|
133
|
+
) -> MessageResult:
|
|
134
|
+
"""Send an app/web push notification to one or more devices."""
|
|
135
|
+
payload: Dict[str, Any] = {
|
|
136
|
+
"device_tokens": list(device_tokens),
|
|
137
|
+
"title": title,
|
|
138
|
+
"body": body,
|
|
139
|
+
}
|
|
140
|
+
if data:
|
|
141
|
+
payload["data"] = data
|
|
142
|
+
return self._send("/push/send", payload, channel="push")
|
|
143
|
+
|
|
144
|
+
def get_message_status(self, message_id: str) -> Dict[str, Any]:
|
|
145
|
+
"""Fetch the delivery status of a previously sent message."""
|
|
146
|
+
return self._request("GET", f"/messages/{message_id}")
|
|
147
|
+
|
|
148
|
+
# ------------------------------------------------------------------
|
|
149
|
+
# Webhooks
|
|
150
|
+
# ------------------------------------------------------------------
|
|
151
|
+
@staticmethod
|
|
152
|
+
def verify_webhook(payload: bytes, signature: str, secret: str) -> bool:
|
|
153
|
+
"""Verify an HMAC-SHA256 webhook signature in constant time."""
|
|
154
|
+
expected = hmac.new(
|
|
155
|
+
secret.encode("utf-8"), payload, hashlib.sha256
|
|
156
|
+
).hexdigest()
|
|
157
|
+
return hmac.compare_digest(expected, signature.strip())
|
|
158
|
+
|
|
159
|
+
# ------------------------------------------------------------------
|
|
160
|
+
# Internals
|
|
161
|
+
# ------------------------------------------------------------------
|
|
162
|
+
def _send(self, path: str, payload: Dict[str, Any], channel: str) -> MessageResult:
|
|
163
|
+
data = self._request("POST", path, payload)
|
|
164
|
+
return MessageResult.from_payload(data, channel=channel)
|
|
165
|
+
|
|
166
|
+
def _request(
|
|
167
|
+
self, method: str, path: str, payload: Optional[Dict[str, Any]] = None
|
|
168
|
+
) -> Dict[str, Any]:
|
|
169
|
+
url = f"{self.base_url}{path}"
|
|
170
|
+
headers = {
|
|
171
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
172
|
+
"Content-Type": "application/json",
|
|
173
|
+
"Accept": "application/json",
|
|
174
|
+
"User-Agent": "yunmail-python/0.1.0",
|
|
175
|
+
}
|
|
176
|
+
body = json.dumps(payload).encode("utf-8") if payload is not None else None
|
|
177
|
+
|
|
178
|
+
attempt = 0
|
|
179
|
+
while True:
|
|
180
|
+
status, _resp_headers, raw = self._transport(method, url, headers, body)
|
|
181
|
+
if 200 <= status < 300:
|
|
182
|
+
return json.loads(raw.decode("utf-8")) if raw else {}
|
|
183
|
+
retryable = status == 429 or status >= 500
|
|
184
|
+
if retryable and attempt < self.max_retries:
|
|
185
|
+
self._sleeper(0.5 * (2**attempt))
|
|
186
|
+
attempt += 1
|
|
187
|
+
continue
|
|
188
|
+
self._raise_for_status(status, raw)
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def _raise_for_status(status: int, raw: bytes):
|
|
192
|
+
payload = None
|
|
193
|
+
message = ""
|
|
194
|
+
if raw:
|
|
195
|
+
try:
|
|
196
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
197
|
+
message = payload.get("message") or payload.get("error") or ""
|
|
198
|
+
except (ValueError, UnicodeDecodeError):
|
|
199
|
+
message = raw.decode("utf-8", errors="replace")[:200]
|
|
200
|
+
if status in (401, 403):
|
|
201
|
+
raise AuthenticationError(status, message, payload)
|
|
202
|
+
if status == 429:
|
|
203
|
+
raise RateLimitError(status, message, payload)
|
|
204
|
+
raise APIError(status, message, payload)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Exception types raised by the Yunmail SDK."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class YunmailError(Exception):
|
|
5
|
+
"""Base class for all Yunmail SDK errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class APIError(YunmailError):
|
|
9
|
+
"""The API returned a non-2xx response."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, status: int, message: str = "", payload=None):
|
|
12
|
+
self.status = status
|
|
13
|
+
self.payload = payload
|
|
14
|
+
super().__init__(message or f"Yunmail API error (HTTP {status})")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AuthenticationError(APIError):
|
|
18
|
+
"""HTTP 401/403 — the API key is missing, invalid or lacks scope."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RateLimitError(APIError):
|
|
22
|
+
"""HTTP 429 — too many requests; back off and retry."""
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Response models returned by the Yunmail SDK."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class MessageResult:
|
|
9
|
+
"""Result of a send request (email / SMS / voice / push)."""
|
|
10
|
+
|
|
11
|
+
id: Optional[str] = None
|
|
12
|
+
status: Optional[str] = None
|
|
13
|
+
channel: Optional[str] = None
|
|
14
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def from_payload(cls, payload: Dict[str, Any], channel: str) -> "MessageResult":
|
|
18
|
+
return cls(
|
|
19
|
+
id=payload.get("id") or payload.get("message_id"),
|
|
20
|
+
status=payload.get("status"),
|
|
21
|
+
channel=channel,
|
|
22
|
+
raw=payload,
|
|
23
|
+
)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: yunmail
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the Yunmail cloud communications API — email, SMS, voice verification and push notifications through one unified API.
|
|
5
|
+
Author: Yunmail Maintainers
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://www.yunmail.cc.cd
|
|
8
|
+
Project-URL: Documentation, https://www.yunmail.cc.cd
|
|
9
|
+
Project-URL: Issues, https://github.com/tanxi281-sketch/yunmail-sdk/issues
|
|
10
|
+
Keywords: yunmail,email-api,sms-api,voice-otp,push-notifications,cloud-communications
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Communications :: Email
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# Yunmail Python SDK
|
|
22
|
+
|
|
23
|
+
Official Python SDK for the [Yunmail](https://www.yunmail.cc.cd) cloud
|
|
24
|
+
communications platform — **email, SMS, voice verification and push
|
|
25
|
+
notifications through one unified API**, with a single API key.
|
|
26
|
+
|
|
27
|
+
- 📧 Transactional & marketing email with template support
|
|
28
|
+
- 💬 SMS verification codes, alerts and campaigns (200+ countries/regions)
|
|
29
|
+
- 📞 Voice OTP as a reliable fallback where SMS can't reach
|
|
30
|
+
- 🔔 App & web push notifications
|
|
31
|
+
- 🔐 HMAC-SHA256 webhook signature verification built in
|
|
32
|
+
- 🚀 Zero dependencies — Python standard library only
|
|
33
|
+
|
|
34
|
+
> Status: **0.1.0 (alpha)**. The API surface covers the four core send
|
|
35
|
+
> channels plus delivery-status lookup. See [ROADMAP.md](ROADMAP.md).
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install yunmail
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Or from source:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
git clone https://github.com/tanxi281-sketch/yunmail-sdk.git
|
|
47
|
+
cd yunmail-sdk
|
|
48
|
+
pip install -e .
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quickstart
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from yunmail import YunmailClient
|
|
55
|
+
|
|
56
|
+
client = YunmailClient(api_key="YOUR_YUNMAIL_API_KEY")
|
|
57
|
+
|
|
58
|
+
# Email
|
|
59
|
+
client.send_email(
|
|
60
|
+
to="user@example.com",
|
|
61
|
+
subject="Welcome to Yunmail",
|
|
62
|
+
html="<p>Thanks for signing up!</p>",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# SMS verification code (template based)
|
|
66
|
+
client.send_sms(
|
|
67
|
+
to="+8613800000000",
|
|
68
|
+
template_id="verify_code",
|
|
69
|
+
params={"code": "123456"},
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# Voice OTP fallback
|
|
73
|
+
client.send_voice_code(to="+8613800000000", code="123456")
|
|
74
|
+
|
|
75
|
+
# Push notification
|
|
76
|
+
client.send_push(
|
|
77
|
+
device_tokens=["device-token-1"],
|
|
78
|
+
title="Order shipped",
|
|
79
|
+
body="Your order is on its way.",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Delivery status of any message
|
|
83
|
+
status = client.get_message_status("MESSAGE_ID")
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Webhook verification
|
|
87
|
+
|
|
88
|
+
Verify that a webhook really came from Yunmail before trusting it:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from yunmail import YunmailClient
|
|
92
|
+
|
|
93
|
+
ok = YunmailClient.verify_webhook(
|
|
94
|
+
payload=request_body_bytes, # raw request body
|
|
95
|
+
signature=request.headers["X-Yunmail-Signature"],
|
|
96
|
+
secret="YOUR_WEBHOOK_SECRET",
|
|
97
|
+
)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Error handling
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from yunmail import AuthenticationError, RateLimitError, APIError
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
client.send_email(...)
|
|
107
|
+
except AuthenticationError:
|
|
108
|
+
... # bad or under-scoped API key (HTTP 401/403)
|
|
109
|
+
except RateLimitError:
|
|
110
|
+
... # HTTP 429 — the client already retried with backoff
|
|
111
|
+
except APIError as exc:
|
|
112
|
+
print(exc.status, exc.payload)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
HTTP 429 and 5xx responses are retried automatically with exponential
|
|
116
|
+
backoff (`max_retries=2` by default).
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
python -m unittest discover -s tests -v
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Contributions are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
125
|
+
|
|
126
|
+
## License
|
|
127
|
+
|
|
128
|
+
Apache License 2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/yunmail/__init__.py
|
|
5
|
+
src/yunmail/client.py
|
|
6
|
+
src/yunmail/errors.py
|
|
7
|
+
src/yunmail/models.py
|
|
8
|
+
src/yunmail.egg-info/PKG-INFO
|
|
9
|
+
src/yunmail.egg-info/SOURCES.txt
|
|
10
|
+
src/yunmail.egg-info/dependency_links.txt
|
|
11
|
+
src/yunmail.egg-info/top_level.txt
|
|
12
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
yunmail
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from yunmail import (
|
|
5
|
+
AuthenticationError,
|
|
6
|
+
RateLimitError,
|
|
7
|
+
YunmailClient,
|
|
8
|
+
)
|
|
9
|
+
from yunmail.client import YunmailClient as Client
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FakeTransport:
|
|
13
|
+
"""Records requests and replays queued (status, payload) responses."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, responses):
|
|
16
|
+
self.responses = list(responses)
|
|
17
|
+
self.requests = []
|
|
18
|
+
|
|
19
|
+
def __call__(self, method, url, headers, body):
|
|
20
|
+
self.requests.append((method, url, headers, body))
|
|
21
|
+
status, payload = self.responses.pop(0)
|
|
22
|
+
return status, {}, json.dumps(payload).encode("utf-8")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def make_client(responses):
|
|
26
|
+
transport = FakeTransport(responses)
|
|
27
|
+
client = Client(
|
|
28
|
+
"test-key", transport=transport, sleeper=lambda _s: None
|
|
29
|
+
)
|
|
30
|
+
return client, transport
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SendEmailTest(unittest.TestCase):
|
|
34
|
+
def test_send_email_posts_expected_payload(self):
|
|
35
|
+
client, transport = make_client([(200, {"id": "m1", "status": "queued"})])
|
|
36
|
+
result = client.send_email(
|
|
37
|
+
"user@example.com", "Welcome", html="<p>Hi</p>", tags=["onboarding"]
|
|
38
|
+
)
|
|
39
|
+
self.assertEqual(result.id, "m1")
|
|
40
|
+
self.assertEqual(result.channel, "email")
|
|
41
|
+
method, url, headers, body = transport.requests[0]
|
|
42
|
+
self.assertEqual(method, "POST")
|
|
43
|
+
self.assertTrue(url.endswith("/email/send"))
|
|
44
|
+
self.assertEqual(headers["Authorization"], "Bearer test-key")
|
|
45
|
+
payload = json.loads(body.decode("utf-8"))
|
|
46
|
+
self.assertEqual(payload["to"], "user@example.com")
|
|
47
|
+
self.assertEqual(payload["tags"], ["onboarding"])
|
|
48
|
+
|
|
49
|
+
def test_send_email_requires_content(self):
|
|
50
|
+
client, _ = make_client([])
|
|
51
|
+
with self.assertRaises(ValueError):
|
|
52
|
+
client.send_email("user@example.com", "No body")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class SendSmsTest(unittest.TestCase):
|
|
56
|
+
def test_send_sms_with_template(self):
|
|
57
|
+
client, transport = make_client([(200, {"id": "s1", "status": "sent"})])
|
|
58
|
+
result = client.send_sms(
|
|
59
|
+
"+8613800000000", template_id="verify", params={"code": "123456"}
|
|
60
|
+
)
|
|
61
|
+
self.assertEqual(result.id, "s1")
|
|
62
|
+
payload = json.loads(transport.requests[0][3].decode("utf-8"))
|
|
63
|
+
self.assertEqual(payload["template_id"], "verify")
|
|
64
|
+
self.assertEqual(payload["params"]["code"], "123456")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ErrorMappingTest(unittest.TestCase):
|
|
68
|
+
def test_401_raises_authentication_error(self):
|
|
69
|
+
client, _ = make_client([(401, {"message": "invalid key"})])
|
|
70
|
+
with self.assertRaises(AuthenticationError):
|
|
71
|
+
client.get_message_status("m1")
|
|
72
|
+
|
|
73
|
+
def test_429_retries_then_raises_rate_limit(self):
|
|
74
|
+
client, transport = make_client([(429, {}), (429, {}), (429, {})])
|
|
75
|
+
with self.assertRaises(RateLimitError):
|
|
76
|
+
client.send_sms("+10000000000", content="hi")
|
|
77
|
+
self.assertEqual(len(transport.requests), 3) # 1 try + 2 retries
|
|
78
|
+
|
|
79
|
+
def test_500_retries_then_succeeds(self):
|
|
80
|
+
client, _ = make_client([(500, {}), (200, {"id": "v1", "status": "calling"})])
|
|
81
|
+
result = client.send_voice_code("+10000000000", "123456")
|
|
82
|
+
self.assertEqual(result.id, "v1")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class WebhookTest(unittest.TestCase):
|
|
86
|
+
def test_verify_webhook(self):
|
|
87
|
+
import hashlib
|
|
88
|
+
import hmac
|
|
89
|
+
|
|
90
|
+
payload = b'{"event":"delivered","id":"m1"}'
|
|
91
|
+
secret = "whsec_test"
|
|
92
|
+
signature = hmac.new(
|
|
93
|
+
secret.encode(), payload, hashlib.sha256
|
|
94
|
+
).hexdigest()
|
|
95
|
+
self.assertTrue(YunmailClient.verify_webhook(payload, signature, secret))
|
|
96
|
+
self.assertFalse(YunmailClient.verify_webhook(payload, "0" * 64, secret))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
if __name__ == "__main__":
|
|
100
|
+
unittest.main()
|