@tylix/mail 1.1.0 → 1.3.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/Mailable.js +6 -2
- package/Mailer.js +102 -49
- package/README.md +132 -20
- package/SmtpClient.js +46 -135
- package/createMailer.js +181 -0
- package/index.d.ts +220 -27
- package/index.js +9 -1
- package/mime.js +266 -0
- package/models/MailLog.js +30 -15
- package/package.json +23 -11
- package/template.js +125 -0
- package/transports/dev.js +29 -0
- package/transports/http.js +36 -0
- package/transports/index.js +8 -0
- package/transports/mailgun.js +39 -0
- package/transports/postmark.js +47 -0
- package/transports/resend.js +39 -0
- package/transports/sendgrid.js +46 -0
- package/transports/ses.js +87 -0
- package/transports/smtp.js +16 -0
- package/drivers/LogDriver.js +0 -16
- package/drivers/SmtpDriver.js +0 -20
package/mime.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Builds RFC 5322 / MIME messages. Used by the SMTP and Amazon SES
|
|
2
|
+
// transports (both take a raw message) and by preview().
|
|
3
|
+
//
|
|
4
|
+
// const { raw, envelope } = await buildMime(normalizeMessage(message))
|
|
5
|
+
//
|
|
6
|
+
// Layout, outermost first, only as deep as the message needs:
|
|
7
|
+
// multipart/mixed when there are regular attachments
|
|
8
|
+
// multipart/related when there are inline images (cid)
|
|
9
|
+
// multipart/alternative text + html
|
|
10
|
+
import crypto from 'node:crypto'
|
|
11
|
+
import fs from 'node:fs/promises'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------- checks
|
|
15
|
+
|
|
16
|
+
// Any CR or LF in a header value would let the caller add headers of
|
|
17
|
+
// their own (or extra SMTP commands, for the envelope addresses).
|
|
18
|
+
export function assertNoLineBreaks(value, label) {
|
|
19
|
+
if (typeof value !== 'string' || /[\r\n]/.test(value)) {
|
|
20
|
+
throw new Error(`Invalid ${label}: line breaks are not allowed`)
|
|
21
|
+
}
|
|
22
|
+
return value
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ------------------------------------------------------------- addresses
|
|
26
|
+
|
|
27
|
+
// Accepts "ada@example.com", "Ada Lovelace <ada@example.com>" or
|
|
28
|
+
// { name, address } and returns { name, address }.
|
|
29
|
+
export function parseAddress(input, label = 'address') {
|
|
30
|
+
let name = ''
|
|
31
|
+
let address
|
|
32
|
+
if (input && typeof input === 'object') {
|
|
33
|
+
name = input.name ?? ''
|
|
34
|
+
address = input.address ?? input.email
|
|
35
|
+
} else if (typeof input === 'string') {
|
|
36
|
+
const m = /^\s*(.*?)\s*<([^<>]+)>\s*$/.exec(input)
|
|
37
|
+
if (m) {
|
|
38
|
+
name = m[1].replace(/^"(.*)"$/, '$1')
|
|
39
|
+
address = m[2]
|
|
40
|
+
} else {
|
|
41
|
+
address = input.trim()
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (typeof address !== 'string') throw new Error(`Invalid ${label}: missing email address`)
|
|
45
|
+
assertNoLineBreaks(address, label)
|
|
46
|
+
assertNoLineBreaks(name, `${label} name`)
|
|
47
|
+
if (!/^[^\s@<>]+@[^\s@<>]+$/.test(address)) {
|
|
48
|
+
throw new Error(`Invalid ${label}: "${address}" is not an email address`)
|
|
49
|
+
}
|
|
50
|
+
return { name, address }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function parseAddressList(input, label) {
|
|
54
|
+
if (input == null || input === '') return []
|
|
55
|
+
return [].concat(input).map((a) => parseAddress(a, label))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function formatAddress({ name, address }) {
|
|
59
|
+
if (!name) return address
|
|
60
|
+
// Letters, digits and spaces go as they are; other printable ASCII
|
|
61
|
+
// (dots, commas, quotes...) is quoted; anything else is encoded.
|
|
62
|
+
if (/^[A-Za-z0-9 ]*$/.test(name)) return `${name} <${address}>`
|
|
63
|
+
if (/^[\x20-\x7e]*$/.test(name)) return `"${name.replace(/(["\\])/g, '\\$1')}" <${address}>`
|
|
64
|
+
return `${encodeHeaderValue(name)} <${address}>`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---------------------------------------------------------------- encoding
|
|
68
|
+
|
|
69
|
+
// RFC 2047: non-ASCII header text is sent as encoded words. Each word
|
|
70
|
+
// stays under the 75-character limit, and multi-byte characters are
|
|
71
|
+
// never split across words.
|
|
72
|
+
export function encodeHeaderValue(value) {
|
|
73
|
+
assertNoLineBreaks(value, 'header value')
|
|
74
|
+
if (/^[\x20-\x7e]*$/.test(value)) return value
|
|
75
|
+
|
|
76
|
+
const words = []
|
|
77
|
+
let chunk = ''
|
|
78
|
+
let bytes = 0
|
|
79
|
+
for (const ch of value) {
|
|
80
|
+
const size = Buffer.byteLength(ch)
|
|
81
|
+
if (bytes + size > 45) {
|
|
82
|
+
words.push(chunk)
|
|
83
|
+
chunk = ''
|
|
84
|
+
bytes = 0
|
|
85
|
+
}
|
|
86
|
+
chunk += ch
|
|
87
|
+
bytes += size
|
|
88
|
+
}
|
|
89
|
+
if (chunk) words.push(chunk)
|
|
90
|
+
return words.map((w) => `=?UTF-8?B?${Buffer.from(w).toString('base64')}?=`).join('\r\n ')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Base64 body parts need no line-ending normalisation or dot-stuffing:
|
|
94
|
+
// the encoded text only has A-Z a-z 0-9 + / = and is wrapped at 76.
|
|
95
|
+
function base64Lines(value) {
|
|
96
|
+
const encoded = Buffer.from(value).toString('base64')
|
|
97
|
+
return (encoded.match(/.{1,76}/g) ?? []).join('\r\n')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// RFC 2231 filename for non-ASCII names, plain quoted otherwise.
|
|
101
|
+
function filenameParam(name) {
|
|
102
|
+
if (/^[\x20-\x7e]*$/.test(name)) return `filename="${name.replace(/(["\\])/g, '\\$1')}"`
|
|
103
|
+
return `filename*=UTF-8''${encodeURIComponent(name)}`
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Rough plain-text version of an HTML body, so the text part is never
|
|
107
|
+
// empty and clients that prefer text show something readable.
|
|
108
|
+
export function htmlToText(html) {
|
|
109
|
+
return String(html)
|
|
110
|
+
.replace(/<(style|script|head)[\s\S]*?<\/\1>/gi, '')
|
|
111
|
+
.replace(/<a\s[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, (_, href, label) => {
|
|
112
|
+
const text = label.replace(/<[^>]+>/g, '').trim()
|
|
113
|
+
return text && text !== href ? `${text} (${href})` : href
|
|
114
|
+
})
|
|
115
|
+
.replace(/<li[^>]*>/gi, '\n- ')
|
|
116
|
+
.replace(/<br\s*\/?>|<\/p>|<\/div>|<\/h[1-6]>|<\/tr>/gi, '\n')
|
|
117
|
+
.replace(/<[^>]+>/g, '')
|
|
118
|
+
.replace(/ /g, ' ')
|
|
119
|
+
.replace(/</g, '<')
|
|
120
|
+
.replace(/>/g, '>')
|
|
121
|
+
.replace(/"/g, '"')
|
|
122
|
+
.replace(/'/g, "'")
|
|
123
|
+
.replace(/&/g, '&')
|
|
124
|
+
.replace(/[ \t]+\n/g, '\n')
|
|
125
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
126
|
+
.trim()
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ------------------------------------------------------------ attachments
|
|
130
|
+
|
|
131
|
+
const TYPES = {
|
|
132
|
+
pdf: 'application/pdf', zip: 'application/zip', json: 'application/json',
|
|
133
|
+
csv: 'text/csv', txt: 'text/plain', html: 'text/html', ics: 'text/calendar',
|
|
134
|
+
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
|
|
135
|
+
webp: 'image/webp', svg: 'image/svg+xml',
|
|
136
|
+
doc: 'application/msword', xls: 'application/vnd.ms-excel',
|
|
137
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
138
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function contentTypeFor(filename) {
|
|
142
|
+
const ext = path.extname(filename ?? '').slice(1).toLowerCase()
|
|
143
|
+
return TYPES[ext] ?? 'application/octet-stream'
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Reads `path` attachments and fills in filename / contentType, giving
|
|
147
|
+
// { filename, content: Buffer, contentType, cid? }
|
|
148
|
+
export async function loadAttachments(list = []) {
|
|
149
|
+
return Promise.all(
|
|
150
|
+
list.map(async (a, i) => {
|
|
151
|
+
if (!a || typeof a !== 'object') throw new Error(`Invalid attachment #${i + 1}`)
|
|
152
|
+
let content = a.content
|
|
153
|
+
if (content == null && a.path) content = await fs.readFile(a.path)
|
|
154
|
+
if (content == null) throw new Error(`Attachment #${i + 1} needs content or path`)
|
|
155
|
+
if (typeof content === 'string') {
|
|
156
|
+
content = a.encoding === 'base64' ? Buffer.from(content, 'base64') : Buffer.from(content)
|
|
157
|
+
} else if (!Buffer.isBuffer(content)) {
|
|
158
|
+
content = Buffer.from(content)
|
|
159
|
+
}
|
|
160
|
+
const filename = a.filename ?? (a.path ? path.basename(a.path) : `attachment-${i + 1}`)
|
|
161
|
+
assertNoLineBreaks(filename, 'attachment filename')
|
|
162
|
+
if (a.cid != null) assertNoLineBreaks(String(a.cid), 'attachment cid')
|
|
163
|
+
return {
|
|
164
|
+
filename,
|
|
165
|
+
content,
|
|
166
|
+
contentType: a.contentType ?? contentTypeFor(filename),
|
|
167
|
+
cid: a.cid ?? null,
|
|
168
|
+
}
|
|
169
|
+
}),
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------------------------------------------------------------- message
|
|
174
|
+
|
|
175
|
+
// Turns what the caller passed into one consistent shape. Throws on
|
|
176
|
+
// anything that cannot be sent, before any connection is made.
|
|
177
|
+
export function normalizeMessage(message, defaults = {}) {
|
|
178
|
+
const m = { ...defaults, ...message }
|
|
179
|
+
const from = parseAddress(m.from, 'from address')
|
|
180
|
+
const to = parseAddressList(m.to, 'to address')
|
|
181
|
+
const cc = parseAddressList(m.cc, 'cc address')
|
|
182
|
+
const bcc = parseAddressList(m.bcc, 'bcc address')
|
|
183
|
+
if (to.length + cc.length + bcc.length === 0) throw new Error('A message needs at least one recipient')
|
|
184
|
+
const replyTo = parseAddressList(m.replyTo, 'replyTo address')
|
|
185
|
+
const subject = assertNoLineBreaks(m.subject ?? '', 'subject')
|
|
186
|
+
const headers = {}
|
|
187
|
+
for (const [k, v] of Object.entries(m.headers ?? {})) {
|
|
188
|
+
if (!/^[A-Za-z0-9-]+$/.test(k)) throw new Error(`Invalid header name "${k}"`)
|
|
189
|
+
headers[k] = assertNoLineBreaks(String(v), `header ${k}`)
|
|
190
|
+
}
|
|
191
|
+
const html = m.html ?? ''
|
|
192
|
+
const text = m.text ?? (html ? htmlToText(html) : '')
|
|
193
|
+
return {
|
|
194
|
+
from, to, cc, bcc, replyTo, subject, html, text, headers,
|
|
195
|
+
attachments: m.attachments ?? [],
|
|
196
|
+
tags: m.tags ?? {},
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function boundary() {
|
|
201
|
+
return `tylix-${crypto.randomBytes(12).toString('hex')}`
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function textPart(type, body) {
|
|
205
|
+
return [`Content-Type: ${type}; charset=utf-8`, 'Content-Transfer-Encoding: base64', '', base64Lines(body)].join('\r\n')
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function attachmentPart(a, inline) {
|
|
209
|
+
const lines = [
|
|
210
|
+
`Content-Type: ${a.contentType}; name="${a.filename.replace(/[^\x20-\x7e]|["\\]/g, '_')}"`,
|
|
211
|
+
'Content-Transfer-Encoding: base64',
|
|
212
|
+
`Content-Disposition: ${inline ? 'inline' : 'attachment'}; ${filenameParam(a.filename)}`,
|
|
213
|
+
]
|
|
214
|
+
if (inline) lines.push(`Content-ID: <${a.cid}>`)
|
|
215
|
+
lines.push('', base64Lines(a.content))
|
|
216
|
+
return lines.join('\r\n')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function multipart(type, parts) {
|
|
220
|
+
const b = boundary()
|
|
221
|
+
return [
|
|
222
|
+
`Content-Type: multipart/${type}; boundary="${b}"`,
|
|
223
|
+
'',
|
|
224
|
+
...parts.flatMap((p) => [`--${b}`, p]),
|
|
225
|
+
`--${b}--`,
|
|
226
|
+
].join('\r\n')
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// { raw, envelope: { from, to[] }, messageId } for a normalized message
|
|
230
|
+
// whose attachments are already loaded (loadAttachments).
|
|
231
|
+
export function buildMime(msg, { date = new Date(), messageId } = {}) {
|
|
232
|
+
const domain = msg.from.address.split('@')[1]
|
|
233
|
+
const id = messageId ?? `<${crypto.randomUUID()}@${domain}>`
|
|
234
|
+
|
|
235
|
+
const headers = [
|
|
236
|
+
`From: ${formatAddress(msg.from)}`,
|
|
237
|
+
msg.to.length ? `To: ${msg.to.map(formatAddress).join(', ')}` : null,
|
|
238
|
+
msg.cc.length ? `Cc: ${msg.cc.map(formatAddress).join(', ')}` : null,
|
|
239
|
+
// Bcc recipients are only in the envelope, never in the headers.
|
|
240
|
+
msg.replyTo.length ? `Reply-To: ${msg.replyTo.map(formatAddress).join(', ')}` : null,
|
|
241
|
+
`Subject: ${encodeHeaderValue(msg.subject)}`,
|
|
242
|
+
// RFC 5322 date, with a numeric zone instead of "GMT".
|
|
243
|
+
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
|
|
244
|
+
`Message-ID: ${id}`,
|
|
245
|
+
'MIME-Version: 1.0',
|
|
246
|
+
...Object.entries(msg.headers).map(([k, v]) => `${k}: ${encodeHeaderValue(v)}`),
|
|
247
|
+
].filter(Boolean)
|
|
248
|
+
|
|
249
|
+
const inline = msg.attachments.filter((a) => a.cid)
|
|
250
|
+
const regular = msg.attachments.filter((a) => !a.cid)
|
|
251
|
+
|
|
252
|
+
let body = msg.html
|
|
253
|
+
? multipart('alternative', [textPart('text/plain', msg.text), textPart('text/html', msg.html)])
|
|
254
|
+
: textPart('text/plain', msg.text)
|
|
255
|
+
if (inline.length) body = multipart('related', [body, ...inline.map((a) => attachmentPart(a, true))])
|
|
256
|
+
if (regular.length) body = multipart('mixed', [body, ...regular.map((a) => attachmentPart(a, false))])
|
|
257
|
+
|
|
258
|
+
return {
|
|
259
|
+
raw: `${headers.join('\r\n')}\r\n${body}\r\n`,
|
|
260
|
+
messageId: id,
|
|
261
|
+
envelope: {
|
|
262
|
+
from: msg.from.address,
|
|
263
|
+
to: [...msg.to, ...msg.cc, ...msg.bcc].map((a) => a.address),
|
|
264
|
+
},
|
|
265
|
+
}
|
|
266
|
+
}
|
package/models/MailLog.js
CHANGED
|
@@ -1,17 +1,32 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
'status',
|
|
11
|
-
'error',
|
|
12
|
-
]
|
|
1
|
+
// mail_logs rows, when the app uses @tylix/orm. Without it (a plain
|
|
2
|
+
// Node app using createMailer) this is a stand-in with available=false,
|
|
3
|
+
// and Mail skips logging.
|
|
4
|
+
let Model = null
|
|
5
|
+
try {
|
|
6
|
+
;({ Model } = await import('@tylix/orm'))
|
|
7
|
+
} catch {
|
|
8
|
+
Model = null
|
|
9
|
+
}
|
|
13
10
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
11
|
+
function missing() {
|
|
12
|
+
throw new Error('MailLog needs @tylix/orm: npm install @tylix/orm')
|
|
17
13
|
}
|
|
14
|
+
|
|
15
|
+
export const MailLog = Model
|
|
16
|
+
? class MailLog extends Model {
|
|
17
|
+
static available = true
|
|
18
|
+
static table = 'mail_logs'
|
|
19
|
+
static fillable = ['recipient', 'subject', 'body', 'driver', 'status', 'error']
|
|
20
|
+
|
|
21
|
+
static async recent(limit = 50) {
|
|
22
|
+
return this.query().orderBy('created_at', 'DESC').limit(limit).get()
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
: class MailLog {
|
|
26
|
+
static available = false
|
|
27
|
+
static create = missing
|
|
28
|
+
static query = missing
|
|
29
|
+
static async recent() {
|
|
30
|
+
return []
|
|
31
|
+
}
|
|
32
|
+
}
|
package/package.json
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/mail",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "1.3.0",
|
|
4
|
+
"description": "Email for any Node app: SMTP, Resend, SendGrid, Postmark, Mailgun and Amazon SES transports, templates, attachments and a test fake. Plugs into Tylix with Mailables and a mail log.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Mbiyrukzz",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"keywords": [
|
|
9
|
-
"tylix",
|
|
10
9
|
"mail",
|
|
11
10
|
"email",
|
|
12
|
-
"smtp"
|
|
11
|
+
"smtp",
|
|
12
|
+
"resend",
|
|
13
|
+
"sendgrid",
|
|
14
|
+
"postmark",
|
|
15
|
+
"mailgun",
|
|
16
|
+
"ses",
|
|
17
|
+
"tylix"
|
|
13
18
|
],
|
|
14
19
|
"homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/mail#readme",
|
|
15
20
|
"repository": {
|
|
@@ -37,9 +42,12 @@
|
|
|
37
42
|
"index.d.ts",
|
|
38
43
|
"Mailer.js",
|
|
39
44
|
"Mailable.js",
|
|
40
|
-
"
|
|
41
|
-
"
|
|
45
|
+
"createMailer.js",
|
|
46
|
+
"mime.js",
|
|
47
|
+
"template.js",
|
|
42
48
|
"SmtpClient.js",
|
|
49
|
+
"models",
|
|
50
|
+
"transports",
|
|
43
51
|
"!**/*.test.js",
|
|
44
52
|
"!**/*.test.mjs",
|
|
45
53
|
"README.md",
|
|
@@ -48,11 +56,15 @@
|
|
|
48
56
|
"publishConfig": {
|
|
49
57
|
"access": "public"
|
|
50
58
|
},
|
|
51
|
-
"dependencies": {
|
|
52
|
-
"@tylix/shared": "^1.1.0",
|
|
53
|
-
"@tylix/generator": "^1.1.0"
|
|
54
|
-
},
|
|
55
59
|
"peerDependencies": {
|
|
56
|
-
"@tylix/orm": "^1.
|
|
60
|
+
"@tylix/orm": "^1.3.0"
|
|
61
|
+
},
|
|
62
|
+
"peerDependenciesMeta": {
|
|
63
|
+
"@tylix/orm": {
|
|
64
|
+
"optional": true
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
"scripts": {
|
|
68
|
+
"test": "node --test test/*.test.js"
|
|
57
69
|
}
|
|
58
70
|
}
|
package/template.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Mail templates: HTML (and optional text) files with placeholders.
|
|
2
|
+
//
|
|
3
|
+
// {{ name }} value, HTML-escaped
|
|
4
|
+
// {{ user.name }} dotted paths
|
|
5
|
+
// {{{ html }}} value inserted as-is (trusted HTML only)
|
|
6
|
+
// {{#if cond}}…{{#else}}…{{/if}}
|
|
7
|
+
// {{#each items}}…{{ this.title }} {{ @index }}…{{/each}}
|
|
8
|
+
//
|
|
9
|
+
// A placeholder whose value is missing (undefined) throws, so a typo in
|
|
10
|
+
// a template fails loudly instead of mailing "undefined" to a customer.
|
|
11
|
+
import fs from 'node:fs/promises'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
|
|
14
|
+
const ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
|
|
15
|
+
export function escapeHtml(value) {
|
|
16
|
+
return String(value).replace(/[&<>"']/g, (c) => ESCAPES[c])
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function lookup(scopes, expr, template) {
|
|
20
|
+
const parts = expr.split('.')
|
|
21
|
+
for (const scope of scopes) {
|
|
22
|
+
if (scope == null || typeof scope !== 'object') continue
|
|
23
|
+
if (parts[0] === 'this') return dig(scope.this, parts.slice(1), expr)
|
|
24
|
+
if (parts[0] in scope) return dig(scope, parts, expr)
|
|
25
|
+
}
|
|
26
|
+
throw new Error(`Mail template variable "${expr}" was not provided in data${template ? ` (${template})` : ''}.`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function dig(value, parts, expr) {
|
|
30
|
+
let v = value
|
|
31
|
+
for (const p of parts) {
|
|
32
|
+
if (v == null) return undefined
|
|
33
|
+
v = v[p]
|
|
34
|
+
}
|
|
35
|
+
return v
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Finds the {{/name}} that closes the block opened just before `from`,
|
|
39
|
+
// skipping nested blocks of the same kind.
|
|
40
|
+
function findClose(src, name, from) {
|
|
41
|
+
const re = new RegExp(`\\{\\{\\s*(#${name}\\b|/${name}\\s*\\}\\})`, 'g')
|
|
42
|
+
re.lastIndex = from
|
|
43
|
+
let depth = 1
|
|
44
|
+
for (let m; (m = re.exec(src)); ) {
|
|
45
|
+
depth += m[1].startsWith('#') ? 1 : -1
|
|
46
|
+
if (depth === 0) return { start: m.index, end: m.index + m[0].length }
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`Unclosed {{#${name}}} in mail template`)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// {{#else}} at the top level of an if-block body.
|
|
52
|
+
function splitElse(body) {
|
|
53
|
+
const re = /\{\{\s*(#if\b|\/if\s*\}\}|#else\s*\}\})/g
|
|
54
|
+
let depth = 0
|
|
55
|
+
for (let m; (m = re.exec(body)); ) {
|
|
56
|
+
if (m[1].startsWith('#if')) depth++
|
|
57
|
+
else if (m[1].startsWith('/if')) depth--
|
|
58
|
+
else if (depth === 0) return [body.slice(0, m.index), body.slice(m.index + m[0].length)]
|
|
59
|
+
}
|
|
60
|
+
return [body, '']
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function renderWith(src, scopes, name) {
|
|
64
|
+
let out = ''
|
|
65
|
+
let i = 0
|
|
66
|
+
const tag = /\{\{\{\s*([\w$.@]+)\s*\}\}\}|\{\{\s*(#if|#each)\s+([\w$.@]+)\s*\}\}|\{\{\s*([\w$.@]+)\s*\}\}/g
|
|
67
|
+
for (let m; (m = tag.exec(src.slice(i))); ) {
|
|
68
|
+
const at = i + m.index
|
|
69
|
+
out += src.slice(i, at)
|
|
70
|
+
const after = at + m[0].length
|
|
71
|
+
if (m[1]) {
|
|
72
|
+
out += String(lookup(scopes, m[1], name) ?? '')
|
|
73
|
+
i = after
|
|
74
|
+
} else if (m[2]) {
|
|
75
|
+
const kind = m[2].slice(1)
|
|
76
|
+
const close = findClose(src, kind, after)
|
|
77
|
+
const body = src.slice(after, close.start)
|
|
78
|
+
const value = lookup(scopes, m[3], name)
|
|
79
|
+
if (kind === 'if') {
|
|
80
|
+
const [yes, no] = splitElse(body)
|
|
81
|
+
const truthy = Array.isArray(value) ? value.length > 0 : Boolean(value)
|
|
82
|
+
out += renderWith(truthy ? yes : no, scopes, name)
|
|
83
|
+
} else {
|
|
84
|
+
const list = value == null ? [] : Array.from(value)
|
|
85
|
+
list.forEach((item, index) => {
|
|
86
|
+
const frame = { this: item, '@index': index }
|
|
87
|
+
out += renderWith(body, [frame, item, ...scopes], name)
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
i = close.end
|
|
91
|
+
} else {
|
|
92
|
+
const v = lookup(scopes, m[4], name)
|
|
93
|
+
if (v === undefined) {
|
|
94
|
+
throw new Error(`Mail template variable "${m[4]}" was not provided in data${name ? ` (${name})` : ''}.`)
|
|
95
|
+
}
|
|
96
|
+
out += escapeHtml(v ?? '')
|
|
97
|
+
i = after
|
|
98
|
+
}
|
|
99
|
+
tag.lastIndex = 0
|
|
100
|
+
}
|
|
101
|
+
return out + src.slice(i)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function renderTemplate(template, data = {}, name = '') {
|
|
105
|
+
return renderWith(template, [data], name)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// The default view loader: `<dir>/<view>.html` and, when it exists,
|
|
109
|
+
// `<dir>/<view>.txt` for the plain-text part.
|
|
110
|
+
// createViewRenderer('resources/mail')('welcome', { name: 'Ada' })
|
|
111
|
+
// -> { html, text? }
|
|
112
|
+
export function createViewRenderer(dir) {
|
|
113
|
+
return async function render(view, data) {
|
|
114
|
+
if (/[\\/]\.\.|^\.\./.test(view)) throw new Error(`Invalid mail view "${view}"`)
|
|
115
|
+
const base = path.resolve(dir, view)
|
|
116
|
+
const html = renderTemplate(await fs.readFile(`${base}.html`, 'utf-8'), data, `${view}.html`)
|
|
117
|
+
let text
|
|
118
|
+
try {
|
|
119
|
+
text = renderTemplate(await fs.readFile(`${base}.txt`, 'utf-8'), data, `${view}.txt`)
|
|
120
|
+
} catch (err) {
|
|
121
|
+
if (err.code !== 'ENOENT') throw err
|
|
122
|
+
}
|
|
123
|
+
return { html, text }
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { formatAddress } from '../mime.js'
|
|
2
|
+
|
|
3
|
+
// log(): prints each message instead of sending it (the default when no
|
|
4
|
+
// transport is configured).
|
|
5
|
+
export function log({ logger = console, showBody = true } = {}) {
|
|
6
|
+
return {
|
|
7
|
+
name: 'log',
|
|
8
|
+
async send(msg) {
|
|
9
|
+
const to = [...msg.to, ...msg.cc, ...msg.bcc].map(formatAddress).join(', ')
|
|
10
|
+
const files = msg.attachments.length ? `\n Attachments: ${msg.attachments.map((a) => a.filename).join(', ')}` : ''
|
|
11
|
+
logger.log(`\n📧 [mail:log] To: ${to}\n Subject: ${msg.subject}${files}${showBody ? `\n${msg.html || msg.text}` : ''}\n`)
|
|
12
|
+
return { status: 'captured', id: null }
|
|
13
|
+
},
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// memory(): keeps every message in `.messages` (newest last). Mostly for
|
|
18
|
+
// tests; see fake() for assertions.
|
|
19
|
+
export function memory() {
|
|
20
|
+
const messages = []
|
|
21
|
+
return {
|
|
22
|
+
name: 'memory',
|
|
23
|
+
messages,
|
|
24
|
+
async send(msg) {
|
|
25
|
+
messages.push(msg)
|
|
26
|
+
return { status: 'captured', id: `memory-${messages.length}` }
|
|
27
|
+
},
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Shared by the HTTP API transports.
|
|
2
|
+
import { formatAddress } from '../mime.js'
|
|
3
|
+
|
|
4
|
+
export class MailTransportError extends Error {
|
|
5
|
+
constructor(provider, status, body) {
|
|
6
|
+
const detail =
|
|
7
|
+
(body && typeof body === 'object' && (body.message || body.Message || body.errors?.[0]?.message || body.error)) ||
|
|
8
|
+
(typeof body === 'string' ? body.slice(0, 300) : '')
|
|
9
|
+
super(`${provider} rejected the message (HTTP ${status})${detail ? `: ${detail}` : ''}`)
|
|
10
|
+
this.name = 'MailTransportError'
|
|
11
|
+
this.provider = provider
|
|
12
|
+
this.status = status
|
|
13
|
+
this.response = body
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function requireOption(value, provider, name) {
|
|
18
|
+
if (!value) throw new Error(`The ${provider} mail transport needs \`${name}\``)
|
|
19
|
+
return value
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function request(provider, fetchImpl, url, init) {
|
|
23
|
+
const doFetch = fetchImpl ?? globalThis.fetch
|
|
24
|
+
if (typeof doFetch !== 'function') throw new Error(`The ${provider} mail transport needs fetch (Node 18+)`)
|
|
25
|
+
const res = await doFetch(url, init)
|
|
26
|
+
const raw = await res.text()
|
|
27
|
+
let body = raw
|
|
28
|
+
try {
|
|
29
|
+
body = raw ? JSON.parse(raw) : null
|
|
30
|
+
} catch {}
|
|
31
|
+
if (!res.ok) throw new MailTransportError(provider, res.status, body)
|
|
32
|
+
return { res, body }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const addr = (a) => formatAddress(a)
|
|
36
|
+
export const b64 = (buf) => Buffer.from(buf).toString('base64')
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { smtp } from './smtp.js'
|
|
2
|
+
export { resend } from './resend.js'
|
|
3
|
+
export { sendgrid } from './sendgrid.js'
|
|
4
|
+
export { postmark } from './postmark.js'
|
|
5
|
+
export { mailgun } from './mailgun.js'
|
|
6
|
+
export { ses, signAwsRequest, signingKey } from './ses.js'
|
|
7
|
+
export { log, memory } from './dev.js'
|
|
8
|
+
export { MailTransportError } from './http.js'
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Mailgun: https://documentation.mailgun.com/docs/mailgun/api-reference/send/mailgun/messages
|
|
2
|
+
import { addr, request, requireOption } from './http.js'
|
|
3
|
+
|
|
4
|
+
export function mailgun({ apiKey, domain, region = 'us', endpoint, fetch } = {}) {
|
|
5
|
+
requireOption(apiKey, 'mailgun', 'apiKey')
|
|
6
|
+
requireOption(domain, 'mailgun', 'domain')
|
|
7
|
+
const base = endpoint ?? (region === 'eu' ? 'https://api.eu.mailgun.net' : 'https://api.mailgun.net')
|
|
8
|
+
return {
|
|
9
|
+
name: 'mailgun',
|
|
10
|
+
async send(msg) {
|
|
11
|
+
const form = new FormData()
|
|
12
|
+
form.append('from', addr(msg.from))
|
|
13
|
+
for (const a of msg.to) form.append('to', addr(a))
|
|
14
|
+
for (const a of msg.cc) form.append('cc', addr(a))
|
|
15
|
+
for (const a of msg.bcc) form.append('bcc', addr(a))
|
|
16
|
+
form.append('subject', msg.subject)
|
|
17
|
+
if (msg.text) form.append('text', msg.text)
|
|
18
|
+
if (msg.html) form.append('html', msg.html)
|
|
19
|
+
if (msg.replyTo.length) form.append('h:Reply-To', msg.replyTo.map(addr).join(', '))
|
|
20
|
+
for (const [k, v] of Object.entries(msg.headers)) form.append(`h:${k}`, v)
|
|
21
|
+
for (const [k, v] of Object.entries(msg.tags)) {
|
|
22
|
+
if (k === 'tag') form.append('o:tag', String(v))
|
|
23
|
+
else form.append(`v:${k}`, String(v))
|
|
24
|
+
}
|
|
25
|
+
for (const a of msg.attachments) {
|
|
26
|
+
// Inline images are matched by filename: <img src="cid:NAME">.
|
|
27
|
+
const blob = new Blob([a.content], { type: a.contentType })
|
|
28
|
+
if (a.cid) form.append('inline', blob, a.cid)
|
|
29
|
+
else form.append('attachment', blob, a.filename)
|
|
30
|
+
}
|
|
31
|
+
const { body } = await request('Mailgun', fetch, `${base}/v3/${encodeURIComponent(domain)}/messages`, {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
headers: { Authorization: `Basic ${Buffer.from(`api:${apiKey}`).toString('base64')}` },
|
|
34
|
+
body: form,
|
|
35
|
+
})
|
|
36
|
+
return { status: 'sent', id: body?.id ?? null }
|
|
37
|
+
},
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Postmark: https://postmarkapp.com/developer/api/email-api
|
|
2
|
+
import { addr, b64, request, requireOption } from './http.js'
|
|
3
|
+
|
|
4
|
+
export function postmark({ serverToken, messageStream, endpoint = 'https://api.postmarkapp.com', fetch } = {}) {
|
|
5
|
+
requireOption(serverToken, 'postmark', 'serverToken')
|
|
6
|
+
return {
|
|
7
|
+
name: 'postmark',
|
|
8
|
+
async send(msg) {
|
|
9
|
+
const list = (xs) => (xs.length ? xs.map(addr).join(', ') : undefined)
|
|
10
|
+
const payload = {
|
|
11
|
+
From: addr(msg.from),
|
|
12
|
+
To: list(msg.to),
|
|
13
|
+
Cc: list(msg.cc),
|
|
14
|
+
Bcc: list(msg.bcc),
|
|
15
|
+
ReplyTo: list(msg.replyTo),
|
|
16
|
+
Subject: msg.subject,
|
|
17
|
+
HtmlBody: msg.html || undefined,
|
|
18
|
+
TextBody: msg.text || undefined,
|
|
19
|
+
MessageStream: messageStream,
|
|
20
|
+
}
|
|
21
|
+
if (Object.keys(msg.headers).length) {
|
|
22
|
+
payload.Headers = Object.entries(msg.headers).map(([Name, Value]) => ({ Name, Value }))
|
|
23
|
+
}
|
|
24
|
+
if (msg.tags.tag) payload.Tag = String(msg.tags.tag)
|
|
25
|
+
const metadata = Object.entries(msg.tags).filter(([k]) => k !== 'tag')
|
|
26
|
+
if (metadata.length) payload.Metadata = Object.fromEntries(metadata.map(([k, v]) => [k, String(v)]))
|
|
27
|
+
if (msg.attachments.length) {
|
|
28
|
+
payload.Attachments = msg.attachments.map((a) => ({
|
|
29
|
+
Name: a.filename,
|
|
30
|
+
Content: b64(a.content),
|
|
31
|
+
ContentType: a.contentType,
|
|
32
|
+
...(a.cid ? { ContentID: `cid:${a.cid}` } : {}),
|
|
33
|
+
}))
|
|
34
|
+
}
|
|
35
|
+
const { body } = await request('Postmark', fetch, `${endpoint}/email`, {
|
|
36
|
+
method: 'POST',
|
|
37
|
+
headers: {
|
|
38
|
+
'X-Postmark-Server-Token': serverToken,
|
|
39
|
+
Accept: 'application/json',
|
|
40
|
+
'Content-Type': 'application/json',
|
|
41
|
+
},
|
|
42
|
+
body: JSON.stringify(payload),
|
|
43
|
+
})
|
|
44
|
+
return { status: 'sent', id: body?.MessageID ?? null }
|
|
45
|
+
},
|
|
46
|
+
}
|
|
47
|
+
}
|