vinworld-vinmail 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.
- vinworld_vinmail-0.1.0/LICENSE +21 -0
- vinworld_vinmail-0.1.0/PKG-INFO +78 -0
- vinworld_vinmail-0.1.0/README.md +53 -0
- vinworld_vinmail-0.1.0/pyproject.toml +37 -0
- vinworld_vinmail-0.1.0/setup.cfg +4 -0
- vinworld_vinmail-0.1.0/src/vinmail/__init__.py +24 -0
- vinworld_vinmail-0.1.0/src/vinmail/attachments.py +199 -0
- vinworld_vinmail-0.1.0/src/vinmail/client.py +207 -0
- vinworld_vinmail-0.1.0/src/vinmail/errors.py +26 -0
- vinworld_vinmail-0.1.0/src/vinmail/py.typed +0 -0
- vinworld_vinmail-0.1.0/src/vinworld_vinmail.egg-info/PKG-INFO +78 -0
- vinworld_vinmail-0.1.0/src/vinworld_vinmail.egg-info/SOURCES.txt +13 -0
- vinworld_vinmail-0.1.0/src/vinworld_vinmail.egg-info/dependency_links.txt +1 -0
- vinworld_vinmail-0.1.0/src/vinworld_vinmail.egg-info/top_level.txt +1 -0
- vinworld_vinmail-0.1.0/tests/test_vinmail.py +105 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vinworld
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vinworld-vinmail
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official zero-dependency Python SDK for the VinMail transactional email API.
|
|
5
|
+
Author-email: Vinworld <dev@vinworlddev.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://vinmail.vinworlddev.com
|
|
8
|
+
Project-URL: Documentation, https://vinmail.vinworlddev.com/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/vinworld/vinmail-sdks
|
|
10
|
+
Keywords: vinmail,vinworld,email,transactional-email,sdk
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# vinworld-vinmail (Python SDK)
|
|
27
|
+
|
|
28
|
+
Official zero-dependency **Python 3.9+ SDK** for the [VinMail](https://vinmail.vinworlddev.com) transactional email API.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install vinworld-vinmail
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quick Start
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import os
|
|
40
|
+
from vinmail import Attachment, VinMail, VinMailError
|
|
41
|
+
|
|
42
|
+
client = VinMail(os.environ["VINMAIL_API_KEY"])
|
|
43
|
+
|
|
44
|
+
result = client.emails.send(
|
|
45
|
+
from_="YourApp <no-reply@yourdomain.com>",
|
|
46
|
+
reply_to="contact@yourdomain.com",
|
|
47
|
+
to="customer@example.com",
|
|
48
|
+
subject="Payment Receipt #1042",
|
|
49
|
+
html="<p>Thank you for your payment!</p>",
|
|
50
|
+
text="Thank you for your payment!",
|
|
51
|
+
attachments=[Attachment.from_path("./receipt-1042.pdf")],
|
|
52
|
+
idempotency_key="receipt-1042",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
print(result) # {'id': '...', 'status': 'queued'}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Using Templates
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
client.emails.send(
|
|
62
|
+
to="customer@example.com",
|
|
63
|
+
template="otp",
|
|
64
|
+
variables={"appName": "YourApp", "code": "482913", "minutes": 10},
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Check Delivery Status
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
details = client.emails.get("em_...")
|
|
72
|
+
print(details["status"], details["events"])
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Business Attachment Policy
|
|
76
|
+
|
|
77
|
+
Allowed formats: `PDF`, `DOC/DOCX`, `XLS/XLSX`, `CSV`, `PPT/PPTX`, `TXT`, `RTF`, `PNG`, `JPG/JPEG`, `WEBP`, `GIF`.
|
|
78
|
+
Limits: up to **5 files**, **5 MB** per file, **7.5 MB** combined per email.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# vinworld-vinmail (Python SDK)
|
|
2
|
+
|
|
3
|
+
Official zero-dependency **Python 3.9+ SDK** for the [VinMail](https://vinmail.vinworlddev.com) transactional email API.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install vinworld-vinmail
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import os
|
|
15
|
+
from vinmail import Attachment, VinMail, VinMailError
|
|
16
|
+
|
|
17
|
+
client = VinMail(os.environ["VINMAIL_API_KEY"])
|
|
18
|
+
|
|
19
|
+
result = client.emails.send(
|
|
20
|
+
from_="YourApp <no-reply@yourdomain.com>",
|
|
21
|
+
reply_to="contact@yourdomain.com",
|
|
22
|
+
to="customer@example.com",
|
|
23
|
+
subject="Payment Receipt #1042",
|
|
24
|
+
html="<p>Thank you for your payment!</p>",
|
|
25
|
+
text="Thank you for your payment!",
|
|
26
|
+
attachments=[Attachment.from_path("./receipt-1042.pdf")],
|
|
27
|
+
idempotency_key="receipt-1042",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
print(result) # {'id': '...', 'status': 'queued'}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Using Templates
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
client.emails.send(
|
|
37
|
+
to="customer@example.com",
|
|
38
|
+
template="otp",
|
|
39
|
+
variables={"appName": "YourApp", "code": "482913", "minutes": 10},
|
|
40
|
+
)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Check Delivery Status
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
details = client.emails.get("em_...")
|
|
47
|
+
print(details["status"], details["events"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Business Attachment Policy
|
|
51
|
+
|
|
52
|
+
Allowed formats: `PDF`, `DOC/DOCX`, `XLS/XLSX`, `CSV`, `PPT/PPTX`, `TXT`, `RTF`, `PNG`, `JPG/JPEG`, `WEBP`, `GIF`.
|
|
53
|
+
Limits: up to **5 files**, **5 MB** per file, **7.5 MB** combined per email.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "vinworld-vinmail"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official zero-dependency Python SDK for the VinMail transactional email API."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
authors = [{ name = "Vinworld", email = "dev@vinworlddev.com" }]
|
|
13
|
+
keywords = ["vinmail", "vinworld", "email", "transactional-email", "sdk"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.9",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = []
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://vinmail.vinworlddev.com"
|
|
30
|
+
Documentation = "https://vinmail.vinworlddev.com/docs"
|
|
31
|
+
Repository = "https://github.com/vinworld/vinmail-sdks"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.packages.find]
|
|
34
|
+
where = ["src"]
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.package-data]
|
|
37
|
+
vinmail = ["py.typed"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from .attachments import (
|
|
2
|
+
ALLOWED_BUSINESS_EXTENSIONS,
|
|
3
|
+
MAX_ATTACHMENTS_PER_EMAIL,
|
|
4
|
+
MAX_SINGLE_ATTACHMENT_BYTES,
|
|
5
|
+
MAX_TOTAL_ATTACHMENTS_BYTES,
|
|
6
|
+
Attachment,
|
|
7
|
+
prepare_attachments,
|
|
8
|
+
)
|
|
9
|
+
from .client import DEFAULT_BASE_URL, SDK_VERSION, EmailsResource, VinMail
|
|
10
|
+
from .errors import VinMailError
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"ALLOWED_BUSINESS_EXTENSIONS",
|
|
14
|
+
"Attachment",
|
|
15
|
+
"DEFAULT_BASE_URL",
|
|
16
|
+
"EmailsResource",
|
|
17
|
+
"MAX_ATTACHMENTS_PER_EMAIL",
|
|
18
|
+
"MAX_SINGLE_ATTACHMENT_BYTES",
|
|
19
|
+
"MAX_TOTAL_ATTACHMENTS_BYTES",
|
|
20
|
+
"SDK_VERSION",
|
|
21
|
+
"VinMail",
|
|
22
|
+
"VinMailError",
|
|
23
|
+
"prepare_attachments",
|
|
24
|
+
]
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict, Iterable, List, Mapping, Optional, Union
|
|
8
|
+
|
|
9
|
+
from .errors import VinMailError
|
|
10
|
+
|
|
11
|
+
MAX_ATTACHMENTS_PER_EMAIL = 5
|
|
12
|
+
MAX_SINGLE_ATTACHMENT_BYTES = 5 * 1024 * 1024
|
|
13
|
+
MAX_TOTAL_ATTACHMENTS_BYTES = int(7.5 * 1024 * 1024)
|
|
14
|
+
|
|
15
|
+
ALLOWED_BUSINESS_EXTENSIONS: Dict[str, str] = {
|
|
16
|
+
".pdf": "application/pdf",
|
|
17
|
+
".doc": "application/msword",
|
|
18
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
19
|
+
".xls": "application/vnd.ms-excel",
|
|
20
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
21
|
+
".csv": "text/csv",
|
|
22
|
+
".ppt": "application/vnd.ms-powerpoint",
|
|
23
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
24
|
+
".txt": "text/plain",
|
|
25
|
+
".rtf": "application/rtf",
|
|
26
|
+
".png": "image/png",
|
|
27
|
+
".jpg": "image/jpeg",
|
|
28
|
+
".jpeg": "image/jpeg",
|
|
29
|
+
".webp": "image/webp",
|
|
30
|
+
".gif": "image/gif",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
_DATA_URL_RE = re.compile(r"^data:[^;]+;base64,(.+)$", re.IGNORECASE | re.DOTALL)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _validate_filename_and_mime(filename: str) -> str:
|
|
37
|
+
clean = filename.strip()
|
|
38
|
+
if not clean:
|
|
39
|
+
raise VinMailError(
|
|
40
|
+
"Each attachment must include a valid filename.",
|
|
41
|
+
status=422,
|
|
42
|
+
code="validation_error",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
dot = clean.rfind(".")
|
|
46
|
+
ext = clean[dot:].lower() if 0 < dot < len(clean) - 1 else ""
|
|
47
|
+
canonical = ALLOWED_BUSINESS_EXTENSIONS.get(ext)
|
|
48
|
+
if canonical is None:
|
|
49
|
+
raise VinMailError(
|
|
50
|
+
f'File "{clean}" is not permitted. Only business documents and images are allowed '
|
|
51
|
+
"(PDF, DOC/DOCX, XLS/XLSX, CSV, PPT/PPTX, TXT, RTF, PNG, JPG, WEBP, GIF).",
|
|
52
|
+
status=422,
|
|
53
|
+
code="validation_error",
|
|
54
|
+
)
|
|
55
|
+
return canonical
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _validate_single_size(filename: str, size_bytes: int) -> None:
|
|
59
|
+
if size_bytes <= 0:
|
|
60
|
+
raise VinMailError(
|
|
61
|
+
f'Attachment "{filename}" cannot be empty.',
|
|
62
|
+
status=422,
|
|
63
|
+
code="validation_error",
|
|
64
|
+
)
|
|
65
|
+
if size_bytes > MAX_SINGLE_ATTACHMENT_BYTES:
|
|
66
|
+
raise VinMailError(
|
|
67
|
+
f'Attachment "{filename}" exceeds the 5 MB per-file size limit.',
|
|
68
|
+
status=422,
|
|
69
|
+
code="validation_error",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Attachment:
|
|
75
|
+
"""Validated business file attachment ready for VinMail."""
|
|
76
|
+
|
|
77
|
+
filename: str
|
|
78
|
+
base64_content: str
|
|
79
|
+
content_type: str
|
|
80
|
+
size_bytes: int
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def from_path(
|
|
84
|
+
cls,
|
|
85
|
+
file_path: Union[str, Path],
|
|
86
|
+
filename: Optional[str] = None,
|
|
87
|
+
) -> "Attachment":
|
|
88
|
+
path_obj = Path(file_path)
|
|
89
|
+
if not path_obj.is_file():
|
|
90
|
+
raise VinMailError(
|
|
91
|
+
f"Attachment file not found: {path_obj}",
|
|
92
|
+
status=422,
|
|
93
|
+
code="validation_error",
|
|
94
|
+
)
|
|
95
|
+
raw = path_obj.read_bytes()
|
|
96
|
+
return cls.from_bytes(filename or path_obj.name, raw)
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_bytes(cls, filename: str, data: bytes) -> "Attachment":
|
|
100
|
+
clean_name = filename.strip()
|
|
101
|
+
mime = _validate_filename_and_mime(clean_name)
|
|
102
|
+
_validate_single_size(clean_name, len(data))
|
|
103
|
+
encoded = base64.b64encode(data).decode("ascii")
|
|
104
|
+
return cls(
|
|
105
|
+
filename=clean_name,
|
|
106
|
+
base64_content=encoded,
|
|
107
|
+
content_type=mime,
|
|
108
|
+
size_bytes=len(data),
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def from_base64(cls, filename: str, content_b64: str) -> "Attachment":
|
|
113
|
+
clean_name = filename.strip()
|
|
114
|
+
mime = _validate_filename_and_mime(clean_name)
|
|
115
|
+
trimmed = content_b64.strip()
|
|
116
|
+
match = _DATA_URL_RE.match(trimmed)
|
|
117
|
+
clean_b64 = re.sub(r"\s+", "", match.group(1) if match else trimmed)
|
|
118
|
+
try:
|
|
119
|
+
decoded = base64.b64decode(clean_b64, validate=True)
|
|
120
|
+
except Exception as exc:
|
|
121
|
+
raise VinMailError(
|
|
122
|
+
f'Attachment "{clean_name}" contains invalid base64 content.',
|
|
123
|
+
status=422,
|
|
124
|
+
code="validation_error",
|
|
125
|
+
) from exc
|
|
126
|
+
_validate_single_size(clean_name, len(decoded))
|
|
127
|
+
return cls(
|
|
128
|
+
filename=clean_name,
|
|
129
|
+
base64_content=clean_b64,
|
|
130
|
+
content_type=mime,
|
|
131
|
+
size_bytes=len(decoded),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def to_payload(self) -> Dict[str, str]:
|
|
135
|
+
return {
|
|
136
|
+
"filename": self.filename,
|
|
137
|
+
"content": self.base64_content,
|
|
138
|
+
"contentType": self.content_type,
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
AttachmentLike = Union[Attachment, Mapping[str, Any]]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def prepare_attachments(items: Iterable[AttachmentLike]) -> List[Dict[str, str]]:
|
|
146
|
+
item_list = list(items)
|
|
147
|
+
if not item_list:
|
|
148
|
+
return []
|
|
149
|
+
if len(item_list) > MAX_ATTACHMENTS_PER_EMAIL:
|
|
150
|
+
raise VinMailError(
|
|
151
|
+
f"At most {MAX_ATTACHMENTS_PER_EMAIL} file attachments are allowed per email.",
|
|
152
|
+
status=422,
|
|
153
|
+
code="validation_error",
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
total_bytes = 0
|
|
157
|
+
payload: List[Dict[str, str]] = []
|
|
158
|
+
|
|
159
|
+
for item in item_list:
|
|
160
|
+
if isinstance(item, Attachment):
|
|
161
|
+
att = item
|
|
162
|
+
elif isinstance(item, Mapping):
|
|
163
|
+
if "path" in item:
|
|
164
|
+
att = Attachment.from_path(item["path"], filename=item.get("filename"))
|
|
165
|
+
elif "filename" in item and "content" in item:
|
|
166
|
+
content = item["content"]
|
|
167
|
+
if isinstance(content, (bytes, bytearray)):
|
|
168
|
+
att = Attachment.from_bytes(str(item["filename"]), bytes(content))
|
|
169
|
+
elif isinstance(content, str):
|
|
170
|
+
att = Attachment.from_base64(str(item["filename"]), content)
|
|
171
|
+
else:
|
|
172
|
+
raise VinMailError(
|
|
173
|
+
"Attachment content must be bytes or a base64 string.",
|
|
174
|
+
status=422,
|
|
175
|
+
code="validation_error",
|
|
176
|
+
)
|
|
177
|
+
else:
|
|
178
|
+
raise VinMailError(
|
|
179
|
+
'Each attachment dict must include "path" or ("filename" and "content").',
|
|
180
|
+
status=422,
|
|
181
|
+
code="validation_error",
|
|
182
|
+
)
|
|
183
|
+
else:
|
|
184
|
+
raise VinMailError(
|
|
185
|
+
"Invalid attachment item.",
|
|
186
|
+
status=422,
|
|
187
|
+
code="validation_error",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
total_bytes += att.size_bytes
|
|
191
|
+
if total_bytes > MAX_TOTAL_ATTACHMENTS_BYTES:
|
|
192
|
+
raise VinMailError(
|
|
193
|
+
"Combined attachment size exceeds the 7.5 MB limit per email.",
|
|
194
|
+
status=422,
|
|
195
|
+
code="validation_error",
|
|
196
|
+
)
|
|
197
|
+
payload.append(att.to_payload())
|
|
198
|
+
|
|
199
|
+
return payload
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import socket
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union
|
|
10
|
+
|
|
11
|
+
from .attachments import AttachmentLike, prepare_attachments
|
|
12
|
+
from .errors import VinMailError
|
|
13
|
+
|
|
14
|
+
DEFAULT_BASE_URL = "https://vinmail-api.vinworlddev.com"
|
|
15
|
+
SDK_VERSION = "0.1.0"
|
|
16
|
+
|
|
17
|
+
TransportCallable = Callable[
|
|
18
|
+
[str, str, Dict[str, str], Optional[bytes], float],
|
|
19
|
+
Tuple[int, Dict[str, str], bytes],
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _default_transport(
|
|
24
|
+
method: str,
|
|
25
|
+
url: str,
|
|
26
|
+
headers: Dict[str, str],
|
|
27
|
+
body: Optional[bytes],
|
|
28
|
+
timeout: float,
|
|
29
|
+
) -> Tuple[int, Dict[str, str], bytes]:
|
|
30
|
+
req = urllib.request.Request(url=url, data=body, headers=headers, method=method)
|
|
31
|
+
try:
|
|
32
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
33
|
+
resp_headers = {k.lower(): v for k, v in resp.headers.items()}
|
|
34
|
+
return int(resp.status), resp_headers, resp.read()
|
|
35
|
+
except urllib.error.HTTPError as err:
|
|
36
|
+
resp_headers = {k.lower(): v for k, v in err.headers.items()} if err.headers else {}
|
|
37
|
+
return int(err.code), resp_headers, err.read()
|
|
38
|
+
except urllib.error.URLError as err:
|
|
39
|
+
raise VinMailError(
|
|
40
|
+
f"Network error contacting VinMail: {err.reason}",
|
|
41
|
+
status=0,
|
|
42
|
+
code="network_error",
|
|
43
|
+
) from err
|
|
44
|
+
except (TimeoutError, socket.timeout) as err:
|
|
45
|
+
raise VinMailError(
|
|
46
|
+
f"VinMail request timed out after {timeout}s.",
|
|
47
|
+
status=0,
|
|
48
|
+
code="timeout",
|
|
49
|
+
) from err
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class EmailsResource:
|
|
53
|
+
def __init__(self, client: "VinMail") -> None:
|
|
54
|
+
self._client = client
|
|
55
|
+
|
|
56
|
+
def send(
|
|
57
|
+
self,
|
|
58
|
+
*,
|
|
59
|
+
to: Union[str, Sequence[str]],
|
|
60
|
+
from_: Optional[str] = None,
|
|
61
|
+
reply_to: Optional[str] = None,
|
|
62
|
+
subject: Optional[str] = None,
|
|
63
|
+
html: Optional[str] = None,
|
|
64
|
+
text: Optional[str] = None,
|
|
65
|
+
template: Optional[str] = None,
|
|
66
|
+
variables: Optional[Mapping[str, Any]] = None,
|
|
67
|
+
tags: Optional[Mapping[str, str]] = None,
|
|
68
|
+
attachments: Optional[Iterable[AttachmentLike]] = None,
|
|
69
|
+
idempotency_key: Optional[str] = None,
|
|
70
|
+
) -> Dict[str, Any]:
|
|
71
|
+
"""Queue a transactional email for immediate delivery (`POST /v1/emails`)."""
|
|
72
|
+
payload: Dict[str, Any] = {
|
|
73
|
+
"to": to if isinstance(to, str) else list(to),
|
|
74
|
+
}
|
|
75
|
+
if from_ is not None:
|
|
76
|
+
payload["from"] = from_
|
|
77
|
+
if reply_to is not None:
|
|
78
|
+
payload["replyTo"] = reply_to
|
|
79
|
+
if subject is not None:
|
|
80
|
+
payload["subject"] = subject
|
|
81
|
+
if html is not None:
|
|
82
|
+
payload["html"] = html
|
|
83
|
+
if text is not None:
|
|
84
|
+
payload["text"] = text
|
|
85
|
+
if template is not None:
|
|
86
|
+
payload["template"] = template
|
|
87
|
+
if variables is not None:
|
|
88
|
+
payload["variables"] = dict(variables)
|
|
89
|
+
if tags is not None:
|
|
90
|
+
payload["tags"] = dict(tags)
|
|
91
|
+
if attachments is not None:
|
|
92
|
+
prepared = prepare_attachments(attachments)
|
|
93
|
+
if prepared:
|
|
94
|
+
payload["attachments"] = prepared
|
|
95
|
+
|
|
96
|
+
extra_headers: Dict[str, str] = {}
|
|
97
|
+
if idempotency_key and idempotency_key.strip():
|
|
98
|
+
extra_headers["Idempotency-Key"] = idempotency_key.strip()
|
|
99
|
+
|
|
100
|
+
return self._client.request("POST", "/v1/emails", payload=payload, extra_headers=extra_headers)
|
|
101
|
+
|
|
102
|
+
def get(self, email_id: str) -> Dict[str, Any]:
|
|
103
|
+
"""Fetch delivery status and event timeline (`GET /v1/emails/:id`)."""
|
|
104
|
+
clean_id = email_id.strip()
|
|
105
|
+
if not clean_id:
|
|
106
|
+
raise VinMailError("Email id is required.", status=422, code="validation_error")
|
|
107
|
+
return self._client.request("GET", f"/v1/emails/{urllib.parse.quote(clean_id, safe='')}")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class VinMail:
|
|
111
|
+
"""Official synchronous VinMail API client."""
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
api_key: str,
|
|
116
|
+
*,
|
|
117
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
118
|
+
timeout: float = 15.0,
|
|
119
|
+
max_retries: int = 2,
|
|
120
|
+
transport: Optional[TransportCallable] = None,
|
|
121
|
+
) -> None:
|
|
122
|
+
trimmed = api_key.strip()
|
|
123
|
+
if not trimmed:
|
|
124
|
+
raise VinMailError(
|
|
125
|
+
"A valid VinMail API key (vm_live_...) is required.",
|
|
126
|
+
status=401,
|
|
127
|
+
code="missing_api_key",
|
|
128
|
+
)
|
|
129
|
+
self._api_key = trimmed
|
|
130
|
+
self._base_url = base_url.rstrip("/")
|
|
131
|
+
self._timeout = max(1.0, float(timeout))
|
|
132
|
+
self._max_retries = max(0, int(max_retries))
|
|
133
|
+
self._transport = transport or _default_transport
|
|
134
|
+
self.emails = EmailsResource(self)
|
|
135
|
+
|
|
136
|
+
def request(
|
|
137
|
+
self,
|
|
138
|
+
method: str,
|
|
139
|
+
path: str,
|
|
140
|
+
*,
|
|
141
|
+
payload: Optional[Dict[str, Any]] = None,
|
|
142
|
+
extra_headers: Optional[Dict[str, str]] = None,
|
|
143
|
+
) -> Dict[str, Any]:
|
|
144
|
+
url = f"{self._base_url}{path}"
|
|
145
|
+
headers: Dict[str, str] = {
|
|
146
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
147
|
+
"Accept": "application/json",
|
|
148
|
+
"User-Agent": f"vinmail-python/{SDK_VERSION}",
|
|
149
|
+
}
|
|
150
|
+
if extra_headers:
|
|
151
|
+
headers.update(extra_headers)
|
|
152
|
+
|
|
153
|
+
encoded_body: Optional[bytes] = None
|
|
154
|
+
if payload is not None:
|
|
155
|
+
headers["Content-Type"] = "application/json"
|
|
156
|
+
encoded_body = json.dumps(payload).encode("utf-8")
|
|
157
|
+
|
|
158
|
+
attempt = 0
|
|
159
|
+
while True:
|
|
160
|
+
try:
|
|
161
|
+
status, resp_headers, raw_body = self._transport(
|
|
162
|
+
method, url, headers, encoded_body, self._timeout
|
|
163
|
+
)
|
|
164
|
+
except VinMailError as exc:
|
|
165
|
+
if attempt < self._max_retries and exc.status == 0:
|
|
166
|
+
attempt += 1
|
|
167
|
+
time.sleep(min(0.3 * (2 ** (attempt - 1)), 3.0))
|
|
168
|
+
continue
|
|
169
|
+
raise
|
|
170
|
+
|
|
171
|
+
decoded: Optional[Dict[str, Any]] = None
|
|
172
|
+
text = raw_body.decode("utf-8", errors="replace") if raw_body else ""
|
|
173
|
+
if text:
|
|
174
|
+
try:
|
|
175
|
+
parsed = json.loads(text)
|
|
176
|
+
if isinstance(parsed, dict):
|
|
177
|
+
decoded = parsed
|
|
178
|
+
except json.JSONDecodeError:
|
|
179
|
+
decoded = None
|
|
180
|
+
|
|
181
|
+
if 200 <= status < 300:
|
|
182
|
+
return decoded or {}
|
|
183
|
+
|
|
184
|
+
retry_after_raw = resp_headers.get("retry-after")
|
|
185
|
+
retry_after: Optional[int] = None
|
|
186
|
+
if retry_after_raw and retry_after_raw.isdigit():
|
|
187
|
+
retry_after = int(retry_after_raw)
|
|
188
|
+
|
|
189
|
+
if attempt < self._max_retries and (status == 429 or status >= 500):
|
|
190
|
+
attempt += 1
|
|
191
|
+
delay = (
|
|
192
|
+
min(float(retry_after), 5.0)
|
|
193
|
+
if retry_after is not None
|
|
194
|
+
else min(0.3 * (2 ** (attempt - 1)), 3.0)
|
|
195
|
+
)
|
|
196
|
+
time.sleep(delay)
|
|
197
|
+
continue
|
|
198
|
+
|
|
199
|
+
err_obj = decoded.get("error") if decoded else None
|
|
200
|
+
if isinstance(err_obj, dict):
|
|
201
|
+
code = str(err_obj.get("code") or f"http_{status}")
|
|
202
|
+
message = str(err_obj.get("message") or f"VinMail HTTP {status}")
|
|
203
|
+
else:
|
|
204
|
+
code = f"http_{status}"
|
|
205
|
+
message = text[:300] if text else f"VinMail request failed with HTTP {status}."
|
|
206
|
+
|
|
207
|
+
raise VinMailError(message, status=status, code=code, retry_after=retry_after)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class VinMailError(Exception):
|
|
7
|
+
"""Raised when a VinMail API request or client-side validation fails."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
message: str,
|
|
12
|
+
status: int = 0,
|
|
13
|
+
code: str = "vinmail_error",
|
|
14
|
+
retry_after: Optional[int] = None,
|
|
15
|
+
) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.message = message
|
|
18
|
+
self.status = status
|
|
19
|
+
self.code = code
|
|
20
|
+
self.retry_after = retry_after
|
|
21
|
+
|
|
22
|
+
def __repr__(self) -> str:
|
|
23
|
+
return (
|
|
24
|
+
f"VinMailError(status={self.status!r}, code={self.code!r}, "
|
|
25
|
+
f"message={self.message!r})"
|
|
26
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vinworld-vinmail
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official zero-dependency Python SDK for the VinMail transactional email API.
|
|
5
|
+
Author-email: Vinworld <dev@vinworlddev.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://vinmail.vinworlddev.com
|
|
8
|
+
Project-URL: Documentation, https://vinmail.vinworlddev.com/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/vinworld/vinmail-sdks
|
|
10
|
+
Keywords: vinmail,vinworld,email,transactional-email,sdk
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# vinworld-vinmail (Python SDK)
|
|
27
|
+
|
|
28
|
+
Official zero-dependency **Python 3.9+ SDK** for the [VinMail](https://vinmail.vinworlddev.com) transactional email API.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install vinworld-vinmail
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quick Start
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import os
|
|
40
|
+
from vinmail import Attachment, VinMail, VinMailError
|
|
41
|
+
|
|
42
|
+
client = VinMail(os.environ["VINMAIL_API_KEY"])
|
|
43
|
+
|
|
44
|
+
result = client.emails.send(
|
|
45
|
+
from_="YourApp <no-reply@yourdomain.com>",
|
|
46
|
+
reply_to="contact@yourdomain.com",
|
|
47
|
+
to="customer@example.com",
|
|
48
|
+
subject="Payment Receipt #1042",
|
|
49
|
+
html="<p>Thank you for your payment!</p>",
|
|
50
|
+
text="Thank you for your payment!",
|
|
51
|
+
attachments=[Attachment.from_path("./receipt-1042.pdf")],
|
|
52
|
+
idempotency_key="receipt-1042",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
print(result) # {'id': '...', 'status': 'queued'}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Using Templates
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
client.emails.send(
|
|
62
|
+
to="customer@example.com",
|
|
63
|
+
template="otp",
|
|
64
|
+
variables={"appName": "YourApp", "code": "482913", "minutes": 10},
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Check Delivery Status
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
details = client.emails.get("em_...")
|
|
72
|
+
print(details["status"], details["events"])
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Business Attachment Policy
|
|
76
|
+
|
|
77
|
+
Allowed formats: `PDF`, `DOC/DOCX`, `XLS/XLSX`, `CSV`, `PPT/PPTX`, `TXT`, `RTF`, `PNG`, `JPG/JPEG`, `WEBP`, `GIF`.
|
|
78
|
+
Limits: up to **5 files**, **5 MB** per file, **7.5 MB** combined per email.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/vinmail/__init__.py
|
|
5
|
+
src/vinmail/attachments.py
|
|
6
|
+
src/vinmail/client.py
|
|
7
|
+
src/vinmail/errors.py
|
|
8
|
+
src/vinmail/py.typed
|
|
9
|
+
src/vinworld_vinmail.egg-info/PKG-INFO
|
|
10
|
+
src/vinworld_vinmail.egg-info/SOURCES.txt
|
|
11
|
+
src/vinworld_vinmail.egg-info/dependency_links.txt
|
|
12
|
+
src/vinworld_vinmail.egg-info/top_level.txt
|
|
13
|
+
tests/test_vinmail.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
vinmail
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
import unittest
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Dict, List, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
_SRC_DIR = str(Path(__file__).resolve().parents[1] / "src")
|
|
12
|
+
if _SRC_DIR not in sys.path:
|
|
13
|
+
sys.path.insert(0, _SRC_DIR)
|
|
14
|
+
|
|
15
|
+
from vinmail import Attachment, VinMail, VinMailError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FakeTransport:
|
|
19
|
+
def __init__(self, responses: List[Tuple[int, Dict[str, str], bytes]]) -> None:
|
|
20
|
+
self.responses = list(responses)
|
|
21
|
+
self.requests: List[Dict[str, object]] = []
|
|
22
|
+
|
|
23
|
+
def __call__(
|
|
24
|
+
self,
|
|
25
|
+
method: str,
|
|
26
|
+
url: str,
|
|
27
|
+
headers: Dict[str, str],
|
|
28
|
+
body: Optional[bytes],
|
|
29
|
+
timeout: float,
|
|
30
|
+
) -> Tuple[int, Dict[str, str], bytes]:
|
|
31
|
+
self.requests.append(
|
|
32
|
+
{"method": method, "url": url, "headers": headers, "body": body}
|
|
33
|
+
)
|
|
34
|
+
return self.responses.pop(0)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class VinMailPythonSdkTest(unittest.TestCase):
|
|
38
|
+
def test_send_with_attachment_and_idempotency(self) -> None:
|
|
39
|
+
transport = FakeTransport([(202, {}, b'{"id":"em_py_1","status":"queued"}')])
|
|
40
|
+
client = VinMail("vm_live_py_key", base_url="https://api.example.test", transport=transport)
|
|
41
|
+
|
|
42
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
43
|
+
pdf = Path(tmp) / "invoice.pdf"
|
|
44
|
+
pdf.write_bytes(b"%PDF-1.4 py invoice")
|
|
45
|
+
|
|
46
|
+
res = client.emails.send(
|
|
47
|
+
from_="Billing <billing@acme.com>",
|
|
48
|
+
to="buyer@example.com",
|
|
49
|
+
subject="Invoice #9",
|
|
50
|
+
text="Attached.",
|
|
51
|
+
attachments=[Attachment.from_path(pdf)],
|
|
52
|
+
idempotency_key="inv-9",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
self.assertEqual(res["id"], "em_py_1")
|
|
56
|
+
req = transport.requests[0]
|
|
57
|
+
headers = req["headers"]
|
|
58
|
+
assert isinstance(headers, dict)
|
|
59
|
+
self.assertEqual(headers["Authorization"], "Bearer vm_live_py_key")
|
|
60
|
+
self.assertEqual(headers["Idempotency-Key"], "inv-9")
|
|
61
|
+
|
|
62
|
+
body_bytes = req["body"]
|
|
63
|
+
assert isinstance(body_bytes, bytes)
|
|
64
|
+
payload = json.loads(body_bytes.decode("utf-8"))
|
|
65
|
+
self.assertEqual(payload["attachments"][0]["filename"], "invoice.pdf")
|
|
66
|
+
self.assertEqual(payload["attachments"][0]["contentType"], "application/pdf")
|
|
67
|
+
self.assertEqual(
|
|
68
|
+
base64.b64decode(payload["attachments"][0]["content"]),
|
|
69
|
+
b"%PDF-1.4 py invoice",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def test_rejects_disallowed_file_type(self) -> None:
|
|
73
|
+
with self.assertRaises(VinMailError) as ctx:
|
|
74
|
+
Attachment.from_bytes("archive.zip", b"PK\x03\x04")
|
|
75
|
+
self.assertEqual(ctx.exception.code, "validation_error")
|
|
76
|
+
|
|
77
|
+
def test_retries_on_503_and_raises_on_422(self) -> None:
|
|
78
|
+
transport = FakeTransport(
|
|
79
|
+
[
|
|
80
|
+
(503, {}, b'{"error":{"code":"unavailable","message":"retry"}}'),
|
|
81
|
+
(202, {}, b'{"id":"em_retry","status":"queued"}'),
|
|
82
|
+
(422, {}, b'{"error":{"code":"domain_not_verified","message":"Not verified"}}'),
|
|
83
|
+
]
|
|
84
|
+
)
|
|
85
|
+
client = VinMail("vm_live_py_key", max_retries=2, transport=transport)
|
|
86
|
+
ok = client.emails.send(to="a@example.com", template="otp", variables={"code": "123456"})
|
|
87
|
+
self.assertEqual(ok["id"], "em_retry")
|
|
88
|
+
self.assertEqual(len(transport.requests), 2)
|
|
89
|
+
|
|
90
|
+
with self.assertRaises(VinMailError) as ctx:
|
|
91
|
+
client.emails.send(to="a@example.com", subject="Hi", text="Hi")
|
|
92
|
+
self.assertEqual(ctx.exception.status, 422)
|
|
93
|
+
self.assertEqual(ctx.exception.code, "domain_not_verified")
|
|
94
|
+
|
|
95
|
+
def test_get_email_status(self) -> None:
|
|
96
|
+
transport = FakeTransport(
|
|
97
|
+
[(200, {}, b'{"id":"em_55","status":"delivered","events":[]}')]
|
|
98
|
+
)
|
|
99
|
+
client = VinMail("vm_live_py_key", transport=transport)
|
|
100
|
+
details = client.emails.get("em_55")
|
|
101
|
+
self.assertEqual(details["status"], "delivered")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
if __name__ == "__main__":
|
|
105
|
+
unittest.main()
|