mailisk 1.0.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.
package/.prettierrc ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "printWidth": 120
3
+ }
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ ## MIT License
2
+
3
+ Copyright (c) 2022 Mailisk https://mailisk.com
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 ADDED
@@ -0,0 +1,102 @@
1
+ # Mailisk Node Client
2
+
3
+ Mailisk is an end-to-end email testing platform. It allows you to receive emails with code and automate email tests.
4
+
5
+ - Get a unique subdomain and unlimited email addresses for free.
6
+ - Easily automate E2E password reset and account verification by catching emails.
7
+ - Virtual SMTP support to test outbound email without 3rd party clients.
8
+
9
+ ## Get started
10
+
11
+ For a more step-by-step walkthrough see the [NodeJS Guide](https://docs.mailisk.com/guides/nodejs.html).
12
+
13
+ ### Installation
14
+
15
+ #### Install with npm
16
+
17
+ ```shell
18
+ npm install --save-dev mailisk
19
+ ```
20
+
21
+ #### Install with Yarn
22
+
23
+ ```shell
24
+ yarn add mailisk --dev
25
+ ```
26
+
27
+ ### Usage
28
+
29
+ After installing the library import it and set the [API Key](https://docs.mailisk.com/#getting-your-api-key)
30
+
31
+ ```js
32
+ const { MailiskClient } = require("mailisk");
33
+
34
+ // create client
35
+ const mailisk = new MailiskClient({ apiKey: "YOUR_API_KEY" });
36
+
37
+ // send email (using virtual SMTP)
38
+ await client.sendVirtualEmail(namespace, {
39
+ from: "test@example.com",
40
+ to: `john@${namespace}.mailisk.net`,
41
+ subject: "Testing",
42
+ text: "This is a test.",
43
+ });
44
+
45
+ // receive email
46
+ const result = await client.searchInbox(namespace);
47
+
48
+ console.log(result);
49
+ ```
50
+
51
+ ### API Reference
52
+
53
+ This library wraps the REST API endpoints. Find out more in the [API Reference](https://docs.mailisk.com/api-reference/).
54
+
55
+ ## Client functions
56
+
57
+ ### searchInbox(namespace, params?)
58
+
59
+ The `searchInbox` function takes a namespace and call parameters.
60
+
61
+ - It uses the `wait` property by default. This means the call won't timeout until a result is returned or 5 minutes pass. This is adjustable by passing the `timeout` paramter (it can also be disabled by passing `wait: false`).
62
+ - It uses a default `from_timestamp` of **current timestamp - 5 seconds**. This means that older emails will be ignored. This can be overriden by passing the `from_timestamp` parameter (`from_timestmap: 0` will disable filtering by email age).
63
+
64
+ #### Filter by destination address
65
+
66
+ A common use case is filtering the returned emails by the destination address, this is done using the `to_addr_prefix` parameter.
67
+
68
+ ```js
69
+ const { data: emails } = await mailisk.searchInbox(namespace, {
70
+ to_addr_prefix: "john@mynamespace.mailisk.net",
71
+ });
72
+ ```
73
+
74
+ For more parameter options see the [endpoint reference](https://docs.mailisk.com/api-reference/search-inbox.html#request-1).
75
+
76
+ ### sendVirtualEmail(namespace, params)
77
+
78
+ Send an email using [Virtual SMTP](https://docs.mailisk.com/smtp.html). This will fetch the SMTP settings for the selected namespace and send an email. These emails can only be sent to an address that ends in `@{namespace}.mailisk.net`.
79
+
80
+ ```js
81
+ const namespace = "mynamespace";
82
+
83
+ await mailisk.sendVirtualEmail(namespace, {
84
+ from: "test@example.com",
85
+ to: `john@${namespace}.mailisk.net`,
86
+ subject: "This is a test",
87
+ text: "Testing",
88
+ });
89
+ ```
90
+
91
+ This does not call an API endpoint but rather uses nodemailer to send an email using SMTP.
92
+
93
+ ### listNamespaces()
94
+
95
+ List all namespaces associated with the current API Key.
96
+
97
+ ```js
98
+ const namespacesResponse = await mailisk.listNamespaces();
99
+
100
+ // will be ['namespace1', 'namespace2']
101
+ const namespaces = namespacesResponse.map((nr) => nr.namespace);
102
+ ```
@@ -0,0 +1,168 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+
3
+ interface EmailAddress {
4
+ /** Email address */
5
+ address: string;
6
+ /** Display name, if one is specified */
7
+ name?: string;
8
+ }
9
+ interface Email {
10
+ /** Namespace scoped ID */
11
+ id: string;
12
+ /** Sender of email */
13
+ from: EmailAddress;
14
+ /** Recepients of email */
15
+ to: EmailAddress[];
16
+ /** Carbon-copied recipients for email message */
17
+ cc?: EmailAddress[];
18
+ /** Blind carbon-copied recipients for email message */
19
+ bcc?: EmailAddress[];
20
+ /** Subject of email */
21
+ subject?: string;
22
+ /** Email content that was sent in HTML format */
23
+ html?: string;
24
+ /** Email content that was sent in plain text format */
25
+ text?: string;
26
+ /** The datetime that this email was received */
27
+ received_date: Date;
28
+ /** The unix timestamp (s) that this email was received */
29
+ received_timestamp: number;
30
+ /** The unix timestamp (s) when this email will be deleted */
31
+ expires_timestamp: number;
32
+ /** The spam score as reported by SpamAssassin */
33
+ spam_score?: number;
34
+ }
35
+ interface SearchInboxParams {
36
+ /**
37
+ * The maximum number of emails that can be returned in this request, used alongside `offset` for pagination.
38
+ */
39
+ limit?: number;
40
+ /**
41
+ * The number of emails to skip/ignore, used alongside `limit` for pagination.
42
+ */
43
+ offset?: number;
44
+ /**
45
+ * Filter emails by starting unix timestamp in seconds.
46
+ */
47
+ from_timestamp?: number;
48
+ /**
49
+ * Filter emails by ending unix timestamp in seconds.
50
+ */
51
+ to_timestamp?: number;
52
+ /**
53
+ * Filter emails by 'to' address. Address must start with this.
54
+ *
55
+ * 'foo' would return 'foobar@namespace.mailisk.net' but not 'barfoo@namespace.mailisk.net'
56
+ */
57
+ to_addr_prefix?: string;
58
+ /**
59
+ * Will keep the request going till at least one email would be returned.
60
+ *
61
+ * Default is `true`
62
+ */
63
+ wait?: boolean;
64
+ }
65
+ interface SearchInboxResponse {
66
+ /**
67
+ * Total number of emails matching query.
68
+ */
69
+ total_count: number;
70
+ /**
71
+ * Parameters that were used for the query
72
+ */
73
+ options: SearchInboxParams;
74
+ /**
75
+ * Emails
76
+ */
77
+ data: Email[];
78
+ }
79
+ interface SmtpSettings {
80
+ data: {
81
+ host: string;
82
+ port: number;
83
+ username: string;
84
+ password: string;
85
+ };
86
+ }
87
+ interface ListNamespacesResponse {
88
+ data: [
89
+ {
90
+ id: string;
91
+ namespace: string;
92
+ }
93
+ ];
94
+ }
95
+ interface SendVirtualEmailParams {
96
+ /** Sender of email */
97
+ from: string;
98
+ /**
99
+ * Recepients of email
100
+ *
101
+ * Must match namespace. E.g. if using namespace 'mynamespace' `to` must be 'something@mynamespace.mailisk.net'.
102
+ */
103
+ to: string;
104
+ /** The subject of the e-mail */
105
+ subject: string;
106
+ /** The plaintext version of the message */
107
+ text?: string | undefined;
108
+ /** The HTML version of the message */
109
+ html?: string | undefined;
110
+ }
111
+
112
+ declare class MailiskClient {
113
+ constructor({ apiKey, baseUrl }: {
114
+ apiKey: string;
115
+ baseUrl?: string;
116
+ });
117
+ private readonly axiosInstance;
118
+ /**
119
+ * List all namespaces that belong to the current account (API key).
120
+ */
121
+ listNamespaces(): Promise<ListNamespacesResponse>;
122
+ /**
123
+ * Send an email using the Virtual SMTP.
124
+ *
125
+ * These emails can only be sent to valid Mailisk namespaces, i.e. emails that end in @mynamespace.mailisk.net
126
+ *
127
+ * @example
128
+ * For example, sending a test email:
129
+ * ```typescript
130
+ * client.sendVirtualEmail(namespace, {
131
+ * from: "test@example.com",
132
+ * to: `john@${namespace}.mailisk.net`,
133
+ * subject: "This is a test",
134
+ * text: "Testing",
135
+ * });
136
+ * ```
137
+ */
138
+ sendVirtualEmail(namespace: string, params: SendVirtualEmailParams): Promise<void>;
139
+ /**
140
+ * Search inbox of a namespace.
141
+ *
142
+ * By default, this calls the api using the `wait` flag. This means the call won't timeout until at least one email is received or 5 minutes pass.
143
+ * It also uses a default `from_timestamp` of **current timestamp - 5 seconds**. This means that older emails will be ignored.
144
+ *
145
+ * Both of these settings can be overriden by passing them in the `params` object.
146
+ *
147
+ * @example
148
+ * Get the latest emails in the namespace
149
+ * ```typescript
150
+ * const { data: emails } = await client.searchInbox(namespace);
151
+ * ```
152
+ *
153
+ * @example
154
+ * Get the latest emails for a specific email address
155
+ * ```typescript
156
+ * const { data: emails } = await client.searchInbox(namespace, {
157
+ * to_addr_prefix: 'john@mynamespace.mailisk.net'
158
+ * });
159
+ * ```
160
+ */
161
+ searchInbox(namespace: string, params?: SearchInboxParams, config?: AxiosRequestConfig): Promise<SearchInboxResponse>;
162
+ /**
163
+ * Get the SMTP settings for a namespace.
164
+ */
165
+ getSmtpSettings(namespace: string): Promise<SmtpSettings>;
166
+ }
167
+
168
+ export { MailiskClient };
package/dist/index.js ADDED
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+
27
+ // src/index.ts
28
+ var src_exports = {};
29
+ __export(src_exports, {
30
+ MailiskClient: () => MailiskClient
31
+ });
32
+ module.exports = __toCommonJS(src_exports);
33
+
34
+ // src/mailisk.ts
35
+ var import_axios = __toESM(require("axios"));
36
+ var import_nodemailer = __toESM(require("nodemailer"));
37
+ var MailiskClient = class {
38
+ constructor({ apiKey, baseUrl }) {
39
+ this.axiosInstance = import_axios.default.create({
40
+ headers: {
41
+ "X-Api-Key": apiKey
42
+ },
43
+ baseURL: baseUrl || "https://api.mailisk.com/"
44
+ });
45
+ }
46
+ axiosInstance;
47
+ async listNamespaces() {
48
+ return (await this.axiosInstance.get("api/namespaces")).data;
49
+ }
50
+ async sendVirtualEmail(namespace, params) {
51
+ const smtpSettings = await this.getSmtpSettings(namespace);
52
+ const transport = import_nodemailer.default.createTransport({
53
+ host: smtpSettings.data.host,
54
+ port: smtpSettings.data.port,
55
+ secure: false,
56
+ auth: {
57
+ user: smtpSettings.data.username,
58
+ pass: smtpSettings.data.password
59
+ }
60
+ });
61
+ const { from, to, subject, text, html } = params;
62
+ await transport.sendMail({
63
+ from,
64
+ to,
65
+ subject,
66
+ text,
67
+ html
68
+ });
69
+ transport.close();
70
+ }
71
+ async searchInbox(namespace, params, config) {
72
+ let _params = { ...params };
73
+ if (!params?.from_timestamp) {
74
+ _params.from_timestamp = Math.floor(new Date().getTime() / 1e3) - 5;
75
+ }
76
+ if (params?.wait !== false) {
77
+ _params.wait = true;
78
+ }
79
+ let _config = { ...config };
80
+ if (_params.wait && !config?.timeout) {
81
+ _config.timeout = 1e3 * 60 * 5;
82
+ }
83
+ return (await this.axiosInstance.get(`api/emails/${namespace}/inbox`, {
84
+ ...config,
85
+ params: _params
86
+ })).data;
87
+ }
88
+ async getSmtpSettings(namespace) {
89
+ const result = await this.axiosInstance.get(`api/smtp/${namespace}`);
90
+ return result.data;
91
+ }
92
+ };
93
+ __name(MailiskClient, "MailiskClient");
94
+ // Annotate the CommonJS export names for ESM import in node:
95
+ 0 && (module.exports = {
96
+ MailiskClient
97
+ });
98
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/mailisk.ts"],"sourcesContent":["export * from \"./mailisk\";\n","import axios, { AxiosRequestConfig } from \"axios\";\nimport {\n ListNamespacesResponse,\n SearchInboxParams,\n SearchInboxResponse,\n SendVirtualEmailParams,\n SmtpSettings,\n} from \"./mailisk.interfaces\";\nimport nodemailer from \"nodemailer\";\n\nexport class MailiskClient {\n constructor({ apiKey, baseUrl }: { apiKey: string; baseUrl?: string }) {\n this.axiosInstance = axios.create({\n headers: {\n \"X-Api-Key\": apiKey,\n },\n baseURL: baseUrl || \"https://api.mailisk.com/\",\n });\n }\n\n private readonly axiosInstance;\n\n /**\n * List all namespaces that belong to the current account (API key).\n */\n async listNamespaces(): Promise<ListNamespacesResponse> {\n return (await this.axiosInstance.get(\"api/namespaces\")).data;\n }\n\n /**\n * Send an email using the Virtual SMTP.\n *\n * These emails can only be sent to valid Mailisk namespaces, i.e. emails that end in @mynamespace.mailisk.net\n *\n * @example\n * For example, sending a test email:\n * ```typescript\n * client.sendVirtualEmail(namespace, {\n * from: \"test@example.com\",\n * to: `john@${namespace}.mailisk.net`,\n * subject: \"This is a test\",\n * text: \"Testing\",\n * });\n * ```\n */\n async sendVirtualEmail(namespace: string, params: SendVirtualEmailParams): Promise<void> {\n const smtpSettings = await this.getSmtpSettings(namespace);\n\n // TODO: to should match namespace\n\n const transport = nodemailer.createTransport({\n host: smtpSettings.data.host,\n port: smtpSettings.data.port,\n secure: false,\n auth: {\n user: smtpSettings.data.username,\n pass: smtpSettings.data.password,\n },\n });\n\n const { from, to, subject, text, html } = params;\n\n await transport.sendMail({\n from,\n to,\n subject,\n text,\n html,\n });\n\n transport.close();\n }\n\n /**\n * Search inbox of a namespace.\n *\n * By default, this calls the api using the `wait` flag. This means the call won't timeout until at least one email is received or 5 minutes pass.\n * It also uses a default `from_timestamp` of **current timestamp - 5 seconds**. This means that older emails will be ignored.\n *\n * Both of these settings can be overriden by passing them in the `params` object.\n *\n * @example\n * Get the latest emails in the namespace\n * ```typescript\n * const { data: emails } = await client.searchInbox(namespace);\n * ```\n *\n * @example\n * Get the latest emails for a specific email address\n * ```typescript\n * const { data: emails } = await client.searchInbox(namespace, {\n * to_addr_prefix: 'john@mynamespace.mailisk.net'\n * });\n * ```\n */\n async searchInbox(\n namespace: string,\n params?: SearchInboxParams,\n config?: AxiosRequestConfig\n ): Promise<SearchInboxResponse> {\n let _params = { ...params };\n\n // default from timestamp, 5 seconds before starting this request\n if (!params?.from_timestamp) {\n _params.from_timestamp = Math.floor(new Date().getTime() / 1000) - 5;\n }\n\n // by default wait for email\n if (params?.wait !== false) {\n _params.wait = true;\n }\n\n let _config = { ...config };\n\n // by default, wait 5 minutes for emails before timing out\n if (_params.wait && !config?.timeout) {\n _config.timeout = 1000 * 60 * 5;\n }\n\n return (\n await this.axiosInstance.get(`api/emails/${namespace}/inbox`, {\n ...config,\n params: _params,\n })\n ).data;\n }\n\n /**\n * Get the SMTP settings for a namespace.\n */\n async getSmtpSettings(namespace: string): Promise<SmtpSettings> {\n const result = await this.axiosInstance.get(`api/smtp/${namespace}`);\n return result.data;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;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AChC;AAEA,YACE,MAAM,KAAK,cAAc,IAAI,cAAc,mBAAmB;AAAA,MAC5D,GAAG;AAAA,MACH,QAAQ;AAAA,IACV,CAAC,GACD;AAAA,EACJ;AAAA,EAKA,MAAM,gBAAgB,WAA0C;AAC9D,UAAM,SAAS,MAAM,KAAK,cAAc,IAAI,YAAY,WAAW;AACnE,WAAO,OAAO;AAAA,EAChB;AACF;AA5Ha;","names":["axios","nodemailer"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,67 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/mailisk.ts
5
+ import axios from "axios";
6
+ import nodemailer from "nodemailer";
7
+ var MailiskClient = class {
8
+ constructor({ apiKey, baseUrl }) {
9
+ this.axiosInstance = axios.create({
10
+ headers: {
11
+ "X-Api-Key": apiKey
12
+ },
13
+ baseURL: baseUrl || "https://api.mailisk.com/"
14
+ });
15
+ }
16
+ axiosInstance;
17
+ async listNamespaces() {
18
+ return (await this.axiosInstance.get("api/namespaces")).data;
19
+ }
20
+ async sendVirtualEmail(namespace, params) {
21
+ const smtpSettings = await this.getSmtpSettings(namespace);
22
+ const transport = nodemailer.createTransport({
23
+ host: smtpSettings.data.host,
24
+ port: smtpSettings.data.port,
25
+ secure: false,
26
+ auth: {
27
+ user: smtpSettings.data.username,
28
+ pass: smtpSettings.data.password
29
+ }
30
+ });
31
+ const { from, to, subject, text, html } = params;
32
+ await transport.sendMail({
33
+ from,
34
+ to,
35
+ subject,
36
+ text,
37
+ html
38
+ });
39
+ transport.close();
40
+ }
41
+ async searchInbox(namespace, params, config) {
42
+ let _params = { ...params };
43
+ if (!params?.from_timestamp) {
44
+ _params.from_timestamp = Math.floor(new Date().getTime() / 1e3) - 5;
45
+ }
46
+ if (params?.wait !== false) {
47
+ _params.wait = true;
48
+ }
49
+ let _config = { ...config };
50
+ if (_params.wait && !config?.timeout) {
51
+ _config.timeout = 1e3 * 60 * 5;
52
+ }
53
+ return (await this.axiosInstance.get(`api/emails/${namespace}/inbox`, {
54
+ ...config,
55
+ params: _params
56
+ })).data;
57
+ }
58
+ async getSmtpSettings(namespace) {
59
+ const result = await this.axiosInstance.get(`api/smtp/${namespace}`);
60
+ return result.data;
61
+ }
62
+ };
63
+ __name(MailiskClient, "MailiskClient");
64
+ export {
65
+ MailiskClient
66
+ };
67
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mailisk.ts"],"sourcesContent":["import axios, { AxiosRequestConfig } from \"axios\";\nimport {\n ListNamespacesResponse,\n SearchInboxParams,\n SearchInboxResponse,\n SendVirtualEmailParams,\n SmtpSettings,\n} from \"./mailisk.interfaces\";\nimport nodemailer from \"nodemailer\";\n\nexport class MailiskClient {\n constructor({ apiKey, baseUrl }: { apiKey: string; baseUrl?: string }) {\n this.axiosInstance = axios.create({\n headers: {\n \"X-Api-Key\": apiKey,\n },\n baseURL: baseUrl || \"https://api.mailisk.com/\",\n });\n }\n\n private readonly axiosInstance;\n\n /**\n * List all namespaces that belong to the current account (API key).\n */\n async listNamespaces(): Promise<ListNamespacesResponse> {\n return (await this.axiosInstance.get(\"api/namespaces\")).data;\n }\n\n /**\n * Send an email using the Virtual SMTP.\n *\n * These emails can only be sent to valid Mailisk namespaces, i.e. emails that end in @mynamespace.mailisk.net\n *\n * @example\n * For example, sending a test email:\n * ```typescript\n * client.sendVirtualEmail(namespace, {\n * from: \"test@example.com\",\n * to: `john@${namespace}.mailisk.net`,\n * subject: \"This is a test\",\n * text: \"Testing\",\n * });\n * ```\n */\n async sendVirtualEmail(namespace: string, params: SendVirtualEmailParams): Promise<void> {\n const smtpSettings = await this.getSmtpSettings(namespace);\n\n // TODO: to should match namespace\n\n const transport = nodemailer.createTransport({\n host: smtpSettings.data.host,\n port: smtpSettings.data.port,\n secure: false,\n auth: {\n user: smtpSettings.data.username,\n pass: smtpSettings.data.password,\n },\n });\n\n const { from, to, subject, text, html } = params;\n\n await transport.sendMail({\n from,\n to,\n subject,\n text,\n html,\n });\n\n transport.close();\n }\n\n /**\n * Search inbox of a namespace.\n *\n * By default, this calls the api using the `wait` flag. This means the call won't timeout until at least one email is received or 5 minutes pass.\n * It also uses a default `from_timestamp` of **current timestamp - 5 seconds**. This means that older emails will be ignored.\n *\n * Both of these settings can be overriden by passing them in the `params` object.\n *\n * @example\n * Get the latest emails in the namespace\n * ```typescript\n * const { data: emails } = await client.searchInbox(namespace);\n * ```\n *\n * @example\n * Get the latest emails for a specific email address\n * ```typescript\n * const { data: emails } = await client.searchInbox(namespace, {\n * to_addr_prefix: 'john@mynamespace.mailisk.net'\n * });\n * ```\n */\n async searchInbox(\n namespace: string,\n params?: SearchInboxParams,\n config?: AxiosRequestConfig\n ): Promise<SearchInboxResponse> {\n let _params = { ...params };\n\n // default from timestamp, 5 seconds before starting this request\n if (!params?.from_timestamp) {\n _params.from_timestamp = Math.floor(new Date().getTime() / 1000) - 5;\n }\n\n // by default wait for email\n if (params?.wait !== false) {\n _params.wait = true;\n }\n\n let _config = { ...config };\n\n // by default, wait 5 minutes for emails before timing out\n if (_params.wait && !config?.timeout) {\n _config.timeout = 1000 * 60 * 5;\n }\n\n return (\n await this.axiosInstance.get(`api/emails/${namespace}/inbox`, {\n ...config,\n params: _params,\n })\n ).data;\n }\n\n /**\n * Get the SMTP settings for a namespace.\n */\n async getSmtpSettings(namespace: string): Promise<SmtpSettings> {\n const result = await this.axiosInstance.get(`api/smtp/${namespace}`);\n return result.data;\n }\n}\n"],"mappings":";;;;AAAA,OAAO,WAAmC;AAQ1C,OAAO,gBAAgB;AAEhB,IAAM,gBAAN,MAAoB;AAAA,EACzB,YAAY,EAAE,QAAQ,QAAQ,GAAyC;AACrE,SAAK,gBAAgB,MAAM,OAAO;AAAA,MAChC,SAAS;AAAA,QACP,aAAa;AAAA,MACf;AAAA,MACA,SAAS,WAAW;AAAA,IACtB,CAAC;AAAA,EACH;AAAA,EAEiB;AAAA,EAKjB,MAAM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 -0,0 +1,27 @@
1
+ {
2
+ "name": "mailisk",
3
+ "version": "1.0.0",
4
+ "description": "Mailisk library for NodeJS",
5
+ "keywords": [
6
+ "mailisk",
7
+ "email-automation",
8
+ "email-testing",
9
+ "email"
10
+ ],
11
+ "main": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "scripts": {
14
+ "build": "tsup"
15
+ },
16
+ "author": "",
17
+ "license": "ISC",
18
+ "devDependencies": {
19
+ "@types/nodemailer": "^6.4.6",
20
+ "tsup": "^6.2.3",
21
+ "typescript": "^4.8.4"
22
+ },
23
+ "dependencies": {
24
+ "axios": "^1.1.2",
25
+ "nodemailer": "^6.8.0"
26
+ }
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./mailisk";
@@ -0,0 +1,114 @@
1
+ export interface EmailAddress {
2
+ /** Email address */
3
+ address: string;
4
+ /** Display name, if one is specified */
5
+ name?: string;
6
+ }
7
+
8
+ export interface Email {
9
+ /** Namespace scoped ID */
10
+ id: string;
11
+ /** Sender of email */
12
+ from: EmailAddress;
13
+ /** Recepients of email */
14
+ to: EmailAddress[];
15
+ /** Carbon-copied recipients for email message */
16
+ cc?: EmailAddress[];
17
+ /** Blind carbon-copied recipients for email message */
18
+ bcc?: EmailAddress[];
19
+ /** Subject of email */
20
+ subject?: string;
21
+ /** Email content that was sent in HTML format */
22
+ html?: string;
23
+ /** Email content that was sent in plain text format */
24
+ text?: string;
25
+ /** The datetime that this email was received */
26
+ received_date: Date;
27
+ /** The unix timestamp (s) that this email was received */
28
+ received_timestamp: number;
29
+ /** The unix timestamp (s) when this email will be deleted */
30
+ expires_timestamp: number;
31
+ /** The spam score as reported by SpamAssassin */
32
+ spam_score?: number;
33
+ }
34
+
35
+ export interface SearchInboxParams {
36
+ /**
37
+ * The maximum number of emails that can be returned in this request, used alongside `offset` for pagination.
38
+ */
39
+ limit?: number;
40
+ /**
41
+ * The number of emails to skip/ignore, used alongside `limit` for pagination.
42
+ */
43
+ offset?: number;
44
+ /**
45
+ * Filter emails by starting unix timestamp in seconds.
46
+ */
47
+ from_timestamp?: number;
48
+ /**
49
+ * Filter emails by ending unix timestamp in seconds.
50
+ */
51
+ to_timestamp?: number;
52
+ /**
53
+ * Filter emails by 'to' address. Address must start with this.
54
+ *
55
+ * 'foo' would return 'foobar@namespace.mailisk.net' but not 'barfoo@namespace.mailisk.net'
56
+ */
57
+ to_addr_prefix?: string;
58
+ /**
59
+ * Will keep the request going till at least one email would be returned.
60
+ *
61
+ * Default is `true`
62
+ */
63
+ wait?: boolean;
64
+ }
65
+
66
+ export interface SearchInboxResponse {
67
+ /**
68
+ * Total number of emails matching query.
69
+ */
70
+ total_count: number;
71
+ /**
72
+ * Parameters that were used for the query
73
+ */
74
+ options: SearchInboxParams;
75
+ /**
76
+ * Emails
77
+ */
78
+ data: Email[];
79
+ }
80
+
81
+ export interface SmtpSettings {
82
+ data: {
83
+ host: string;
84
+ port: number;
85
+ username: string;
86
+ password: string;
87
+ };
88
+ }
89
+
90
+ export interface ListNamespacesResponse {
91
+ data: [
92
+ {
93
+ id: string;
94
+ namespace: string;
95
+ }
96
+ ];
97
+ }
98
+
99
+ export interface SendVirtualEmailParams {
100
+ /** Sender of email */
101
+ from: string;
102
+ /**
103
+ * Recepients of email
104
+ *
105
+ * Must match namespace. E.g. if using namespace 'mynamespace' `to` must be 'something@mynamespace.mailisk.net'.
106
+ */
107
+ to: string;
108
+ /** The subject of the e-mail */
109
+ subject: string;
110
+ /** The plaintext version of the message */
111
+ text?: string | undefined;
112
+ /** The HTML version of the message */
113
+ html?: string | undefined;
114
+ }
package/src/mailisk.ts ADDED
@@ -0,0 +1,135 @@
1
+ import axios, { AxiosRequestConfig } from "axios";
2
+ import {
3
+ ListNamespacesResponse,
4
+ SearchInboxParams,
5
+ SearchInboxResponse,
6
+ SendVirtualEmailParams,
7
+ SmtpSettings,
8
+ } from "./mailisk.interfaces";
9
+ import nodemailer from "nodemailer";
10
+
11
+ export class MailiskClient {
12
+ constructor({ apiKey, baseUrl }: { apiKey: string; baseUrl?: string }) {
13
+ this.axiosInstance = axios.create({
14
+ headers: {
15
+ "X-Api-Key": apiKey,
16
+ },
17
+ baseURL: baseUrl || "https://api.mailisk.com/",
18
+ });
19
+ }
20
+
21
+ private readonly axiosInstance;
22
+
23
+ /**
24
+ * List all namespaces that belong to the current account (API key).
25
+ */
26
+ async listNamespaces(): Promise<ListNamespacesResponse> {
27
+ return (await this.axiosInstance.get("api/namespaces")).data;
28
+ }
29
+
30
+ /**
31
+ * Send an email using the Virtual SMTP.
32
+ *
33
+ * These emails can only be sent to valid Mailisk namespaces, i.e. emails that end in @mynamespace.mailisk.net
34
+ *
35
+ * @example
36
+ * For example, sending a test email:
37
+ * ```typescript
38
+ * client.sendVirtualEmail(namespace, {
39
+ * from: "test@example.com",
40
+ * to: `john@${namespace}.mailisk.net`,
41
+ * subject: "This is a test",
42
+ * text: "Testing",
43
+ * });
44
+ * ```
45
+ */
46
+ async sendVirtualEmail(namespace: string, params: SendVirtualEmailParams): Promise<void> {
47
+ const smtpSettings = await this.getSmtpSettings(namespace);
48
+
49
+ // TODO: to should match namespace
50
+
51
+ const transport = nodemailer.createTransport({
52
+ host: smtpSettings.data.host,
53
+ port: smtpSettings.data.port,
54
+ secure: false,
55
+ auth: {
56
+ user: smtpSettings.data.username,
57
+ pass: smtpSettings.data.password,
58
+ },
59
+ });
60
+
61
+ const { from, to, subject, text, html } = params;
62
+
63
+ await transport.sendMail({
64
+ from,
65
+ to,
66
+ subject,
67
+ text,
68
+ html,
69
+ });
70
+
71
+ transport.close();
72
+ }
73
+
74
+ /**
75
+ * Search inbox of a namespace.
76
+ *
77
+ * By default, this calls the api using the `wait` flag. This means the call won't timeout until at least one email is received or 5 minutes pass.
78
+ * It also uses a default `from_timestamp` of **current timestamp - 5 seconds**. This means that older emails will be ignored.
79
+ *
80
+ * Both of these settings can be overriden by passing them in the `params` object.
81
+ *
82
+ * @example
83
+ * Get the latest emails in the namespace
84
+ * ```typescript
85
+ * const { data: emails } = await client.searchInbox(namespace);
86
+ * ```
87
+ *
88
+ * @example
89
+ * Get the latest emails for a specific email address
90
+ * ```typescript
91
+ * const { data: emails } = await client.searchInbox(namespace, {
92
+ * to_addr_prefix: 'john@mynamespace.mailisk.net'
93
+ * });
94
+ * ```
95
+ */
96
+ async searchInbox(
97
+ namespace: string,
98
+ params?: SearchInboxParams,
99
+ config?: AxiosRequestConfig
100
+ ): Promise<SearchInboxResponse> {
101
+ let _params = { ...params };
102
+
103
+ // default from timestamp, 5 seconds before starting this request
104
+ if (!params?.from_timestamp) {
105
+ _params.from_timestamp = Math.floor(new Date().getTime() / 1000) - 5;
106
+ }
107
+
108
+ // by default wait for email
109
+ if (params?.wait !== false) {
110
+ _params.wait = true;
111
+ }
112
+
113
+ let _config = { ...config };
114
+
115
+ // by default, wait 5 minutes for emails before timing out
116
+ if (_params.wait && !config?.timeout) {
117
+ _config.timeout = 1000 * 60 * 5;
118
+ }
119
+
120
+ return (
121
+ await this.axiosInstance.get(`api/emails/${namespace}/inbox`, {
122
+ ...config,
123
+ params: _params,
124
+ })
125
+ ).data;
126
+ }
127
+
128
+ /**
129
+ * Get the SMTP settings for a namespace.
130
+ */
131
+ async getSmtpSettings(namespace: string): Promise<SmtpSettings> {
132
+ const result = await this.axiosInstance.get(`api/smtp/${namespace}`);
133
+ return result.data;
134
+ }
135
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2022" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
4
+ "module": "commonjs" /* Specify what module code is generated. */,
5
+ "outDir": "./dist" /* Specify an output folder for all emitted files. */,
6
+ "inlineSourceMap": true /* Include sourcemap files inside the emitted JavaScript. */,
7
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
8
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
9
+ "strict": true /* Enable all strict type-checking options. */,
10
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
11
+ },
12
+ "include": ["src/**/*.ts"]
13
+ }
package/tsup.config.js ADDED
@@ -0,0 +1,19 @@
1
+ module.exports = function defineConfig() {
2
+ return {
3
+ entry: ["src/index.ts"],
4
+ external: [],
5
+ noExternal: [],
6
+ platform: "node",
7
+ format: ["esm", "cjs"],
8
+ target: "es2022",
9
+ skipNodeModulesBundle: true,
10
+ clean: true,
11
+ shims: true,
12
+ minify: false,
13
+ splitting: false,
14
+ keepNames: true,
15
+ dts: true,
16
+ sourcemap: true,
17
+ esbuildPlugins: [],
18
+ };
19
+ };