senddart 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
senddart/__init__.py ADDED
@@ -0,0 +1,80 @@
1
+ """Official SendDart Python SDK.
2
+
3
+ Usage::
4
+
5
+ import senddart
6
+ senddart.api_key = "mb_xxxxxxxxx"
7
+
8
+ email = senddart.Emails.send({
9
+ "from": "Acme <hello@yourdomain.com>",
10
+ "to": ["user@example.com"],
11
+ "subject": "Hello from SendDart",
12
+ "html": "<p>Your first email</p>",
13
+ })
14
+
15
+ Every method returns the parsed JSON response and raises
16
+ :class:`senddart.SendDartError` on any non-2xx status.
17
+ """
18
+
19
+ from typing import Optional
20
+
21
+ from .http_client import (
22
+ DEFAULT_BASE_URL,
23
+ IDEMPOTENCY_KEY_MAX_LENGTH,
24
+ USER_AGENT,
25
+ VERSION,
26
+ )
27
+ from .exceptions import SendDartError
28
+ from .emails import Emails
29
+ from .batch import Batch
30
+ from .domains import Domains
31
+ from .audiences import Audiences
32
+ from .contacts import Contacts
33
+ from .contact_properties import ContactProperties
34
+ from .campaigns import Campaigns
35
+ from .segments import Segments
36
+ from .topics import Topics
37
+ from .templates import Templates
38
+ from .automations import Automations
39
+ from .webhooks import Webhooks, verify_webhook_signature
40
+ from .events import Events
41
+ from .api_keys import ApiKeys
42
+ from .logs import Logs
43
+ from .polls import Polls
44
+
45
+ # ---- Module-level configuration (resend-python style) ----
46
+
47
+ # Your SendDart API key, e.g. senddart.api_key = "mb_xxxxxxxxx"
48
+ api_key: Optional[str] = None
49
+
50
+ # Override to point at a different API host.
51
+ base_url: str = DEFAULT_BASE_URL
52
+
53
+ __version__ = VERSION
54
+
55
+ __all__ = [
56
+ "api_key",
57
+ "base_url",
58
+ "SendDartError",
59
+ "verify_webhook_signature",
60
+ "Emails",
61
+ "Batch",
62
+ "Domains",
63
+ "Audiences",
64
+ "Contacts",
65
+ "ContactProperties",
66
+ "Campaigns",
67
+ "Segments",
68
+ "Topics",
69
+ "Templates",
70
+ "Automations",
71
+ "Webhooks",
72
+ "Events",
73
+ "ApiKeys",
74
+ "Logs",
75
+ "Polls",
76
+ "DEFAULT_BASE_URL",
77
+ "IDEMPOTENCY_KEY_MAX_LENGTH",
78
+ "USER_AGENT",
79
+ "VERSION",
80
+ ]
senddart/api_keys.py ADDED
@@ -0,0 +1,21 @@
1
+ """API keys resource."""
2
+
3
+ from . import http_client
4
+ from .http_client import paginate
5
+
6
+
7
+ class ApiKeys:
8
+ """``senddart.ApiKeys`` — the /api-keys endpoints.
9
+
10
+ Listing only, by design. Keys are created, re-scoped and revoked in the
11
+ SendDart dashboard by a signed-in user: the API answers 403
12
+ ``dashboard_only`` to every API-key caller on those routes, whatever the
13
+ key's scopes. Exposing only ``list`` means a leaked key cannot mint itself
14
+ a replacement or widen its own access."""
15
+
16
+ @classmethod
17
+ def list(cls, params=None):
18
+ """List API keys (non-secret prefixes only; revoked keys excluded).
19
+ Called with no pagination params this returns up to 1,000 keys in one
20
+ response, with ``has_more`` set when that cap bites. GET /api-keys"""
21
+ return http_client.request("GET", f"/api-keys{paginate(params)}")
senddart/audiences.py ADDED
@@ -0,0 +1,56 @@
1
+ """Audiences resource (incl. Google Sheet contact import)."""
2
+
3
+ from typing import TypedDict
4
+
5
+ from . import http_client
6
+ from .http_client import paginate, path_escape as _e
7
+
8
+
9
+ class CreateParams(TypedDict):
10
+ name: str
11
+
12
+
13
+ class ImportSheetParams(TypedDict, total=False):
14
+ url: str # required: link-shared Google Sheet URL
15
+ segment_name: str
16
+
17
+
18
+ class Audiences:
19
+ """``senddart.Audiences`` — the /audiences endpoints."""
20
+
21
+ CreateParams = CreateParams
22
+ ImportSheetParams = ImportSheetParams
23
+
24
+ @classmethod
25
+ def create(cls, params):
26
+ """Create an audience. POST /audiences"""
27
+ return http_client.request("POST", "/audiences", params)
28
+
29
+ @classmethod
30
+ def get(cls, audience_id):
31
+ """Retrieve an audience. GET /audiences/:id"""
32
+ return http_client.request("GET", f"/audiences/{_e(audience_id)}")
33
+
34
+ @classmethod
35
+ def list(cls, params=None):
36
+ """List audiences. GET /audiences"""
37
+ return http_client.request("GET", f"/audiences{paginate(params)}")
38
+
39
+ @classmethod
40
+ def update(cls, audience_id, params):
41
+ """Rename an audience. PATCH /audiences/:id"""
42
+ return http_client.request("PATCH", f"/audiences/{_e(audience_id)}", params)
43
+
44
+ @classmethod
45
+ def import_sheet(cls, audience_id, params):
46
+ """Import contacts from a link-shared Google Sheet. Header columns
47
+ become contact properties (usable as ``{{merge_tags}}``); rows land in
48
+ a fresh segment. POST /audiences/:id/contacts/import-sheet"""
49
+ return http_client.request(
50
+ "POST", f"/audiences/{_e(audience_id)}/contacts/import-sheet", params
51
+ )
52
+
53
+ @classmethod
54
+ def remove(cls, audience_id):
55
+ """Delete an audience. DELETE /audiences/:id"""
56
+ return http_client.request("DELETE", f"/audiences/{_e(audience_id)}")
@@ -0,0 +1,175 @@
1
+ """Automations resource — DOMAIN-FIRST: every automation belongs to one of
2
+ your sending domains (``domain`` is REQUIRED on create). Only ``Events.send``
3
+ calls with the same ``domain`` trigger it."""
4
+
5
+ from typing import Any, Dict, List, TypedDict
6
+
7
+ from . import http_client
8
+ from .http_client import build_query, paginate, path_escape as _e
9
+
10
+
11
+ class CreateParams(TypedDict, total=False):
12
+ name: str # required
13
+ domain: str # REQUIRED: the sending domain this automation belongs to
14
+ trigger: str # e.g. 'contact.created', 'senddart:schedule', 'email.opened', or a custom event name
15
+ # {'at': ISO 8601 instant, 'timezone': IANA name} — required with the
16
+ # 'senddart:schedule' trigger; not accepted on any other.
17
+ trigger_config: Dict[str, str]
18
+ status: str # 'enabled' | 'disabled' (default 'disabled')
19
+ steps: List[Dict[str, Any]] # optional inline step graph
20
+ connections: List[Dict[str, str]] # optional typed edges between step keys
21
+
22
+
23
+ class UpdateParams(TypedDict, total=False):
24
+ name: str
25
+ status: str # 'enabled' | 'disabled'
26
+ domain: str # re-point at another domain (disabled automations only)
27
+ # Re-point the trigger (disabled automations only) — same vocabulary as
28
+ # create. Changing it away from 'senddart:schedule' clears trigger_config.
29
+ trigger: str
30
+ trigger_key: str # graph key the trigger node is addressed by (default 'trigger')
31
+ # {'at', 'timezone'} — update the 'senddart:schedule' trigger's schedule.
32
+ trigger_config: Dict[str, str]
33
+ connections: List[Dict[str, str]] # disabled automations only
34
+
35
+
36
+ class AddStepParams(TypedDict, total=False):
37
+ # 'trigger' is NOT a step type here — the trigger is set on the automation
38
+ # itself. Documented names ('send_email', 'wait_for_event') and internal
39
+ # ones ('send', 'wait') are both accepted.
40
+ type: str # required: 'delay' | 'send_email' | 'wait_for_event' | 'condition' | 'split' | 'add_to_segment' | 'contact_update' | 'contact_delete'
41
+ config: Dict[str, Any]
42
+ key: str
43
+
44
+
45
+ class UpdateStepParams(TypedDict, total=False):
46
+ # REQUIRED on every call: the PATCH re-validates the WHOLE step with the
47
+ # same validator the add path uses, so a body without `type` is a 422
48
+ # ("type must be one of: ...") — it does not mean "leave the type alone".
49
+ # Resend the step's current type even when only `config` changes.
50
+ type: str
51
+ config: Dict[str, Any] # REPLACES the stored config wholesale; omissions are dropped
52
+ # No `key` here: a step's graph key is fixed at creation so the connections
53
+ # referencing it keep working. Pass `key` to add_step, or delete and re-add
54
+ # the step to re-key it.
55
+
56
+
57
+ class RunListParams(TypedDict, total=False):
58
+ limit: int
59
+ after: str
60
+ before: str
61
+ status: str # comma-separated, e.g. 'running,failed'
62
+
63
+
64
+ class AiParams(TypedDict, total=False):
65
+ prompt: str # required, max 2000 characters
66
+ template_ids: List[str] # first 10 kept
67
+ events: List[str] # first 10 kept
68
+ # {'from': step or trigger key, 'type'?: edge type, 'before'?: step key} —
69
+ # supplying it APPENDS to the existing graph; omitting it builds a whole
70
+ # workflow and requires the automation to have no steps yet.
71
+ attach: Dict[str, str]
72
+
73
+
74
+ class Automations:
75
+ """``senddart.Automations`` — the /automations endpoints."""
76
+
77
+ CreateParams = CreateParams
78
+ UpdateParams = UpdateParams
79
+ AddStepParams = AddStepParams
80
+ UpdateStepParams = UpdateStepParams
81
+ RunListParams = RunListParams
82
+ AiParams = AiParams
83
+
84
+ @classmethod
85
+ def create(cls, params):
86
+ """Create an automation (``domain`` is required). POST /automations"""
87
+ return http_client.request("POST", "/automations", params)
88
+
89
+ @classmethod
90
+ def get(cls, automation_id):
91
+ """Retrieve an automation (with steps/connections/enrollments).
92
+ GET /automations/:id"""
93
+ return http_client.request("GET", f"/automations/{_e(automation_id)}")
94
+
95
+ @classmethod
96
+ def list(cls, params=None):
97
+ """List automations. GET /automations"""
98
+ return http_client.request("GET", f"/automations{paginate(params)}")
99
+
100
+ @classmethod
101
+ def update(cls, automation_id, params):
102
+ """Update an automation. PATCH /automations/:id"""
103
+ return http_client.request("PATCH", f"/automations/{_e(automation_id)}", params)
104
+
105
+ @classmethod
106
+ def add_step(cls, automation_id, params):
107
+ """Append a step to an automation. The automation must be DISABLED —
108
+ editing the graph of an enabled automation is a 422.
109
+ POST /automations/:id/steps"""
110
+ return http_client.request("POST", f"/automations/{_e(automation_id)}/steps", params)
111
+
112
+ @classmethod
113
+ def update_step(cls, automation_id, step_id, params):
114
+ """Update a step. The automation must be DISABLED. The step is
115
+ REPLACED, not merged: ``type`` is required on every call (a body
116
+ without it is a 422, even when only ``config`` changes) and ``config``
117
+ overwrites the stored config wholesale. A step's graph ``key`` is
118
+ create-only — it is ignored here and the response echoes the STORED key
119
+ back, so use ``add_step`` with a ``key``, or delete and re-add the step,
120
+ to change it. PATCH /automations/:id/steps/:step_id"""
121
+ return http_client.request(
122
+ "PATCH", f"/automations/{_e(automation_id)}/steps/{_e(step_id)}", params
123
+ )
124
+
125
+ @classmethod
126
+ def delete_step(cls, automation_id, step_id):
127
+ """Delete a step from an automation. The automation must be DISABLED.
128
+ DELETE /automations/:id/steps/:step_id"""
129
+ return http_client.request(
130
+ "DELETE", f"/automations/{_e(automation_id)}/steps/{_e(step_id)}"
131
+ )
132
+
133
+ @classmethod
134
+ def create_with_ai(cls, automation_id, params):
135
+ """Build or extend an automation's steps from a natural-language
136
+ ``prompt`` ("Create with AI"). Pass ``attach`` to append to an existing
137
+ graph; without it the automation must have no steps yet. The automation
138
+ must be stopped, and this route is limited to 20 requests per minute
139
+ per account. POST /automations/:id/ai"""
140
+ return http_client.request("POST", f"/automations/{_e(automation_id)}/ai", params)
141
+
142
+ @classmethod
143
+ def runs(cls, automation_id, params=None):
144
+ """List an automation's runs, optionally filtered to a comma-separated
145
+ ``status`` list (e.g. ``'running,failed'``).
146
+ GET /automations/:id/runs"""
147
+ params = params or {}
148
+ qs = build_query(
149
+ {
150
+ "limit": params.get("limit"),
151
+ "after": params.get("after"),
152
+ "before": params.get("before"),
153
+ "status": params.get("status"),
154
+ }
155
+ )
156
+ return http_client.request("GET", f"/automations/{_e(automation_id)}/runs{qs}")
157
+
158
+ @classmethod
159
+ def get_run(cls, automation_id, run_id):
160
+ """Retrieve a single automation run (with its step trace).
161
+ GET /automations/:id/runs/:run_id"""
162
+ return http_client.request(
163
+ "GET", f"/automations/{_e(automation_id)}/runs/{_e(run_id)}"
164
+ )
165
+
166
+ @classmethod
167
+ def stop(cls, automation_id):
168
+ """Stop an automation — prevents new runs; in-progress runs finish.
169
+ POST /automations/:id/stop"""
170
+ return http_client.request("POST", f"/automations/{_e(automation_id)}/stop")
171
+
172
+ @classmethod
173
+ def remove(cls, automation_id):
174
+ """Delete an automation. DELETE /automations/:id"""
175
+ return http_client.request("DELETE", f"/automations/{_e(automation_id)}")
senddart/batch.py ADDED
@@ -0,0 +1,40 @@
1
+ """Batch send resource — ``senddart.Batch.send([...])``."""
2
+
3
+ from . import http_client
4
+
5
+
6
+ class Batch:
7
+ """``senddart.Batch`` — the /emails/batch endpoint."""
8
+
9
+ @classmethod
10
+ def send(cls, params, options=None):
11
+ """Send up to 100 emails in one request. POST /emails/batch
12
+
13
+ ``params`` is a list of :class:`senddart.Emails.SendParams` dicts.
14
+ Batch items reject ``attachments`` and ``scheduled_at`` — send those
15
+ individually via ``senddart.Emails.send``.
16
+
17
+ TWO MODES, chosen by batch SIZE alone, and BOTH are success — branch on
18
+ ``result.get("queued")``, not on the absence of an error:
19
+
20
+ * **1-40 emails** are sent while the request is open (200). The response
21
+ carries NO ``queued`` key at all — never ``queued: False``. Every id
22
+ in ``result["data"]`` has already been handed to the mail service.
23
+ * **41-100 emails** are accepted, written as due-now sends and delivered
24
+ in the background (202): ``result["queued"]`` is ``True`` and
25
+ ``result["queued_count"] == len(result["data"])``. Those ids are real
26
+ (``senddart.Emails.get(id)`` works) but the emails start at
27
+ ``scheduled`` and NOTHING has been transmitted yet — reporting them as
28
+ sent, or tearing down state on return, is wrong for this case.
29
+
30
+ Queuing is the only way the documented 100-email maximum can be accepted
31
+ at all: 100 inline sends run past the platform's request ceiling. A batch
32
+ carrying an ``@test.senddart.com`` simulator recipient in ``to``, ``cc`` or
33
+ ``bcc`` stays inline at any size.
34
+
35
+ An inline batch near the 40-email boundary can take ~100s server-side,
36
+ far past the 30s default ``senddart.timeout`` — raise it if you send
37
+ batches that large, and always pass ``options={"idempotency_key": ...}``,
38
+ since a client that gives up mid-request cannot tell what was already
39
+ sent."""
40
+ return http_client.request("POST", "/emails/batch", params, options)
senddart/campaigns.py ADDED
@@ -0,0 +1,128 @@
1
+ """Campaigns resource — bulk sends to a domain's contact pool (DOMAIN-FIRST:
2
+ ``domain`` is required on create and picks the contact pool the campaign
3
+ targets; ``from`` may be a different verified domain)."""
4
+
5
+ from typing import Any, Dict, List, TypedDict, Union
6
+
7
+ from . import http_client
8
+ from .http_client import paginate, path_escape as _e
9
+
10
+ CreateParams = TypedDict(
11
+ "CreateParams",
12
+ {
13
+ "domain": str, # REQUIRED: the sending domain whose contact pool to target
14
+ "from": str, # required
15
+ "subject": str, # required
16
+ "html": str,
17
+ "text": str,
18
+ "reply_to": Union[str, List[str]],
19
+ "preview_text": str,
20
+ "name": str,
21
+ "segment_id": str, # target a segment instead of everyone
22
+ "topic_id": str, # gate recipients by a topic subscription
23
+ "recurrence": str, # 'daily' | 'weekly' | 'monthly'
24
+ "recurrence_every": int, # periods between recurring sends (1-365)
25
+ "ab_test": Dict[str, Any], # A/B-test configuration
26
+ "followups": List[Dict[str, Any]], # engagement follow-ups (max 5)
27
+ "list_to": bool,
28
+ "unsubscribe_policy": str, # 'account' | 'domain' | 'ignore'
29
+ "send": bool, # send immediately on create
30
+ "scheduled_at": str,
31
+ "schedule_timezone": str, # IANA zone the schedule + daily batching run in
32
+ "daily_batch_size": int, # max recipients per batch-day (1-100000)
33
+ },
34
+ total=False,
35
+ )
36
+
37
+ UpdateParams = TypedDict(
38
+ "UpdateParams",
39
+ {
40
+ "name": str,
41
+ "from": str,
42
+ "subject": str,
43
+ "html": str,
44
+ "text": str,
45
+ "reply_to": Union[str, List[str]],
46
+ "preview_text": str,
47
+ "domain": str, # re-point at another domain's pool (draft campaigns only)
48
+ "segment_id": Union[str, None],
49
+ "topic_id": Union[str, None],
50
+ "recurrence": str,
51
+ "recurrence_every": int,
52
+ "ab_test": Dict[str, Any],
53
+ "followups": List[Dict[str, Any]], # replace pending follow-ups (max 5; [] clears)
54
+ "list_to": bool, # enable (True) or clear (False) the mailing-list To address
55
+ "unsubscribe_policy": str, # 'account' | 'domain' | 'ignore'
56
+ "schedule_timezone": Union[str, None], # IANA zone (None clears to account tz)
57
+ "daily_batch_size": Union[int, None], # 1-100000 (None clears)
58
+ },
59
+ total=False,
60
+ )
61
+
62
+
63
+ class Campaigns:
64
+ """``senddart.Campaigns`` — the /campaigns endpoints."""
65
+
66
+ CreateParams = CreateParams
67
+ UpdateParams = UpdateParams
68
+
69
+ @classmethod
70
+ def create(cls, params):
71
+ """Create a campaign (``domain`` is required). POST /campaigns"""
72
+ return http_client.request("POST", "/campaigns", params)
73
+
74
+ @classmethod
75
+ def get(cls, campaign_id):
76
+ """Retrieve a campaign. GET /campaigns/:id"""
77
+ return http_client.request("GET", f"/campaigns/{_e(campaign_id)}")
78
+
79
+ @classmethod
80
+ def list(cls, params=None):
81
+ """List campaigns. GET /campaigns"""
82
+ return http_client.request("GET", f"/campaigns{paginate(params)}")
83
+
84
+ @classmethod
85
+ def update(cls, campaign_id, params):
86
+ """Update a campaign. PATCH /campaigns/:id"""
87
+ return http_client.request("PATCH", f"/campaigns/{_e(campaign_id)}", params)
88
+
89
+ @classmethod
90
+ def send(cls, campaign_id, params=None):
91
+ """Send now, or schedule with ``{"scheduled_at": ...}``. An optional
92
+ ``"schedule_timezone"`` (IANA name) is persisted onto the campaign so
93
+ daily batching evaluates batch-days in that zone.
94
+ POST /campaigns/:id/send"""
95
+ return http_client.request(
96
+ "POST", f"/campaigns/{_e(campaign_id)}/send", params if params is not None else {}
97
+ )
98
+
99
+ @classmethod
100
+ def cancel(cls, campaign_id):
101
+ """Cancel a scheduled campaign (returns it to draft).
102
+ POST /campaigns/:id/cancel"""
103
+ return http_client.request("POST", f"/campaigns/{_e(campaign_id)}/cancel")
104
+
105
+ @classmethod
106
+ def stats(cls, campaign_id):
107
+ """Per-campaign analytics (counts, engagement rates, top links).
108
+ GET /campaigns/:id/stats"""
109
+ return http_client.request("GET", f"/campaigns/{_e(campaign_id)}/stats")
110
+
111
+ @classmethod
112
+ def engagement(cls, campaign_id):
113
+ """Who opened, clicked and replied — per-recipient engagement rows.
114
+ Each of the three lists is capped at 500 rows and this endpoint is not
115
+ paginated. GET /campaigns/:id/engagement"""
116
+ return http_client.request("GET", f"/campaigns/{_e(campaign_id)}/engagement")
117
+
118
+ @classmethod
119
+ def ab(cls, campaign_id):
120
+ """A/B winner evaluation for an A/B campaign (422 when the campaign is
121
+ not an A/B test). Note the camelCase ``zScore`` / ``pValue`` keys in the
122
+ result. GET /campaigns/:id/ab"""
123
+ return http_client.request("GET", f"/campaigns/{_e(campaign_id)}/ab")
124
+
125
+ @classmethod
126
+ def remove(cls, campaign_id):
127
+ """Delete a campaign. DELETE /campaigns/:id"""
128
+ return http_client.request("DELETE", f"/campaigns/{_e(campaign_id)}")
@@ -0,0 +1,50 @@
1
+ """Contact properties (custom fields) resource."""
2
+
3
+ from typing import TypedDict, Union
4
+
5
+ from . import http_client
6
+ from .http_client import paginate, path_escape as _e
7
+
8
+
9
+ class CreateParams(TypedDict, total=False):
10
+ key: str # REQUIRED: canonical merge-tag key (`name` is accepted as an alias)
11
+ name: str # alias for `key`
12
+ type: str # 'string' (default) | 'number' — immutable once created
13
+ fallback_value: Union[str, int, float]
14
+
15
+
16
+ class UpdateParams(TypedDict, total=False):
17
+ fallback_value: Union[str, int, float, None] # only fallback_value is mutable
18
+
19
+
20
+ class ContactProperties:
21
+ """``senddart.ContactProperties`` — the /contact-properties endpoints."""
22
+
23
+ CreateParams = CreateParams
24
+ UpdateParams = UpdateParams
25
+
26
+ @classmethod
27
+ def create(cls, params):
28
+ """Register a custom contact property. POST /contact-properties"""
29
+ return http_client.request("POST", "/contact-properties", params)
30
+
31
+ @classmethod
32
+ def get(cls, property_id):
33
+ """Retrieve a contact property. GET /contact-properties/:id"""
34
+ return http_client.request("GET", f"/contact-properties/{_e(property_id)}")
35
+
36
+ @classmethod
37
+ def list(cls, params=None):
38
+ """List contact properties. GET /contact-properties"""
39
+ return http_client.request("GET", f"/contact-properties{paginate(params)}")
40
+
41
+ @classmethod
42
+ def update(cls, property_id, params):
43
+ """Update a contact property (key/type are immutable).
44
+ PATCH /contact-properties/:id"""
45
+ return http_client.request("PATCH", f"/contact-properties/{_e(property_id)}", params)
46
+
47
+ @classmethod
48
+ def remove(cls, property_id):
49
+ """Delete a contact property. DELETE /contact-properties/:id"""
50
+ return http_client.request("DELETE", f"/contact-properties/{_e(property_id)}")