dsh-mailgun 0.0.0-stage → 0.1.2
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.
- package/LICENSE +21 -0
- package/README.md +148 -2
- package/assets/icon.svg +24 -0
- package/cordis.patch.yml +17 -0
- package/docs/DETAIL.md +57 -0
- package/lib/accounts.js +93 -0
- package/lib/api.js +192 -0
- package/lib/client.js +576 -0
- package/lib/config.js +47 -0
- package/lib/credentials.js +127 -0
- package/lib/index.js +86 -0
- package/lib/service.js +214 -0
- package/lib/settings-web.js +273 -0
- package/lib/store.js +108 -0
- package/lib/tools.js +289 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +6 -0
- package/package.json +66 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 boldandigital
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,149 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-mailgun
|
|
2
|
+
|
|
3
|
+
Mailgun HTTP API tools for DeepSeek Harness: send a message with per-message
|
|
4
|
+
open and click tracking, read the delivery and engagement events, list the
|
|
5
|
+
sending domains and read the domain counters.
|
|
6
|
+
|
|
7
|
+
This plugin is **send-and-track only**. Reading mailboxes is the job of the
|
|
8
|
+
`dsh-email` plugin, which owns IMAP and SMTP. Mailgun has no mailbox server of
|
|
9
|
+
its own, so there is nothing here to read — and the separation keeps a
|
|
10
|
+
send-only sending service out of the account list that `dsh-email` manages.
|
|
11
|
+
|
|
12
|
+
## Several Mailgun accounts
|
|
13
|
+
|
|
14
|
+
One Mailgun account is one API key and one sending domain, so the plugin
|
|
15
|
+
holds a list of accounts rather than a single one. Add them on the harness
|
|
16
|
+
**Settings → Mailgun** page: one card per account, each with a label, the
|
|
17
|
+
sending domain, the region, the From address and the API key.
|
|
18
|
+
|
|
19
|
+
The **Add Mailgun account** form stays open after it saves, so a second
|
|
20
|
+
account is one more click away instead of another trip through the button.
|
|
21
|
+
Several accounts may carry the same label — each one still gets its own id,
|
|
22
|
+
its own key and its own place in the list.
|
|
23
|
+
|
|
24
|
+
Where each piece lives:
|
|
25
|
+
|
|
26
|
+
| What | Where |
|
|
27
|
+
|---|---|
|
|
28
|
+
| The account list (label, domain, region, From) | `~/.dsh/data/dsh-mailgun/accounts.json` |
|
|
29
|
+
| Each account's API key | the credential store, as the record `dsh-mailgun/<id>` |
|
|
30
|
+
|
|
31
|
+
The account list is this plugin's own file rather than a section of the
|
|
32
|
+
harness settings document, on purpose: the harness settings API is the one
|
|
33
|
+
part of DSH whose shape differs between host releases — one exposes a
|
|
34
|
+
namespace-registration API (`ctx.settings.register`), another a per-entry form
|
|
35
|
+
API (`ctx.settings.update`) — and a plugin bound to either breaks on the
|
|
36
|
+
other. The API keys are in the credential store regardless, because that is
|
|
37
|
+
where a secret belongs.
|
|
38
|
+
|
|
39
|
+
The key is **write-only from the browser**: the settings backend reports
|
|
40
|
+
whether a key is stored, never its value, so the page never holds a key it
|
|
41
|
+
did not just type. The account id is derived from the label
|
|
42
|
+
(`Bold & Digital` → `bold-digital`), and it is the id the credential record
|
|
43
|
+
is keyed by.
|
|
44
|
+
|
|
45
|
+
One account is the default; the agent sends from it unless a tool names
|
|
46
|
+
another one.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
The plugin is a local package in this workspace. It is registered in the
|
|
51
|
+
`desktop` profile as a bundle:
|
|
52
|
+
|
|
53
|
+
```yaml
|
|
54
|
+
# ~/.dsh/profiles/desktop/package.json
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"dsh-mailgun": "link:/Users/lars/Documents/deepseek-harness/default-workspace/dsh-mailgun"
|
|
57
|
+
},
|
|
58
|
+
"dsh": { "profile": { "bundles": [ ..., "dsh-mailgun" ] } }
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Then link it into the profile:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
cd ~/.dsh/profiles/desktop && pnpm install
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Configure
|
|
68
|
+
|
|
69
|
+
The bundle patch carries only the fallbacks for an install that keeps one
|
|
70
|
+
account in the patch rather than on the settings page:
|
|
71
|
+
|
|
72
|
+
```yaml
|
|
73
|
+
- insert:
|
|
74
|
+
- id: mailgun
|
|
75
|
+
name: 'dsh-mailgun'
|
|
76
|
+
config:
|
|
77
|
+
domain: '' # fallback sending domain
|
|
78
|
+
region: us # us | eu
|
|
79
|
+
from: '' # fallback From address
|
|
80
|
+
apiKeyRef: MAILGUN_API_KEY
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
A single-account install may also read its key from the plugin-level
|
|
84
|
+
reference instead of the settings page:
|
|
85
|
+
|
|
86
|
+
```yaml
|
|
87
|
+
# ~/.dsh/.credentials.yaml
|
|
88
|
+
refs:
|
|
89
|
+
MAILGUN_API_KEY: "key-..."
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Tools
|
|
93
|
+
|
|
94
|
+
| Tool | What it does |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `mailgun_send` | Send one message. `o:tracking`, `o:tracking-opens` and `o:tracking-clicks` are set on the send itself, so the dashboard toggle does not matter. Returns the Mailgun message id. |
|
|
97
|
+
| `mailgun_events` | The event feed: delivered, opened, clicked, failed, complained, unsubscribed. Filter by event name and recipient. |
|
|
98
|
+
| `mailgun_domains` | The sending domains on the account with their state. |
|
|
99
|
+
| `mailgun_stats` | The aggregate counters for the domain: sent, delivered, opened, clicked, failed. |
|
|
100
|
+
|
|
101
|
+
Every tool takes an optional `account` (id or label) to choose which
|
|
102
|
+
configured Mailgun account to use; it defaults to the default account.
|
|
103
|
+
|
|
104
|
+
`mailgun_send` takes `to`, `subject`, `text` or `html`, plus optional `cc`,
|
|
105
|
+
`bcc`, `from`, `domain`, `tag`, `tracking` (default true) and `testMode`
|
|
106
|
+
(validate without delivering).
|
|
107
|
+
|
|
108
|
+
## Why the HTTP API rather than SMTP
|
|
109
|
+
|
|
110
|
+
Over plain SMTP, Mailgun cannot set the per-message tracking flags — the
|
|
111
|
+
`o:tracking*` options exist only on the HTTP API's `POST /v3/{domain}/messages`
|
|
112
|
+
call. SMTP sends therefore arrive with no open or click tracking at all, and
|
|
113
|
+
the dashboard-side tracking endpoints do not help either. The HTTP API is the
|
|
114
|
+
only path that gives you both the send and its engagement counters.
|
|
115
|
+
|
|
116
|
+
This is also why the plugin does not reuse `dsh-email` for Mailgun: that
|
|
117
|
+
plugin requires every account to carry an IMAP endpoint, which a send-only
|
|
118
|
+
sending service does not have.
|
|
119
|
+
|
|
120
|
+
## Notes
|
|
121
|
+
|
|
122
|
+
- The API base is `https://api.mailgun.net/v3` for the `us` region and
|
|
123
|
+
`https://api.eu.mailgun.net/v3` for `eu`. The region is per account.
|
|
124
|
+
- The key and the sending domain must belong to the same Mailgun account.
|
|
125
|
+
- Tracking flags per message: `o:tracking=yes`, `o:tracking-opens=yes`,
|
|
126
|
+
`o:tracking-clicks=htmlonly`.
|
|
127
|
+
- The raw web route `/_dsh/dsh-mailgun/settings` is localhost-only, because
|
|
128
|
+
it carries API keys. The browser half uses the connection channel route
|
|
129
|
+
`/api/dsh-mailgun/settings` instead.
|
|
130
|
+
- The plugin depends on no harness settings service, so it loads on every
|
|
131
|
+
host release.
|
|
132
|
+
- The plugin's own icon is `assets/icon.svg`, exported as `./icon` and read
|
|
133
|
+
by the Plugin Manager for the plugin row. The settings navigation uses the
|
|
134
|
+
same artwork, so the row and the section show one mark.
|
|
135
|
+
- The section's visible strings go through the Client locale service under
|
|
136
|
+
the `dsh-mailgun.settings` namespace, in English and Chinese.
|
|
137
|
+
|
|
138
|
+
## Test
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
cd dsh-mailgun && npm test
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
The test loads the browser bundle the way the browser does and checks that
|
|
145
|
+
`apply` registers both the `settings.section` and the `settings.section.icon`
|
|
146
|
+
contribution. A React hook called from `apply` throws there ("Invalid hook
|
|
147
|
+
call") and the settings section disappears without any error in the page —
|
|
148
|
+
the test is what catches it.
|
|
2
149
|
|
|
3
|
-
This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
|
package/assets/icon.svg
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Mailgun">
|
|
2
|
+
<title>Mailgun</title>
|
|
3
|
+
<!--
|
|
4
|
+
A paper plane in flight: the send-and-track half of the plugin, drawn
|
|
5
|
+
without the red of the Mailgun brand so the set reads as one family.
|
|
6
|
+
Bold and digital ink plate, brand cyan glyph, paper fold.
|
|
7
|
+
-->
|
|
8
|
+
<defs>
|
|
9
|
+
<linearGradient id="mg-plate" x1="0" y1="0" x2="0" y2="1">
|
|
10
|
+
<stop offset="0" stop-color="#091c36"/>
|
|
11
|
+
<stop offset="1" stop-color="#05121f"/>
|
|
12
|
+
</linearGradient>
|
|
13
|
+
</defs>
|
|
14
|
+
<rect width="64" height="64" rx="14" fill="url(#mg-plate)"/>
|
|
15
|
+
|
|
16
|
+
<!-- the upper wing -->
|
|
17
|
+
<path d="M12 26 L50 15 L26 31 Z" fill="#57ebee"/>
|
|
18
|
+
<!-- the lower fold, in paper, so the plane still reads in greyscale -->
|
|
19
|
+
<path d="M12 26 L26 31 L21 44 Z" fill="#ffffff"/>
|
|
20
|
+
|
|
21
|
+
<!-- monogram -->
|
|
22
|
+
<rect x="36" y="42" width="24" height="18" rx="6" fill="#091c36" stroke="#57ebee" stroke-width="2"/>
|
|
23
|
+
<text x="48" y="55" font-family="ui-sans-serif,-apple-system,Segoe UI,Roboto,sans-serif" font-size="11" font-weight="700" fill="#ffffff" text-anchor="middle" letter-spacing="0.3">MG</text>
|
|
24
|
+
</svg>
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Mailgun API tools.
|
|
2
|
+
#
|
|
3
|
+
# The accounts themselves are managed on the harness Settings page
|
|
4
|
+
# (Settings -> Mailgun): each one carries its sending domain, its region and
|
|
5
|
+
# its From address, and its own API key in the harness credential store.
|
|
6
|
+
#
|
|
7
|
+
# The values below are only the fallbacks for an install that keeps one
|
|
8
|
+
# account in the patch instead of the settings page, and the name of the
|
|
9
|
+
# credential reference a single-account install reads its key from.
|
|
10
|
+
- insert:
|
|
11
|
+
- id: mailgun
|
|
12
|
+
name: 'dsh-mailgun'
|
|
13
|
+
config:
|
|
14
|
+
domain: ''
|
|
15
|
+
region: us
|
|
16
|
+
from: ''
|
|
17
|
+
apiKeyRef: MAILGUN_API_KEY
|
package/docs/DETAIL.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Mailgun
|
|
2
|
+
|
|
3
|
+
Send transactional email through the Mailgun HTTP API, with per-message open
|
|
4
|
+
and click tracking, and read back what happened to it.
|
|
5
|
+
|
|
6
|
+
## What it does
|
|
7
|
+
|
|
8
|
+
The plugin gives the agent four things, all against the Mailgun HTTP API:
|
|
9
|
+
|
|
10
|
+
- **Send** a message through a sending domain, with the tracking flags chosen
|
|
11
|
+
per message: open tracking, click tracking, or both.
|
|
12
|
+
- **Read the events** for a message — delivered, opened, clicked, failed,
|
|
13
|
+
complained — as the Mailgun event feed reports them.
|
|
14
|
+
- **List the sending domains** of an account, so the agent can find the domain
|
|
15
|
+
it is allowed to send from.
|
|
16
|
+
- **Read the domain statistics**: the accepted, delivered, opened, clicked and
|
|
17
|
+
failed counters per domain.
|
|
18
|
+
|
|
19
|
+
## The settings page
|
|
20
|
+
|
|
21
|
+
**Settings → Mailgun** holds one card per account. A card carries:
|
|
22
|
+
|
|
23
|
+
| Field | Meaning |
|
|
24
|
+
|---|---|
|
|
25
|
+
| Label | The name you give the account; the account id is derived from it |
|
|
26
|
+
| Sending domain | The domain Mailgun is allowed to send from |
|
|
27
|
+
| Region | `US` (`api.mailgun.net`) or `EU` (`api.eu.mailgun.net`) |
|
|
28
|
+
| From address | The sender the agent uses |
|
|
29
|
+
| Sender name | The display name that goes with it |
|
|
30
|
+
| API key | The Mailgun private API key |
|
|
31
|
+
|
|
32
|
+
**Add Mailgun account** opens a form for a new account. The form stays open
|
|
33
|
+
after it saves and the fields clear, so a second account — or a third — is one
|
|
34
|
+
more click away. Several accounts may carry the same label: each one still
|
|
35
|
+
gets its own id, its own key and its own card, and the agent can be told
|
|
36
|
+
which one to use by id or by label.
|
|
37
|
+
|
|
38
|
+
**Save** stores the account, **Test connection** checks the key against
|
|
39
|
+
Mailgun and lists the sending domains it can see, **Make default** marks the
|
|
40
|
+
account the agent sends from unless a tool names another one, and **Remove**
|
|
41
|
+
deletes the account and its key.
|
|
42
|
+
|
|
43
|
+
The API key is **write-only from the browser**: the page reports whether a key
|
|
44
|
+
is stored, never its value, so a key never sits in the page unless you just
|
|
45
|
+
typed it. Keys live in the harness credential store as the record
|
|
46
|
+
`dsh-mailgun/<id>`; the account list itself lives in
|
|
47
|
+
`~/.dsh/data/dsh-mailgun/accounts.json`.
|
|
48
|
+
|
|
49
|
+
## Limits
|
|
50
|
+
|
|
51
|
+
- **Send and track only.** Mailgun has no mailbox server, so there is nothing
|
|
52
|
+
to read. Reading mailboxes is the job of the `dsh-email` plugin, which owns
|
|
53
|
+
IMAP and SMTP.
|
|
54
|
+
- **One domain per account.** A Mailgun account may own several sending
|
|
55
|
+
domains; the plugin sends from the one you name on the card.
|
|
56
|
+
- **The events feed is Mailgun's own.** It reports what Mailgun observed, so
|
|
57
|
+
an event can lag behind the send by a few seconds.
|
package/lib/accounts.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Mailgun account model.
|
|
3
|
+
*
|
|
4
|
+
* One account is one Mailgun credential plus the endpoints it belongs to:
|
|
5
|
+
* the sending domain, the region and the From address. The account list
|
|
6
|
+
* lives in `~/.dsh/data/dsh-mailgun/accounts.json`; see `./store.js`.
|
|
7
|
+
*
|
|
8
|
+
* The API key of an account is NOT stored here. It lives in the harness
|
|
9
|
+
* credential store as a record keyed `dsh-mailgun/<id>`, which keeps the
|
|
10
|
+
* secret out of the account document and out of every log line.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import z from '@deepseek-ai/schemastery';
|
|
14
|
+
|
|
15
|
+
/** The credential-record scope this plugin owns. */
|
|
16
|
+
export const CREDENTIAL_SCOPE = 'dsh-mailgun';
|
|
17
|
+
|
|
18
|
+
/** One Mailgun account, without its key. */
|
|
19
|
+
export const AccountSchema = z.object({
|
|
20
|
+
id: z.string().default(''),
|
|
21
|
+
label: z.string().default(''),
|
|
22
|
+
domain: z.string().default(''),
|
|
23
|
+
region: z.union(['us', 'eu']).default('us'),
|
|
24
|
+
from: z.string().default(''),
|
|
25
|
+
senderName: z.string().default(''),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Turn a label into an id the credential store accepts.
|
|
30
|
+
*
|
|
31
|
+
* The credential key grammar is `lowercase-hyphenated` on both sides of the
|
|
32
|
+
* slash, so a label like "Bold & Digital" becomes `bold-digital` and a
|
|
33
|
+
* label like "HostSalt (EU)" becomes `hostsalt-eu`.
|
|
34
|
+
*
|
|
35
|
+
* @param {string} label - the raw label.
|
|
36
|
+
* @returns {string} a usable id, possibly empty when the label has no usable characters.
|
|
37
|
+
*/
|
|
38
|
+
export function slugify(label) {
|
|
39
|
+
return String(label ?? '')
|
|
40
|
+
.toLowerCase()
|
|
41
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
42
|
+
.replace(/^-+|-+$/g, '')
|
|
43
|
+
.replace(/-{2,}/g, '-');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Make an id unique within a set of taken ids.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} base - the wanted id.
|
|
50
|
+
* @param {Iterable<string>} taken - the ids already in use.
|
|
51
|
+
* @returns {string} an id that is not taken.
|
|
52
|
+
*/
|
|
53
|
+
export function uniqueId(base, taken) {
|
|
54
|
+
const used = new Set(taken);
|
|
55
|
+
if (base !== '' && !used.has(base)) return base;
|
|
56
|
+
for (let index = 2; ; index += 1) {
|
|
57
|
+
const candidate = base === '' ? 'account-' + index : base + '-' + index;
|
|
58
|
+
if (!used.has(candidate)) return candidate;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Validate one account row coming from the browser.
|
|
64
|
+
*
|
|
65
|
+
* The id is only kept when the browser named one, because that is what tells
|
|
66
|
+
* an *edited* account apart from a *new* one. Deriving the id from the label
|
|
67
|
+
* here would make every new account look like the account that already owns
|
|
68
|
+
* that label, so adding a second one would replace the first.
|
|
69
|
+
*
|
|
70
|
+
* @param {object} row - the raw row.
|
|
71
|
+
* @returns {{id: string, label: string, domain: string, region: string, from: string}} the clean row.
|
|
72
|
+
*/
|
|
73
|
+
export function cleanAccount(row) {
|
|
74
|
+
const source = row && typeof row === 'object' ? row : {};
|
|
75
|
+
return {
|
|
76
|
+
id: slugify(source.id ?? ''),
|
|
77
|
+
label: String(source.label ?? '').trim(),
|
|
78
|
+
domain: String(source.domain ?? '').trim(),
|
|
79
|
+
region: source.region === 'eu' ? 'eu' : 'us',
|
|
80
|
+
from: String(source.from ?? '').trim(),
|
|
81
|
+
senderName: String(source.senderName ?? '').trim(),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The credential-store key for one account.
|
|
87
|
+
*
|
|
88
|
+
* @param {string} id - the account id.
|
|
89
|
+
* @returns {string} the record key.
|
|
90
|
+
*/
|
|
91
|
+
export function credentialKeyFor(id) {
|
|
92
|
+
return CREDENTIAL_SCOPE + '/' + id;
|
|
93
|
+
}
|
package/lib/api.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Mailgun HTTP API client.
|
|
3
|
+
*
|
|
4
|
+
* Everything speaks the documented v3 REST API: `POST /v3/{domain}/messages`
|
|
5
|
+
* for sending, `GET /v3/{domain}/events` for the delivery and engagement
|
|
6
|
+
* feed, `GET /v3/domains` for the sending domains and
|
|
7
|
+
* `GET /v3/{domain}/stats/total` for the counters.
|
|
8
|
+
*
|
|
9
|
+
* Tracking is per message: `o:tracking`, `o:tracking-opens` and
|
|
10
|
+
* `o:tracking-clicks` are send-time flags, because the dashboard toggle
|
|
11
|
+
* cannot be relied on for a restricted key.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { apiBase } from './config.js';
|
|
15
|
+
|
|
16
|
+
/** The error a failed Mailgun call produces. */
|
|
17
|
+
export class MailgunError extends Error {
|
|
18
|
+
/**
|
|
19
|
+
* @param {string} message - the human-readable failure.
|
|
20
|
+
* @param {object} [details] - the parsed Mailgun error body.
|
|
21
|
+
*/
|
|
22
|
+
constructor(message, details) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = 'MailgunError';
|
|
25
|
+
this.status = details?.status ?? 0;
|
|
26
|
+
this.code = details?.code ?? '';
|
|
27
|
+
this.details = details;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Perform one Mailgun API call.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} options - the call options.
|
|
35
|
+
* @param {string} options.base - the API base URL for the region.
|
|
36
|
+
* @param {string} options.path - the path below the base URL.
|
|
37
|
+
* @param {string} options.apiKey - the Mailgun API key.
|
|
38
|
+
* @param {object} [options.query] - query parameters.
|
|
39
|
+
* @param {URLSearchParams} [options.form] - the form body for a send.
|
|
40
|
+
* @param {string} [options.method] - the HTTP method; defaults to GET.
|
|
41
|
+
* @param {AbortSignal} [options.signal] - the caller's cancellation signal.
|
|
42
|
+
* @returns {Promise<object>} the parsed JSON response.
|
|
43
|
+
*/
|
|
44
|
+
export async function call(options) {
|
|
45
|
+
const { base, path, apiKey, query, form, method = 'GET', signal } = options;
|
|
46
|
+
const url = new URL(base + path);
|
|
47
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
48
|
+
if (value !== undefined && value !== null && value !== '') url.searchParams.set(key, String(value));
|
|
49
|
+
}
|
|
50
|
+
const headers = { Authorization: 'Basic ' + Buffer.from('api:' + apiKey).toString('base64') };
|
|
51
|
+
let body;
|
|
52
|
+
if (form) {
|
|
53
|
+
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
54
|
+
body = form.toString();
|
|
55
|
+
}
|
|
56
|
+
let response;
|
|
57
|
+
try {
|
|
58
|
+
response = await fetch(url, { method, headers, body, signal });
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (error?.name === 'AbortError') throw error;
|
|
62
|
+
throw new MailgunError('Mailgun API request failed: ' + (error?.message ?? error));
|
|
63
|
+
}
|
|
64
|
+
const text = await response.text();
|
|
65
|
+
let parsed;
|
|
66
|
+
try {
|
|
67
|
+
parsed = text === '' ? {} : JSON.parse(text);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
parsed = { message: text.slice(0, 400) };
|
|
71
|
+
}
|
|
72
|
+
if (!response.ok) {
|
|
73
|
+
throw new MailgunError(
|
|
74
|
+
'Mailgun API error ' + response.status + ': ' + (parsed?.message ?? text.slice(0, 300)),
|
|
75
|
+
{ status: response.status, code: parsed?.code ?? '', ...parsed },
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return parsed;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Send one message through the Mailgun API.
|
|
83
|
+
*
|
|
84
|
+
* @param {object} options - the send options.
|
|
85
|
+
* @param {string} options.base - the API base URL.
|
|
86
|
+
* @param {string} options.domain - the sending domain.
|
|
87
|
+
* @param {string} options.apiKey - the Mailgun API key.
|
|
88
|
+
* @param {string} options.from - the From address.
|
|
89
|
+
* @param {string[]} options.to - the recipients.
|
|
90
|
+
* @param {string} [options.cc] - the CC recipients.
|
|
91
|
+
* @param {string} [options.bcc] - the BCC recipients.
|
|
92
|
+
* @param {string} options.subject - the subject line.
|
|
93
|
+
* @param {string} [options.text] - the plain-text body.
|
|
94
|
+
* @param {string} [options.html] - the HTML body.
|
|
95
|
+
* @param {boolean} [options.tracking] - whether to track opens and clicks.
|
|
96
|
+
* @param {string} [options.tag] - the campaign tag.
|
|
97
|
+
* @param {boolean} [options.testMode] - whether to validate without delivering.
|
|
98
|
+
* @param {AbortSignal} [options.signal] - the cancellation signal.
|
|
99
|
+
* @returns {Promise<object>} the Mailgun response (the message id lives in `id`).
|
|
100
|
+
*/
|
|
101
|
+
export async function sendMessage(options) {
|
|
102
|
+
const {
|
|
103
|
+
base, domain, apiKey, from, to, cc, bcc, subject,
|
|
104
|
+
text, html, tracking = true, tag, testMode = false, signal,
|
|
105
|
+
senderName,
|
|
106
|
+
} = options;
|
|
107
|
+
const form = new URLSearchParams();
|
|
108
|
+
form.set('from', from);
|
|
109
|
+
if (senderName) form.set('sender_name', senderName);
|
|
110
|
+
for (const address of to) form.append('to', address);
|
|
111
|
+
for (const address of cc ?? []) form.append('cc', address);
|
|
112
|
+
for (const address of bcc ?? []) form.append('bcc', address);
|
|
113
|
+
form.set('subject', subject);
|
|
114
|
+
if (text) form.set('text', text);
|
|
115
|
+
if (html) form.set('html', html);
|
|
116
|
+
// Tracking is a per-message flag: the dashboard toggle cannot be trusted
|
|
117
|
+
// for a key that cannot open the tracking endpoints.
|
|
118
|
+
if (tracking) {
|
|
119
|
+
form.set('o:tracking', 'yes');
|
|
120
|
+
form.set('o:tracking-opens', 'yes');
|
|
121
|
+
form.set('o:tracking-clicks', 'htmlonly');
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
form.set('o:tracking', 'no');
|
|
125
|
+
}
|
|
126
|
+
if (tag) form.set('o:tag', tag);
|
|
127
|
+
if (testMode) form.set('o:testmode', 'yes');
|
|
128
|
+
return await call({ base, path: '/' + encodeURIComponent(domain) + '/messages', apiKey, method: 'POST', form, signal });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Read the event feed for a domain.
|
|
133
|
+
*
|
|
134
|
+
* @param {object} options - the query options.
|
|
135
|
+
* @param {string} options.base - the API base URL.
|
|
136
|
+
* @param {string} options.domain - the sending domain.
|
|
137
|
+
* @param {string} options.apiKey - the Mailgun API key.
|
|
138
|
+
* @param {string} [options.event] - one event name, or a comma-separated list.
|
|
139
|
+
* @param {string} [options.recipient] - filter by recipient.
|
|
140
|
+
* @param {number} [options.limit] - the number of events to return.
|
|
141
|
+
* @param {boolean} [options.ascending] - the sort order.
|
|
142
|
+
* @param {AbortSignal} [options.signal] - the cancellation signal.
|
|
143
|
+
* @returns {Promise<object>} the parsed events response.
|
|
144
|
+
*/
|
|
145
|
+
export async function listEvents(options) {
|
|
146
|
+
const { base, domain, apiKey, event, recipient, limit = 25, ascending = false, signal } = options;
|
|
147
|
+
return await call({
|
|
148
|
+
base,
|
|
149
|
+
path: '/' + encodeURIComponent(domain) + '/events',
|
|
150
|
+
apiKey,
|
|
151
|
+
query: {
|
|
152
|
+
event,
|
|
153
|
+
recipient,
|
|
154
|
+
limit: Math.min(Math.max(Number(limit) || 25, 1), 300),
|
|
155
|
+
ascending: ascending ? 'yes' : 'no',
|
|
156
|
+
},
|
|
157
|
+
signal,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* List the sending domains on the account.
|
|
163
|
+
*
|
|
164
|
+
* @param {object} options - the query options.
|
|
165
|
+
* @param {string} options.base - the API base URL.
|
|
166
|
+
* @param {string} options.apiKey - the Mailgun API key.
|
|
167
|
+
* @param {number} [options.limit] - the number of domains to return.
|
|
168
|
+
* @param {AbortSignal} [options.signal] - the cancellation signal.
|
|
169
|
+
* @returns {Promise<object>} the parsed domains response.
|
|
170
|
+
*/
|
|
171
|
+
export async function listDomains(options) {
|
|
172
|
+
const { base, apiKey, limit = 20, signal } = options;
|
|
173
|
+
return await call({ base, path: '/domains', apiKey, query: { limit: Math.min(Math.max(Number(limit) || 20, 1), 100) }, signal });
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Read the aggregate counters for a domain.
|
|
178
|
+
*
|
|
179
|
+
* @param {object} options - the query options.
|
|
180
|
+
* @param {string} options.base - the API base URL.
|
|
181
|
+
* @param {string} options.domain - the sending domain.
|
|
182
|
+
* @param {string} options.apiKey - the Mailgun API key.
|
|
183
|
+
* @param {AbortSignal} [options.signal] - the cancellation signal.
|
|
184
|
+
* @returns {Promise<object>} the parsed stats response.
|
|
185
|
+
*/
|
|
186
|
+
export async function domainStats(options) {
|
|
187
|
+
const { base, domain, apiKey, signal } = options;
|
|
188
|
+
return await call({ base, path: '/' + encodeURIComponent(domain) + '/stats/total', apiKey, signal });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The API base for a region. */
|
|
192
|
+
export { apiBase };
|