mailpit-api 1.3.0 → 1.4.0-alpha

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/dist/index.mjs ADDED
@@ -0,0 +1,538 @@
1
+ // src/index.ts
2
+ import axios, {
3
+ isAxiosError
4
+ } from "axios";
5
+ var MailpitClient = class {
6
+ axiosInstance;
7
+ /**
8
+ * Creates an instance of {@link MailpitClient}.
9
+ * @param baseURL - The base URL of the Mailpit API.
10
+ * @param auth - Optional authentication credentials.
11
+ * @param auth.username - The username for basic authentication.
12
+ * @param auth.password - The password for basic authentication.
13
+ * @example No Auth
14
+ * ```typescript
15
+ * const mailpit = new MailpitClient("http://localhost:8025");
16
+ * ```
17
+ * @example Basic Auth
18
+ * ```typescript
19
+ * const mailpit = new MailpitClient("http://localhost:8025", {
20
+ * username: "admin",
21
+ * password: "supersecret",
22
+ * });
23
+ * ```
24
+ */
25
+ constructor(baseURL, auth) {
26
+ this.axiosInstance = axios.create({
27
+ baseURL,
28
+ auth,
29
+ validateStatus: function(status) {
30
+ return status === 200;
31
+ }
32
+ });
33
+ }
34
+ async handleRequest(request, options = { fullResponse: false }) {
35
+ try {
36
+ const response = await request();
37
+ return options.fullResponse ? response : response.data;
38
+ } catch (error) {
39
+ if (isAxiosError(error)) {
40
+ const url = error.config?.url || "UNKNOWN URL";
41
+ const method = error.config?.method?.toUpperCase() || "UNKNOWN METHOD";
42
+ if (error.response) {
43
+ throw new Error(
44
+ `Mailpit API Error: ${error.response.status.toString()} ${error.response.statusText} at ${method} ${url}: ${JSON.stringify(error.response.data)}`
45
+ );
46
+ } else if (error.request) {
47
+ throw new Error(
48
+ `Mailpit API Error: No response received from server at ${method} ${url}`
49
+ );
50
+ } else {
51
+ throw new Error(
52
+ `Mailpit API Error: ${error.toString()} at ${method} ${url}`
53
+ );
54
+ }
55
+ } else {
56
+ throw new Error(`Unexpected Error: ${error}`);
57
+ }
58
+ }
59
+ }
60
+ /**
61
+ * Retrieves information about the Mailpit instance.
62
+ *
63
+ * @returns Basic runtime information, message totals and latest release version.
64
+ * @example
65
+ * ```typescript
66
+ * const info = await mailpit.getInfo();
67
+ * ```
68
+ */
69
+ async getInfo() {
70
+ return await this.handleRequest(
71
+ () => this.axiosInstance.get("/api/v1/info")
72
+ );
73
+ }
74
+ /**
75
+ * Retrieves the configuration of the Mailpit web UI.
76
+ * @remarks Intended for web UI only!
77
+ * @returns Configuration settings
78
+ * @example
79
+ * ```typescript
80
+ * const config = await mailpit.getConfiguration();
81
+ * ```
82
+ */
83
+ async getConfiguration() {
84
+ return await this.handleRequest(
85
+ () => this.axiosInstance.get("/api/v1/webui")
86
+ );
87
+ }
88
+ /**
89
+ * Retrieves a summary of a specific message and marks it as read.
90
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
91
+ * @returns Message summary
92
+ * @example
93
+ * ```typescript
94
+ * const message = await mailpit.getMessageSummary();
95
+ * ```
96
+ */
97
+ async getMessageSummary(id = "latest") {
98
+ return await this.handleRequest(
99
+ () => this.axiosInstance.get(
100
+ `/api/v1/message/${id}`
101
+ )
102
+ );
103
+ }
104
+ /**
105
+ * Retrieves the headers of a specific message.
106
+ * @remarks Header keys are returned alphabetically.
107
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
108
+ * @returns Message headers
109
+ * @example
110
+ * ```typescript
111
+ * const headers = await mailpit.getMessageHeaders();
112
+ * ```
113
+ */
114
+ async getMessageHeaders(id = "latest") {
115
+ return await this.handleRequest(
116
+ () => this.axiosInstance.get(
117
+ `/api/v1/message/${id}/headers`
118
+ )
119
+ );
120
+ }
121
+ /**
122
+ * Retrieves a specific attachment from a message.
123
+ * @param id - Message database ID or "latest"
124
+ * @param partID - The attachment part ID
125
+ * @returns Attachment as binary data and the content type
126
+ * @example
127
+ * ```typescript
128
+ * const message = await mailpit.getMessageSummary();
129
+ * if (message.Attachments.length) {
130
+ * const attachment = await mailpit.getMessageAttachment(message.ID, message.Attachments[0].PartID);
131
+ * // Do something with the attachment data
132
+ * }
133
+ * ```
134
+ */
135
+ async getMessageAttachment(id, partID) {
136
+ const response = await this.handleRequest(
137
+ () => this.axiosInstance.get(
138
+ `/api/v1/message/${id}/part/${partID}`,
139
+ { responseType: "arraybuffer" }
140
+ ),
141
+ { fullResponse: true }
142
+ );
143
+ return {
144
+ data: response.data,
145
+ contentType: response.headers["content-type"]
146
+ };
147
+ }
148
+ /**
149
+ * Generates a cropped 180x120 JPEG thumbnail of an image attachment from a message.
150
+ * Only image attachments are supported.
151
+ * @remarks
152
+ * If the image is smaller than 180x120 then the image is padded.
153
+ * If the attachment is not an image then a blank image is returned.
154
+ * @param id - Message database ID or "latest"
155
+ * @param partID - The attachment part ID
156
+ * @returns Image attachment thumbnail as binary data and the content type
157
+ * @example
158
+ * ```typescript
159
+ * const message = await mailpit.getMessageSummary();
160
+ * if (message.Attachments.length) {
161
+ * const thumbnail = await mailpit.getAttachmentThumbnail(message.ID, message.Attachments[0].PartID);
162
+ * // Do something with the thumbnail data
163
+ * }
164
+ * ```
165
+ */
166
+ async getAttachmentThumbnail(id, partID) {
167
+ const response = await this.handleRequest(
168
+ () => this.axiosInstance.get(
169
+ `/api/v1/message/${id}/part/${partID}/thumb`,
170
+ {
171
+ responseType: "arraybuffer"
172
+ }
173
+ ),
174
+ { fullResponse: true }
175
+ );
176
+ return {
177
+ data: response.data,
178
+ contentType: response.headers["content-type"]
179
+ };
180
+ }
181
+ /**
182
+ * Retrieves the full email message source as plain text.
183
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
184
+ * @returns Plain text message source
185
+ * @example
186
+ * ```typescript
187
+ * const messageSource = await mailpit.getMessageSource();
188
+ * ```
189
+ */
190
+ async getMessageSource(id = "latest") {
191
+ return await this.handleRequest(
192
+ () => this.axiosInstance.get(`/api/v1/message/${id}/raw`)
193
+ );
194
+ }
195
+ /**
196
+ * Release a message via a pre-configured external SMTP server.
197
+ * @remarks This is only enabled if message relaying has been configured.
198
+ * @param id - The message database ID. Use `latest` to return the latest message.
199
+ * @param relayTo - Array of email addresses to relay the message to
200
+ * @returns Plain text "ok" response
201
+ * @example
202
+ * ```typescript
203
+ * const message = await mailpit.releaseMessage("latest", ["user1@example.test", "user2@example.test"]);
204
+ * ```
205
+ */
206
+ async releaseMessage(id, relayTo) {
207
+ return await this.handleRequest(
208
+ () => this.axiosInstance.post(`/api/v1/message/${id}/release`, relayTo)
209
+ );
210
+ }
211
+ /**
212
+ * Sends a message
213
+ * @param sendReqest - The request containing the message details.
214
+ * @returns Response containing database messsage ID
215
+ * @example
216
+ * ```typescript
217
+ * await mailpit.sendMessage(
218
+ * From: { Email: "user@example.test", Name: "First LastName" },
219
+ * To: [{ Email: "rec@example.test", Name: "Recipient Name"}, {Email: "another@example.test"}],
220
+ * Subject: "Test Email",
221
+ * );
222
+ * ```
223
+ */
224
+ async sendMessage(sendReqest) {
225
+ return await this.handleRequest(
226
+ () => this.axiosInstance.post(
227
+ `/api/v1/send`,
228
+ sendReqest
229
+ )
230
+ );
231
+ }
232
+ /**
233
+ * Retrieves a list of message summaries ordered from newest to oldest.
234
+ * @remarks Only contains the number of attachments and a snippet of the message body.
235
+ * @see {@link MailpitClient.getMessageSummary | getMessageSummary()} for more attachment and body details for a specific message.
236
+ * @param start - The pagination offset. Defaults to `0`.
237
+ * @param limit - The number of messages to retrieve. Defaults to `50`.
238
+ * @returns A list of message summaries
239
+ * @example
240
+ * ```typescript
241
+ * const messages = await.listMessages();
242
+ * ```
243
+ */
244
+ async listMessages(start = 0, limit = 50) {
245
+ return await this.handleRequest(
246
+ () => this.axiosInstance.get(
247
+ `/api/v1/messages`,
248
+ { params: { start, limit } }
249
+ )
250
+ );
251
+ }
252
+ /**
253
+ * Set the read status of messages.
254
+ * @remarks You can optionally provide an array of `IDs` **OR** a `Search` filter. If neither is set then all messages are updated.
255
+ * @param readStatus - The request containing the message database IDs/search string and the read status.
256
+ * @param readStatus.Read - The read status to set. Defaults to `false`.
257
+ * @param readStatus.IDs - The optional IDs of the messages to update.
258
+ * @param readStatus.Search - The optional search string to filter messages.
259
+ * @param params - Optional parameters for defining the time zone when using the `before:` and `after:` search filters.
260
+ * @see {@link https://mailpit.axllent.org/docs/usage/search-filters/ | Search filters}
261
+ * @returns Plain text "ok" response
262
+ * @example
263
+ * ```typescript
264
+ * // Set all messages as unread
265
+ * await mailpit.setReadStatus();
266
+ *
267
+ * // Set all messages as read
268
+ * await mailpit.setReadStatus({ Read: true });
269
+ *
270
+ * // Set specific messages as read using IDs
271
+ * await mailpit.setReadStatus({ IDs: ["1", "2", "3"], Read: true });
272
+ *
273
+ * // Set specific messages as read using search
274
+ * await mailpit.setReadStatus({ Search: "from:example.test", Read: true });
275
+ *
276
+ * // Set specific messages as read using after: search with time zone
277
+ * await mailpit.setReadStatus({ Search: "after:2025-04-30", Read: true }, { tz: "America/Chicago" });
278
+ * ```
279
+ */
280
+ async setReadStatus(readStatus, params) {
281
+ return await this.handleRequest(
282
+ () => this.axiosInstance.put(`/api/v1/messages`, readStatus, {
283
+ params
284
+ })
285
+ );
286
+ }
287
+ /**
288
+ * Delete individual or all messages.
289
+ * @remarks If no `IDs` are provided then all messages are deleted.
290
+ * @param deleteRequest - The request containing the message database IDs to delete.
291
+ * @returns Plain text "ok" response
292
+ * @example
293
+ * ```typescript
294
+ * // Delete all messages
295
+ * await mailpit.deleteMessages();
296
+ *
297
+ * // Delete specific messages
298
+ * await mailpit.deleteMessages({ IDs: ["1", "2", "3"] });
299
+ * ```
300
+ */
301
+ async deleteMessages(deleteRequest) {
302
+ return await this.handleRequest(
303
+ () => this.axiosInstance.delete(`/api/v1/messages`, {
304
+ data: deleteRequest
305
+ })
306
+ );
307
+ }
308
+ /**
309
+ * Retrieve messages matching a search, sorted by received date (descending).
310
+ * @see {@link https://mailpit.axllent.org/docs/usage/search-filters/ | Search filters}
311
+ * @remarks Only contains the number of attachments and a snippet of the message body.
312
+ * @see {@link MailpitClient.getMessageSummary | getMessageSummary()} for more attachment and body details for a specific message.
313
+ * @param search - The search request containing the query and optional parameters.
314
+ * @returns A list of message summaries matching the search criteria.
315
+ * @example
316
+ * ```typescript
317
+ * // Search for messages from a the domain example.test
318
+ * const messages = await mailpit.searchMessages({query: "from:example.test"});
319
+ * ```
320
+ */
321
+ async searchMessages(search) {
322
+ return await this.handleRequest(
323
+ () => this.axiosInstance.get(`/api/v1/search`, {
324
+ params: search
325
+ })
326
+ );
327
+ }
328
+ /**
329
+ * Delete all messages matching a search.
330
+ * @see {@link https://mailpit.axllent.org/docs/usage/search-filters/ | Search filters}
331
+ * @param search - The search request containing the query.
332
+ * @returns Plain text "ok" response
333
+ * @example
334
+ * ```typescript
335
+ * // Delete all messages from the domain example.test
336
+ * await mailpit.deleteMessagesBySearch({query: "from:example.test"});
337
+ * ```
338
+ */
339
+ async deleteMessagesBySearch(search) {
340
+ return await this.handleRequest(
341
+ () => this.axiosInstance.delete(`/api/v1/search`, { params: search })
342
+ );
343
+ }
344
+ /**
345
+ * Performs an HTML check on a specific message.
346
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
347
+ * @returns The summary of the message HTML checker
348
+ * @example
349
+ * ```typescript
350
+ * const htmlCheck = await mailpit.htmlCheck();
351
+ * ```
352
+ */
353
+ async htmlCheck(id = "latest") {
354
+ return await this.handleRequest(
355
+ () => this.axiosInstance.get(
356
+ `/api/v1/message/${id}/html-check`
357
+ )
358
+ );
359
+ }
360
+ /**
361
+ * Performs a link check on a specific message.
362
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
363
+ * @param follow - Whether to follow links. Defaults to `false`.
364
+ * @returns The summary of the message Link checker.
365
+ * @example
366
+ * ```typescript
367
+ * const linkCheck = await mailpit.linkCheck();
368
+ * ```
369
+ */
370
+ async linkCheck(id = "latest", follow = "false") {
371
+ return await this.handleRequest(
372
+ () => this.axiosInstance.get(
373
+ `/api/v1/message/${id}/link-check`,
374
+ { params: { follow } }
375
+ )
376
+ );
377
+ }
378
+ /**
379
+ * Performs a SpamAssassin check (if enabled) on a specific message.
380
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
381
+ * @returns The SpamAssassin summary (if enabled)
382
+ * @example
383
+ * ```typescript
384
+ * const spamAssassinCheck = await mailpit.spamAssassinCheck();
385
+ * ```
386
+ */
387
+ async spamAssassinCheck(id = "latest") {
388
+ return await this.handleRequest(
389
+ () => this.axiosInstance.get(
390
+ `/api/v1/message/${id}/sa-check`
391
+ )
392
+ );
393
+ }
394
+ /**
395
+ * Retrieves a list of all the unique tags.
396
+ * @returns All unique message tags
397
+ * @example
398
+ * ```typescript
399
+ * const tags = await mailpit.getTags();
400
+ * ```
401
+ */
402
+ async getTags() {
403
+ return await this.handleRequest(
404
+ () => this.axiosInstance.get(`/api/v1/tags`)
405
+ );
406
+ }
407
+ /**
408
+ * Sets and removes tag(s) on message(s). This will overwrite any existing tags for selected message database IDs.
409
+ * @param request - The request containing the message IDs and tags. To remove all tags from a message, pass an empty `Tags` array or exclude `Tags` entirely.
410
+ * @remarks
411
+ * Tags are limited to the following characters: `a-z`, `A-Z`, `0-9`, `-`, `.`, `spaces`, and `_`, and must be a minimum of 1 character.
412
+ * Other characters are silently stripped from the tag.
413
+ * @returns Plain text "ok" response
414
+ * @example
415
+ * ```typescript
416
+ * // Set tags on message(s)
417
+ * await mailpit.setTags({ IDs: ["1", "2", "3"], Tags: ["tag1", "tag2"] });
418
+ * // Remove tags from message(s)
419
+ * await mailpit.setTags({ IDs: ["1", "2", "3"]});
420
+ * ```
421
+ */
422
+ async setTags(request) {
423
+ return await this.handleRequest(
424
+ () => this.axiosInstance.put(`/api/v1/tags`, request)
425
+ );
426
+ }
427
+ /**
428
+ * Renames an existing tag.
429
+ * @param tag - The current name of the tag.
430
+ * @param newTagName - A new name for the tag.
431
+ * @remarks
432
+ * Tags are limited to the following characters: `a-z`, `A-Z`, `0-9`, `-`, `.`, `spaces`, and `_`, and must be a minimum of 1 character.
433
+ * Other characters are silently stripped from the tag.
434
+ * @returns Plain text "ok" response
435
+ * @example
436
+ * ```typescript
437
+ * await mailpit.renameTag("Old Tag Name", "New Tag Name");
438
+ * ```
439
+ */
440
+ async renameTag(tag, newTagName) {
441
+ const encodedTag = encodeURIComponent(tag);
442
+ return await this.handleRequest(
443
+ () => this.axiosInstance.put(`/api/v1/tags/${encodedTag}`, {
444
+ Name: newTagName
445
+ })
446
+ );
447
+ }
448
+ /**
449
+ * Deletes a tag from all messages.
450
+ * @param tag - The name of the tag to delete.
451
+ * @remarks This does NOT delete any messages
452
+ * @returns Plain text "ok" response
453
+ * ```typescript
454
+ * await mailpit.deleteTag("Tag 1");
455
+ * ```
456
+ */
457
+ async deleteTag(tag) {
458
+ const encodedTag = encodeURIComponent(tag);
459
+ return await this.handleRequest(
460
+ () => this.axiosInstance.delete(`/api/v1/tags/${encodedTag}`)
461
+ );
462
+ }
463
+ /**
464
+ * Retrieves the current Chaos triggers configuration (if enabled).
465
+ * @remarks This will return an error if Chaos is not enabled at runtime.
466
+ * @returns The Chaos triggers configuration
467
+ * @example
468
+ * ```typescript
469
+ * const triggers = await mailpit.getChaosTriggers();
470
+ * ```
471
+ */
472
+ async getChaosTriggers() {
473
+ return await this.handleRequest(
474
+ () => this.axiosInstance.get("/api/v1/chaos")
475
+ );
476
+ }
477
+ /**
478
+ * Sets and/or resets the Chaos triggers configuration (if enabled).
479
+ * @param triggers - The request containing the chaos triggers. Omitted triggers will reset to the default `0%` probabibility.
480
+ * @remarks This will return an error if Chaos is not enabled at runtime.
481
+ * @returns The updated Chaos triggers configuration
482
+ * @example
483
+ * ```typescript
484
+ * // Reset all triggers to `0%` probability
485
+ * const triggers = await mailpit.setChaosTriggers();
486
+ * // Set `Sender` and reset `Authentication` and `Recipient` triggers
487
+ * const triggers = await mailpit.setChaosTriggers({ Sender: { ErrorCode: 451, Probability: 5 } });
488
+ * ```
489
+ */
490
+ async setChaosTriggers(triggers = {}) {
491
+ return await this.handleRequest(
492
+ () => this.axiosInstance.put(
493
+ "/api/v1/chaos",
494
+ triggers
495
+ )
496
+ );
497
+ }
498
+ /**
499
+ * Renders the HTML part of a specific message which can be used for UI integration testing.
500
+ * @remarks
501
+ * Attached inline images are modified to link to the API provided they exist.
502
+ * If the message does not contain an HTML part then a 404 error is returned.
503
+ *
504
+ *
505
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
506
+ * @param embed - Whether this route is to be embedded in an iframe. Defaults to `undefined`. Set to `1` to embed.
507
+ * The `embed` parameter will add `target="_blank"` and `rel="noreferrer noopener"` to all links.
508
+ * In addition, a small script will be added to the end of the document to post (postMessage()) the height of the document back to the parent window for optional iframe height resizing.
509
+ * Note that this will also transform the message into a full HTML document (if it isn't already), so this option is useful for viewing but not programmatic testing.
510
+ * @returns Rendered HTML
511
+ * @example
512
+ * ```typescript
513
+ * const html = await mailpit.renderMessageHTML();
514
+ * ```
515
+ */
516
+ async renderMessageHTML(id = "latest", embed) {
517
+ return await this.handleRequest(
518
+ () => this.axiosInstance.get(`/view/${id}.html`, { params: { embed } })
519
+ );
520
+ }
521
+ /**
522
+ * Renders just the message's text part which can be used for UI integration testing.
523
+ * @param id - The message database ID. Defaults to `latest` to return the latest message.
524
+ * @returns Plain text
525
+ * @example
526
+ * ```typescript
527
+ * const html = await mailpit.renderMessageText();
528
+ * ```
529
+ */
530
+ async renderMessageText(id = "latest") {
531
+ return await this.handleRequest(
532
+ () => this.axiosInstance.get(`/view/${id}.txt`)
533
+ );
534
+ }
535
+ };
536
+ export {
537
+ MailpitClient
538
+ };
package/package.json CHANGED
@@ -1,22 +1,22 @@
1
1
  {
2
2
  "name": "mailpit-api",
3
- "version": "1.3.0",
3
+ "version": "1.4.0-alpha",
4
4
  "description": "A NodeJS client library, written in TypeScript, to interact with the Mailpit API.",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/mpspahr/mailpit-api.git"
8
8
  },
9
- "main": "dist/cjs/index.js",
10
- "module": "dist/mjs/index.js",
9
+ "main": "dist/index.cjs",
10
+ "module": "dist/index.mjs",
11
11
  "exports": {
12
12
  ".": {
13
- "import": "./dist/mjs/index.js",
14
- "require": "./dist/cjs/index.js"
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.cjs"
15
15
  }
16
16
  },
17
17
  "scripts": {
18
18
  "test": "echo \"TODO: Add tests\" && exit 0",
19
- "build": "rm -fr dist/* && tsc -p tsconfig.json && tsc -p tsconfig-cjs.json && ./fixup_type",
19
+ "build": "tsup src/index.ts --dts --format esm,cjs --outDir dist",
20
20
  "pretty": "npx prettier . --write",
21
21
  "lint": "npx eslint --fix src",
22
22
  "docs": "typedoc --readme none"
@@ -35,20 +35,20 @@
35
35
  "author": "Matthew Spahr",
36
36
  "license": "MIT",
37
37
  "dependencies": {
38
- "axios": "^1.8.4"
38
+ "axios": "^1.9.0"
39
39
  },
40
40
  "devDependencies": {
41
- "@eslint/js": "^9.25.1",
42
- "@types/eslint__js": "^8.31.1",
43
- "@types/node": "^22.15.3",
44
- "eslint": "^9.25.1",
41
+ "@eslint/js": "^9.27.0",
42
+ "@types/node": "^22.15.18",
43
+ "eslint": "^9.27.0",
45
44
  "jest": "^29.7.0",
46
45
  "prettier": "3.5.3",
46
+ "tsup": "^8.5.0",
47
47
  "tsx": "^4.19.4",
48
- "typedoc": "^0.28.3",
48
+ "typedoc": "^0.28.4",
49
49
  "typedoc-github-wiki-theme": "^2.1.0",
50
50
  "typedoc-plugin-markdown": "^4.6.3",
51
51
  "typescript": "^5.8.3",
52
- "typescript-eslint": "^8.31.1"
52
+ "typescript-eslint": "^8.32.1"
53
53
  }
54
54
  }