mailpit-api 1.1.0 → 1.2.0

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