@cslug/mail 0.0.0-stage → 0.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.
- package/README.md +7 -2
- package/docs/README.md +55 -0
- package/docs/api.md +16 -0
- package/package.json +49 -4
- package/src/fake.ts +106 -0
- package/src/html.ts +117 -0
- package/src/index.ts +30 -0
- package/src/mailable.ts +88 -0
- package/src/mailer.ts +153 -0
- package/src/message.ts +93 -0
- package/src/provider.ts +141 -0
- package/src/smtp.ts +127 -0
- package/src/transports.ts +177 -0
package/README.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/mail
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Mailables rendered from Vue views (CSS inlined, plain-text part derived), a `Mailer` that sends now or queues the
|
|
4
|
+
rendered message, and transports: SMTP (own client: STARTTLS, AUTH), Resend, Postmark, Brevo, log, array.
|
|
5
|
+
List `MailProvider` in `bootstrap/providers.ts`.
|
|
6
|
+
|
|
7
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
8
|
+
[guide 14](../../guides/14-mail-and-notifications.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# @cslug/mail
|
|
2
|
+
|
|
3
|
+
List `MailProvider` in `bootstrap/providers.ts` (after `QueueProvider` if queued mail should go through the queue).
|
|
4
|
+
The guide is [guide 14](../../../guides/14-mail-and-notifications.md).
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
export class TodoDueMail extends Mailable {
|
|
8
|
+
static queued = true
|
|
9
|
+
constructor(private name: string, private items: DueItem[]) { super() }
|
|
10
|
+
build() {
|
|
11
|
+
return this.subject(t('mail.todo_due.subject', { count: this.items.length })).view(TodoDue, { name: this.name, items: this.items })
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
await mailer.to(user).locale(user.locale).send(new TodoDueMail(user.name, items))
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Rendering
|
|
19
|
+
|
|
20
|
+
`send()` renders at once, in the given locale (`withLocale`): `build()` (so `t()` translates for the recipient),
|
|
21
|
+
then the view with `@cslug/vue`'s `renderStandalone` (imported only when `.view()` is used), or `.html()`. Then:
|
|
22
|
+
|
|
23
|
+
- **CSS inlining**: `<style>` rules go into `style` attributes, in specificity then source order, with the element's
|
|
24
|
+
own `style` last (it wins). `@media` rules and pseudo-selectors (`:hover`) stay in a `<style>` block. Selectors
|
|
25
|
+
are matched by Bun's `HTMLRewriter`, so they are real CSS selectors.
|
|
26
|
+
- **The text part** is derived from the HTML unless `.text()` is set: blocks on their own lines, list items as
|
|
27
|
+
`- `, links as `text (url)`.
|
|
28
|
+
- **MIME**: multipart/alternative (text + HTML), multipart/mixed with attachments, base64 parts, RFC 2047 for
|
|
29
|
+
non-ASCII headers; `bcc` only in the envelope.
|
|
30
|
+
|
|
31
|
+
## Sending
|
|
32
|
+
|
|
33
|
+
- Not queued: the transport sends before `send()` returns.
|
|
34
|
+
- Queued (`static queued = true`, or `mail.queued: true` for all): the **rendered** message is dispatched as the
|
|
35
|
+
job `cslug.mail` on `mail.queue` (5 tries, exponential backoff), so inside a transaction it waits for COMMIT.
|
|
36
|
+
Without `@cslug/queue` it is sent after COMMIT in this process. `sendNow()` skips the queue.
|
|
37
|
+
|
|
38
|
+
Transports (`mail.transport`, configured under `mail.transports.<name>`; `driver` if the name differs):
|
|
39
|
+
|
|
40
|
+
| | |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `smtp` | Own client on `Bun.connect`: STARTTLS when offered (`socket.upgradeTLS`), `secure: true` for implicit TLS, AUTH PLAIN or LOGIN, dot-stuffed DATA. Refuses clear text to anything but localhost unless `allowPlain: true` |
|
|
43
|
+
| `resend`, `postmark`, `brevo` | `{ apiKey, endpoint? }`, through `fetch` |
|
|
44
|
+
| `log` | Writes the subject and text to the log |
|
|
45
|
+
| `array` | Keeps messages in `transport.messages` |
|
|
46
|
+
|
|
47
|
+
## Previews and tests
|
|
48
|
+
|
|
49
|
+
`cslug mail:preview [--port=3100]` serves every mailable in `app/mail/` that has a `static preview()`, in each
|
|
50
|
+
locale of `i18n.locales`, as HTML and as text.
|
|
51
|
+
|
|
52
|
+
`testApp({ fakes: ['mail'] })` swaps in `MailFake` (`t.mail`): every mail is rendered (templates are exercised) and
|
|
53
|
+
recorded. `assertSent(Mail, (m) => …)` (sent now), `assertQueued`, `assertSentCount`, `assertQueuedCount`,
|
|
54
|
+
`assertNotSent`, `assertNothingSent`, `of(Mail)`. A record has `to` (the first address), `recipients`, `cc`,
|
|
55
|
+
`bcc`, `subject`, `html`, `text`, `attachments`, `locale`, `queued` and the `mailable` itself.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# @cslug/mail: API
|
|
2
|
+
|
|
3
|
+
| | |
|
|
4
|
+
|---|---|
|
|
5
|
+
| `Mailable` | `build()`; in it: `subject`, `view(Component, props)`, `html`, `text`, `attach(content \| promise, { name, type })`, `tag`, `from`, `replyTo`, `header`. Optional statics: `queued`, `preview()` |
|
|
6
|
+
| `Mailer` | `to(...addresses)` → `PendingMail`; `send(message)` (a rendered `Message`, now); `transport`; `enqueue` (set by the provider with the queue) |
|
|
7
|
+
| `PendingMail` | `cc(...)`, `bcc(...)`, `locale(l)`, `send(mailable)`, `sendNow(mailable)` |
|
|
8
|
+
| `renderMail(mailable, { to, cc?, bcc? }, { locale?, from? })` | → `Message` |
|
|
9
|
+
| `Message` | `{ from, to, cc, bcc, replyTo?, subject, html?, text?, attachments, tags, headers }` |
|
|
10
|
+
| `address(x)`, `formatAddress(a)`, `toMime(message, { messageId, date? })` | Addresses (`string`, `{ email, name }`, `{ address, name }`) and MIME |
|
|
11
|
+
| `inlineCss(html)`, `htmlToText(html)` | The HTML steps |
|
|
12
|
+
| `sendSmtp(config, { from, to }, mime)`, `SmtpConfig`, `SmtpError` | The SMTP client |
|
|
13
|
+
| `SmtpTransport`, `ResendTransport`, `PostmarkTransport`, `BrevoTransport`, `LogTransport`, `ArrayTransport`, `createTransport(name, config, log)` | Transports (`Transport.send(message)` → `{ id }`) |
|
|
14
|
+
| `MailFake`, `installMailFake(app)`, `SentMail` | The fake (`fakes: ['mail']`) |
|
|
15
|
+
| `MailProvider` | Config `mail.{from, transport, transports, queue, queued}`; the job `cslug.mail` when @cslug/queue is installed |
|
|
16
|
+
| `MailPreviewCommand`, `previewableMailables(app)` | `cslug mail:preview` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/mail",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Mailer and mailables, CSS inlining, SMTP and HTTP API transports.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/mail"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/mail",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src",
|
|
23
|
+
"docs",
|
|
24
|
+
"stubs",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"bun": ">=1.3.14"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@cslug/core": "0.2.0",
|
|
32
|
+
"@cslug/vue": "0.2.0",
|
|
33
|
+
"@cslug/queue": "0.2.0"
|
|
34
|
+
},
|
|
35
|
+
"peerDependenciesMeta": {
|
|
36
|
+
"@cslug/vue": {
|
|
37
|
+
"optional": true
|
|
38
|
+
},
|
|
39
|
+
"@cslug/queue": {
|
|
40
|
+
"optional": true
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@cslug/testing": "workspace:*",
|
|
45
|
+
"@cslug/http": "workspace:*",
|
|
46
|
+
"@cslug/redis": "workspace:*",
|
|
47
|
+
"vue": "^3.5.0",
|
|
48
|
+
"@cslug/vue": "workspace:*",
|
|
49
|
+
"@cslug/queue": "workspace:*"
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/fake.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { type Application, Logger } from '@cslug/core'
|
|
2
|
+
import type { Mailable } from './mailable'
|
|
3
|
+
import { Mailer, type Outgoing } from './mailer'
|
|
4
|
+
import type { Attachment } from './message'
|
|
5
|
+
import { ArrayTransport } from './transports'
|
|
6
|
+
|
|
7
|
+
/** A mail the fake recorded. `to` is the first recipient's address; `recipients` all of them. */
|
|
8
|
+
export type SentMail<M extends Mailable = Mailable> = {
|
|
9
|
+
mailable: M
|
|
10
|
+
to: string
|
|
11
|
+
recipients: string[]
|
|
12
|
+
cc: string[]
|
|
13
|
+
bcc: string[]
|
|
14
|
+
subject: string
|
|
15
|
+
html?: string
|
|
16
|
+
text?: string
|
|
17
|
+
attachments: Attachment[]
|
|
18
|
+
locale: string
|
|
19
|
+
queued: boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type MailableCtor<M extends Mailable> = abstract new (...args: never[]) => M
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Mail in tests (`testApp({ fakes: ['mail'] })` → `t.mail`): every mail is rendered (so templates are exercised)
|
|
26
|
+
* and recorded, never sent.
|
|
27
|
+
*/
|
|
28
|
+
export class MailFake extends Mailer {
|
|
29
|
+
readonly sent: SentMail[] = []
|
|
30
|
+
|
|
31
|
+
constructor(app: Application, from = app.config<{ address: string; name?: string } | undefined>('mail.from')) {
|
|
32
|
+
super(app, { from: from ?? { address: 'test@example.test' } }, new ArrayTransport(), Logger.null())
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
protected override async deliver({ mailable, message, locale, queued }: Outgoing): Promise<void> {
|
|
36
|
+
this.sent.push({
|
|
37
|
+
mailable,
|
|
38
|
+
to: message.to[0]?.address ?? '',
|
|
39
|
+
recipients: message.to.map((a) => a.address),
|
|
40
|
+
cc: message.cc.map((a) => a.address),
|
|
41
|
+
bcc: message.bcc.map((a) => a.address),
|
|
42
|
+
subject: message.subject,
|
|
43
|
+
html: message.html,
|
|
44
|
+
text: message.text,
|
|
45
|
+
attachments: message.attachments,
|
|
46
|
+
locale,
|
|
47
|
+
queued,
|
|
48
|
+
})
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
of<M extends Mailable>(cls: MailableCtor<M>, queued?: boolean): SentMail<M>[] {
|
|
52
|
+
return this.sent.filter(
|
|
53
|
+
(m) => m.mailable instanceof cls && (queued === undefined || m.queued === queued),
|
|
54
|
+
) as SentMail<M>[]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private check<M extends Mailable>(
|
|
58
|
+
cls: MailableCtor<M>,
|
|
59
|
+
queued: boolean | undefined,
|
|
60
|
+
predicate?: (m: SentMail<M>) => boolean,
|
|
61
|
+
) {
|
|
62
|
+
const all = this.of(cls, queued)
|
|
63
|
+
if (!all.some((m) => !predicate || predicate(m))) {
|
|
64
|
+
const seen = this.sent.map(
|
|
65
|
+
(m) => `${m.mailable.constructor.name} to ${m.to} "${m.subject}"${m.queued ? ' (queued)' : ''}`,
|
|
66
|
+
)
|
|
67
|
+
const how = queued === undefined ? 'sent or queued' : queued ? 'queued' : 'sent'
|
|
68
|
+
throw new Error(
|
|
69
|
+
`Expected ${cls.name} to be ${how}${predicate ? ' matching the predicate' : ''}; mail: ${seen.join(', ') || 'none'}`,
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Sent now (not queued). */
|
|
75
|
+
assertSent<M extends Mailable>(cls: MailableCtor<M>, predicate?: (m: SentMail<M>) => boolean): void {
|
|
76
|
+
this.check(cls, false, predicate)
|
|
77
|
+
}
|
|
78
|
+
/** Queued (`static queued = true`). */
|
|
79
|
+
assertQueued<M extends Mailable>(cls: MailableCtor<M>, predicate?: (m: SentMail<M>) => boolean): void {
|
|
80
|
+
this.check(cls, true, predicate)
|
|
81
|
+
}
|
|
82
|
+
assertSentCount<M extends Mailable>(cls: MailableCtor<M>, count: number): void {
|
|
83
|
+
const n = this.of(cls, false).length
|
|
84
|
+
if (n !== count) throw new Error(`Expected ${cls.name} to be sent ${count} time(s), got ${n}`)
|
|
85
|
+
}
|
|
86
|
+
assertQueuedCount<M extends Mailable>(cls: MailableCtor<M>, count: number): void {
|
|
87
|
+
const n = this.of(cls, true).length
|
|
88
|
+
if (n !== count) throw new Error(`Expected ${cls.name} to be queued ${count} time(s), got ${n}`)
|
|
89
|
+
}
|
|
90
|
+
/** Neither sent nor queued. */
|
|
91
|
+
assertNotSent<M extends Mailable>(cls: MailableCtor<M>): void {
|
|
92
|
+
const n = this.of(cls).length
|
|
93
|
+
if (n) throw new Error(`Expected ${cls.name} not to be sent, got ${n}`)
|
|
94
|
+
}
|
|
95
|
+
assertNothingSent(): void {
|
|
96
|
+
if (this.sent.length)
|
|
97
|
+
throw new Error(`Expected no mail; got ${this.sent.map((m) => m.mailable.constructor.name).join(', ')}`)
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** For `@cslug/testing`: swap the mailer for a fake and return it. */
|
|
102
|
+
export function installMailFake(app: Application): MailFake {
|
|
103
|
+
const fake = new MailFake(app)
|
|
104
|
+
app.swap(Mailer, fake)
|
|
105
|
+
return fake
|
|
106
|
+
}
|
package/src/html.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
type Rule = { selector: string; declarations: string; specificity: number; order: number }
|
|
2
|
+
|
|
3
|
+
const specificity = (selector: string) => {
|
|
4
|
+
const ids = (selector.match(/#[\w-]+/g) ?? []).length
|
|
5
|
+
const classes = (selector.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+/g) ?? []).length
|
|
6
|
+
const types = (selector.replace(/[#.][\w-]+|\[[^\]]+\]|:[\w-]+(\([^)]*\))?/g, ' ').match(/[a-z][\w-]*/gi) ?? [])
|
|
7
|
+
.length
|
|
8
|
+
return ids * 10_000 + classes * 100 + types
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Rules a style attribute can take (no pseudo-classes or elements, no at-rules). */
|
|
12
|
+
const inlinable = (selector: string) => !/::?[a-z-]+/i.test(selector) && !selector.includes('@')
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Inline `<style>` rules into `style` attributes (email clients drop `<style>`). Rules apply in specificity order,
|
|
16
|
+
* then source order; an element's own `style` wins. `@media` rules and pseudo-selectors stay in a `<style>` block.
|
|
17
|
+
* Uses Bun's HTMLRewriter, so selectors are real CSS selectors.
|
|
18
|
+
*/
|
|
19
|
+
export async function inlineCss(html: string): Promise<string> {
|
|
20
|
+
const rules: Rule[] = []
|
|
21
|
+
const kept: string[] = []
|
|
22
|
+
let order = 0
|
|
23
|
+
const css = [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]).join('\n')
|
|
24
|
+
if (!css.trim()) return html
|
|
25
|
+
// at-rules (with nested braces) are kept as they are
|
|
26
|
+
const plain = css.replace(/\/\*[\s\S]*?\*\//g, '').replace(/@[^{]+\{(?:[^{}]*\{[^{}]*\})*[^{}]*\}/g, (at) => {
|
|
27
|
+
kept.push(at)
|
|
28
|
+
return ''
|
|
29
|
+
})
|
|
30
|
+
for (const [, selectors, declarations] of plain.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
|
|
31
|
+
for (const selector of (selectors as string).split(',').map((s) => s.trim())) {
|
|
32
|
+
if (!selector) continue
|
|
33
|
+
if (inlinable(selector))
|
|
34
|
+
rules.push({
|
|
35
|
+
selector,
|
|
36
|
+
declarations: (declarations as string).trim(),
|
|
37
|
+
specificity: specificity(selector),
|
|
38
|
+
order: order++,
|
|
39
|
+
})
|
|
40
|
+
else kept.push(`${selector}{${(declarations as string).trim()}}`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order)
|
|
44
|
+
|
|
45
|
+
const OWN = 'data-cslug-own-style'
|
|
46
|
+
let rewriter = new HTMLRewriter()
|
|
47
|
+
.on('style', {
|
|
48
|
+
element(el) {
|
|
49
|
+
el.remove()
|
|
50
|
+
},
|
|
51
|
+
})
|
|
52
|
+
.on('*', {
|
|
53
|
+
element(el) {
|
|
54
|
+
const style = el.getAttribute('style')
|
|
55
|
+
if (style === null) return
|
|
56
|
+
el.setAttribute(OWN, style)
|
|
57
|
+
el.removeAttribute('style')
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
// handlers run in registration order for an element: specificity, then source order
|
|
61
|
+
for (const rule of rules) {
|
|
62
|
+
try {
|
|
63
|
+
rewriter = rewriter.on(rule.selector, {
|
|
64
|
+
element(el) {
|
|
65
|
+
const before = el.getAttribute('style')
|
|
66
|
+
el.setAttribute('style', [before, rule.declarations.replace(/;\s*$/, '')].filter(Boolean).join('; '))
|
|
67
|
+
},
|
|
68
|
+
})
|
|
69
|
+
} catch {
|
|
70
|
+
kept.push(`${rule.selector}{${rule.declarations}}`) // a selector HTMLRewriter does not support
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
rewriter = rewriter.on('*', {
|
|
74
|
+
element(el) {
|
|
75
|
+
const own = el.getAttribute(OWN)
|
|
76
|
+
if (own === null) return
|
|
77
|
+
el.removeAttribute(OWN)
|
|
78
|
+
el.setAttribute('style', [el.getAttribute('style'), own].filter(Boolean).join('; '))
|
|
79
|
+
},
|
|
80
|
+
})
|
|
81
|
+
let out = rewriter.transform(html)
|
|
82
|
+
if (kept.length) {
|
|
83
|
+
const block = `<style>${kept.join('\n')}</style>`
|
|
84
|
+
out = /<\/head>/i.test(out) ? out.replace(/<\/head>/i, `${block}</head>`) : block + out
|
|
85
|
+
}
|
|
86
|
+
return out
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }
|
|
90
|
+
|
|
91
|
+
/** A readable plain-text version of an HTML email: blocks on their own lines, links as `text (url)`. */
|
|
92
|
+
export function htmlToText(html: string): string {
|
|
93
|
+
return (
|
|
94
|
+
html
|
|
95
|
+
.replace(/<(head|style|script|title)\b[\s\S]*?<\/\1>/gi, '')
|
|
96
|
+
// hidden elements (the preheader "preview" text) are not part of the text version
|
|
97
|
+
.replace(/<(\w+)\b[^>]*style="[^"]*display:\s*none[^"]*"[^>]*>[\s\S]*?<\/\1>/gi, '')
|
|
98
|
+
.replace(/<a\b[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_m, href: string, label: string) => {
|
|
99
|
+
const text = label.replace(/<[^>]+>/g, '').trim()
|
|
100
|
+
return !href || href === text || href.startsWith('#') ? text : `${text} (${href})`
|
|
101
|
+
})
|
|
102
|
+
.replace(/<br\s*\/?>/gi, '\n')
|
|
103
|
+
.replace(/<li\b[^>]*>/gi, '\n- ')
|
|
104
|
+
.replace(/<\/?(p|div|h[1-6]|tr|table|ul|ol|blockquote|section)\b[^>]*>/gi, '\n\n')
|
|
105
|
+
.replace(/<\/(td|th)>/gi, ' ')
|
|
106
|
+
.replace(/<[^>]+>/g, '')
|
|
107
|
+
.replace(/&(#\d+|#x[\da-f]+|\w+);/gi, (m, e: string) =>
|
|
108
|
+
e[0] === '#'
|
|
109
|
+
? String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? Number.parseInt(e.slice(2), 16) : Number(e.slice(1)))
|
|
110
|
+
: (ENTITIES[e.toLowerCase()] ?? m),
|
|
111
|
+
)
|
|
112
|
+
.replace(/[ \t]+/g, ' ')
|
|
113
|
+
.replace(/ *\n */g, '\n')
|
|
114
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
115
|
+
.trim()
|
|
116
|
+
)
|
|
117
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/mail: mailables rendered from Vue views (CSS inlined, text part derived), a `Mailer` that sends now or
|
|
3
|
+
* queues, and transports: SMTP (own client), Resend, Postmark, Brevo, log, array.
|
|
4
|
+
*/
|
|
5
|
+
export { installMailFake, MailFake, type SentMail } from './fake'
|
|
6
|
+
export { htmlToText, inlineCss } from './html'
|
|
7
|
+
export { Mailable, type MailableClass, type MailParts, PARTS } from './mailable'
|
|
8
|
+
export { type MailConfig, Mailer, type Outgoing, PendingMail, renderMail } from './mailer'
|
|
9
|
+
export {
|
|
10
|
+
type Address,
|
|
11
|
+
type AddressLike,
|
|
12
|
+
type Attachment,
|
|
13
|
+
address,
|
|
14
|
+
formatAddress,
|
|
15
|
+
type Message,
|
|
16
|
+
toMime,
|
|
17
|
+
} from './message'
|
|
18
|
+
export { MailPreviewCommand, MailProvider, previewableMailables } from './provider'
|
|
19
|
+
export { type SmtpConfig, SmtpError, sendSmtp } from './smtp'
|
|
20
|
+
export {
|
|
21
|
+
ArrayTransport,
|
|
22
|
+
BrevoTransport,
|
|
23
|
+
createTransport,
|
|
24
|
+
LogTransport,
|
|
25
|
+
PostmarkTransport,
|
|
26
|
+
ResendTransport,
|
|
27
|
+
SmtpTransport,
|
|
28
|
+
type Transport,
|
|
29
|
+
type TransportConfig,
|
|
30
|
+
} from './transports'
|
package/src/mailable.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { type Address, type AddressLike, type Attachment, address } from './message'
|
|
2
|
+
|
|
3
|
+
/** The key under which a mailable keeps what build() collected (a string, like Standard Schema's '~standard'). */
|
|
4
|
+
export const PARTS = '~mail'
|
|
5
|
+
|
|
6
|
+
/** What `build()` collected. */
|
|
7
|
+
export type MailParts = {
|
|
8
|
+
subject?: string
|
|
9
|
+
view?: { component: unknown; props: Record<string, unknown> }
|
|
10
|
+
html?: string
|
|
11
|
+
text?: string
|
|
12
|
+
attachments: (Omit<Attachment, 'content'> & { content: string | Uint8Array | PromiseLike<string | Uint8Array> })[]
|
|
13
|
+
tags: string[]
|
|
14
|
+
from?: Address
|
|
15
|
+
replyTo?: Address
|
|
16
|
+
headers: Record<string, string>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One email: a class whose `build()` sets the subject and the content (a Vue view, or HTML/text).
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* export class TodoDueMail extends Mailable {
|
|
24
|
+
* static queued = true // optional: sent by the worker
|
|
25
|
+
* constructor(private name: string, private items: DueItem[]) { super() }
|
|
26
|
+
* build() { return this.subject(t('mail.todo_due.subject')).view(TodoDue, { name: this.name, items: this.items }) }
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* `static queued` and `static preview()` are not declared here, so `noImplicitOverride` apps need no `override`.
|
|
31
|
+
*/
|
|
32
|
+
export abstract class Mailable {
|
|
33
|
+
readonly '~mail': MailParts = { attachments: [], tags: [], headers: {} }
|
|
34
|
+
|
|
35
|
+
/** Set the subject and content; runs in the recipient's locale (`t()` translates for them). */
|
|
36
|
+
abstract build(): this | Promise<this>
|
|
37
|
+
|
|
38
|
+
subject(subject: string): this {
|
|
39
|
+
this[PARTS].subject = subject
|
|
40
|
+
return this
|
|
41
|
+
}
|
|
42
|
+
/** A Vue SFC rendered to HTML (needs @cslug/vue); its `<style>` is inlined. */
|
|
43
|
+
view(component: unknown, props: Record<string, unknown> = {}): this {
|
|
44
|
+
this[PARTS].view = { component, props }
|
|
45
|
+
return this
|
|
46
|
+
}
|
|
47
|
+
html(html: string): this {
|
|
48
|
+
this[PARTS].html = html
|
|
49
|
+
return this
|
|
50
|
+
}
|
|
51
|
+
/** The plain-text part (default: derived from the HTML). */
|
|
52
|
+
text(text: string): this {
|
|
53
|
+
this[PARTS].text = text
|
|
54
|
+
return this
|
|
55
|
+
}
|
|
56
|
+
attach(
|
|
57
|
+
content: string | Uint8Array | PromiseLike<string | Uint8Array>,
|
|
58
|
+
options: { name: string; type?: string },
|
|
59
|
+
): this {
|
|
60
|
+
this[PARTS].attachments.push({ content, ...options })
|
|
61
|
+
return this
|
|
62
|
+
}
|
|
63
|
+
tag(tag: string): this {
|
|
64
|
+
this[PARTS].tags.push(tag)
|
|
65
|
+
return this
|
|
66
|
+
}
|
|
67
|
+
from(from: AddressLike): this {
|
|
68
|
+
this[PARTS].from = address(from)
|
|
69
|
+
return this
|
|
70
|
+
}
|
|
71
|
+
replyTo(to: AddressLike): this {
|
|
72
|
+
this[PARTS].replyTo = address(to)
|
|
73
|
+
return this
|
|
74
|
+
}
|
|
75
|
+
header(name: string, value: string): this {
|
|
76
|
+
this[PARTS].headers[name] = value
|
|
77
|
+
return this
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A mailable class, with its optional statics. */
|
|
82
|
+
export type MailableClass = (abstract new (
|
|
83
|
+
...args: never[]
|
|
84
|
+
) => Mailable) & {
|
|
85
|
+
readonly queued?: boolean
|
|
86
|
+
/** An example instance for `cslug mail:preview`. */
|
|
87
|
+
preview?(): Mailable | Promise<Mailable>
|
|
88
|
+
}
|
package/src/mailer.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { type Application, afterCommit, CslugError, currentLocale, type Logger, withLocale } from '@cslug/core'
|
|
2
|
+
import { htmlToText, inlineCss } from './html'
|
|
3
|
+
import { type Mailable, type MailableClass, PARTS } from './mailable'
|
|
4
|
+
import { type Address, type AddressLike, address, type Message } from './message'
|
|
5
|
+
import type { Transport } from './transports'
|
|
6
|
+
|
|
7
|
+
/** `config/mail.ts`. */
|
|
8
|
+
export type MailConfig = {
|
|
9
|
+
from?: { address: string; name?: string }
|
|
10
|
+
/** The transport to use (a key of `transports`). */
|
|
11
|
+
transport?: string
|
|
12
|
+
transports?: Record<string, Record<string, unknown>>
|
|
13
|
+
/** The queue for queued mail. Default `'default'`. */
|
|
14
|
+
queue?: string
|
|
15
|
+
/** Queue every mail unless its class says `static queued = false`. Default false. */
|
|
16
|
+
queued?: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Render a mailable for these recipients, in `locale`: build(), the Vue view, CSS inlined, text part. */
|
|
20
|
+
export async function renderMail(
|
|
21
|
+
mailable: Mailable,
|
|
22
|
+
recipients: { to: Address[]; cc?: Address[]; bcc?: Address[] },
|
|
23
|
+
options: { locale?: string; from?: Address } = {},
|
|
24
|
+
): Promise<Message> {
|
|
25
|
+
const render = async (): Promise<Message> => {
|
|
26
|
+
await mailable.build()
|
|
27
|
+
const parts = mailable[PARTS]
|
|
28
|
+
let html = parts.html
|
|
29
|
+
if (parts.view) {
|
|
30
|
+
const vue = await import('@cslug/vue').catch(() => {
|
|
31
|
+
throw new CslugError('mail.no_vue', '.view() needs @cslug/vue (VueProvider); use .html() otherwise')
|
|
32
|
+
})
|
|
33
|
+
html = await vue.renderStandalone(parts.view.component as never, parts.view.props)
|
|
34
|
+
}
|
|
35
|
+
if (html !== undefined) html = await inlineCss(html)
|
|
36
|
+
const from = parts.from ?? options.from
|
|
37
|
+
if (!from) throw new CslugError('mail.no_from', 'No sender: set config mail.from or call .from() in build()')
|
|
38
|
+
if (!parts.subject) throw new CslugError('mail.no_subject', `${mailable.constructor.name}.build() sets no subject`)
|
|
39
|
+
return {
|
|
40
|
+
from,
|
|
41
|
+
to: recipients.to,
|
|
42
|
+
cc: recipients.cc ?? [],
|
|
43
|
+
bcc: recipients.bcc ?? [],
|
|
44
|
+
replyTo: parts.replyTo,
|
|
45
|
+
subject: parts.subject,
|
|
46
|
+
html,
|
|
47
|
+
text: parts.text ?? (html !== undefined ? htmlToText(html) : undefined),
|
|
48
|
+
attachments: await Promise.all(parts.attachments.map(async (a) => ({ ...a, content: await a.content }))),
|
|
49
|
+
tags: parts.tags,
|
|
50
|
+
headers: parts.headers,
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return options.locale ? withLocale(options.locale, render) : render()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** What `Mailer` hands over for delivery (the fake records it). */
|
|
57
|
+
export type Outgoing = { mailable: Mailable; message: Message; locale: string; queued: boolean }
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Sends mail: `mailer.to(traveller).locale(traveller.locale).send(new BookingConfirmedMail(booking))`.
|
|
61
|
+
* Queued mail (`static queued = true`, or `mail.queued`) is rendered now and sent by a worker; inside a transaction
|
|
62
|
+
* it waits for COMMIT. Without @cslug/queue it is sent after COMMIT in this process.
|
|
63
|
+
*/
|
|
64
|
+
export class Mailer {
|
|
65
|
+
/** Set by `MailProvider` when @cslug/queue is installed: puts a rendered message on the queue. */
|
|
66
|
+
enqueue?: (message: Message, queue: string) => Promise<unknown>
|
|
67
|
+
|
|
68
|
+
constructor(
|
|
69
|
+
protected readonly app: Application,
|
|
70
|
+
protected readonly config: MailConfig,
|
|
71
|
+
readonly transport: Transport,
|
|
72
|
+
protected readonly log: Logger,
|
|
73
|
+
) {}
|
|
74
|
+
|
|
75
|
+
to(...recipients: (AddressLike | AddressLike[])[]): PendingMail {
|
|
76
|
+
return new PendingMail(this, recipients.flat().map(address))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Render and deliver (used by `PendingMail.send`). */
|
|
80
|
+
async dispatch(
|
|
81
|
+
mailable: Mailable,
|
|
82
|
+
to: Address[],
|
|
83
|
+
options: { cc?: Address[]; bcc?: Address[]; locale?: string; now?: boolean } = {},
|
|
84
|
+
) {
|
|
85
|
+
if (!to.length)
|
|
86
|
+
throw new CslugError('mail.no_recipient', `${mailable.constructor.name}: no recipient (mailer.to(…))`)
|
|
87
|
+
const locale = options.locale ?? currentLocale()
|
|
88
|
+
const from = this.config.from ? address(this.config.from) : undefined
|
|
89
|
+
const message = await renderMail(mailable, { to, cc: options.cc, bcc: options.bcc }, { locale, from })
|
|
90
|
+
const cls = mailable.constructor as MailableClass
|
|
91
|
+
const queued = !options.now && (cls.queued ?? this.config.queued ?? false)
|
|
92
|
+
await this.deliver({ mailable, message, locale, queued })
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Hand a rendered message over: queue it, or send it with the transport. */
|
|
96
|
+
protected async deliver({ message, queued }: Outgoing): Promise<void> {
|
|
97
|
+
if (!queued) {
|
|
98
|
+
await this.send(message)
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
if (this.enqueue) await this.enqueue(message, this.config.queue ?? 'default')
|
|
102
|
+
else
|
|
103
|
+
afterCommit(() =>
|
|
104
|
+
this.send(message).catch((error) => this.log.error('mail.failed', { error, subject: message.subject })),
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Send a rendered message now. */
|
|
109
|
+
async send(message: Message): Promise<{ id: string }> {
|
|
110
|
+
const result = await this.transport.send(message)
|
|
111
|
+
this.log.info('mail.sent', { id: result.id, to: message.to.map((a) => a.address), subject: message.subject })
|
|
112
|
+
return result
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** `mailer.to(…)`: add recipients, a locale, then `send()`. */
|
|
117
|
+
export class PendingMail {
|
|
118
|
+
private copies: Address[] = []
|
|
119
|
+
private blind: Address[] = []
|
|
120
|
+
private lang?: string
|
|
121
|
+
|
|
122
|
+
constructor(
|
|
123
|
+
private readonly mailer: Mailer,
|
|
124
|
+
private readonly recipients: Address[],
|
|
125
|
+
) {}
|
|
126
|
+
|
|
127
|
+
cc(...addresses: AddressLike[]): this {
|
|
128
|
+
this.copies.push(...addresses.map(address))
|
|
129
|
+
return this
|
|
130
|
+
}
|
|
131
|
+
bcc(...addresses: AddressLike[]): this {
|
|
132
|
+
this.blind.push(...addresses.map(address))
|
|
133
|
+
return this
|
|
134
|
+
}
|
|
135
|
+
/** Render in this locale (default: the current one). */
|
|
136
|
+
locale(locale: string | null | undefined): this {
|
|
137
|
+
if (locale) this.lang = locale
|
|
138
|
+
return this
|
|
139
|
+
}
|
|
140
|
+
/** Send (or queue, for queued mailables). */
|
|
141
|
+
send(mailable: Mailable): Promise<void> {
|
|
142
|
+
return this.mailer.dispatch(mailable, this.recipients, { cc: this.copies, bcc: this.blind, locale: this.lang })
|
|
143
|
+
}
|
|
144
|
+
/** Send now, even if the mailable is queued. */
|
|
145
|
+
sendNow(mailable: Mailable): Promise<void> {
|
|
146
|
+
return this.mailer.dispatch(mailable, this.recipients, {
|
|
147
|
+
cc: this.copies,
|
|
148
|
+
bcc: this.blind,
|
|
149
|
+
locale: this.lang,
|
|
150
|
+
now: true,
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
}
|
package/src/message.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** `'ada@example.test'`, `{ email, name }`, `{ address, name }`, or any row with `email` (and `name`). */
|
|
4
|
+
export type AddressLike = string | { email: string; name?: string | null } | { address: string; name?: string | null }
|
|
5
|
+
export type Address = { address: string; name?: string }
|
|
6
|
+
|
|
7
|
+
export type Attachment = { name: string; content: string | Uint8Array; type?: string }
|
|
8
|
+
|
|
9
|
+
/** A rendered email, ready for a transport (and serializable for the queue, attachments aside). */
|
|
10
|
+
export type Message = {
|
|
11
|
+
from: Address
|
|
12
|
+
to: Address[]
|
|
13
|
+
cc: Address[]
|
|
14
|
+
bcc: Address[]
|
|
15
|
+
replyTo?: Address
|
|
16
|
+
subject: string
|
|
17
|
+
html?: string
|
|
18
|
+
text?: string
|
|
19
|
+
attachments: Attachment[]
|
|
20
|
+
tags: string[]
|
|
21
|
+
headers: Record<string, string>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Normalise `'a@b.c'`, `{ email, name }` or `{ address, name }`; throws `mail.bad_address`. */
|
|
25
|
+
export function address(value: AddressLike): Address {
|
|
26
|
+
const a =
|
|
27
|
+
typeof value === 'string'
|
|
28
|
+
? { address: value }
|
|
29
|
+
: 'email' in value
|
|
30
|
+
? { address: value.email, name: value.name ?? undefined }
|
|
31
|
+
: { address: value.address, name: value.name ?? undefined }
|
|
32
|
+
if (!/^[^\s@<>]+@[^\s@<>]+$/.test(a.address))
|
|
33
|
+
throw new CslugError('mail.bad_address', `"${a.address}" is not an email address`)
|
|
34
|
+
return a.name ? a : { address: a.address }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** RFC 2047 for non-ASCII header text. */
|
|
38
|
+
const encodeWord = (text: string) =>
|
|
39
|
+
/^[\x20-\x7e]*$/.test(text) ? text : `=?UTF-8?B?${Buffer.from(text).toString('base64')}?=`
|
|
40
|
+
|
|
41
|
+
/** `"Ada" <ada@example.com>` for a header, encoding a non-ASCII name. */
|
|
42
|
+
export const formatAddress = (a: Address) =>
|
|
43
|
+
a.name ? `${/^[\w .-]*$/.test(a.name) ? `"${a.name}"` : encodeWord(a.name)} <${a.address}>` : a.address
|
|
44
|
+
|
|
45
|
+
const base64Lines = (data: string | Uint8Array) =>
|
|
46
|
+
(
|
|
47
|
+
Buffer.from(data)
|
|
48
|
+
.toString('base64')
|
|
49
|
+
.match(/.{1,76}/g) ?? []
|
|
50
|
+
).join('\r\n')
|
|
51
|
+
|
|
52
|
+
/** The full MIME message (headers + body, CRLF): multipart/alternative (text + html), mixed with attachments. */
|
|
53
|
+
export function toMime(message: Message, options: { messageId: string; date?: Date }): string {
|
|
54
|
+
const boundary = (kind: string) => `=_cslug_${kind}_${options.messageId.replace(/\W/g, '').slice(0, 16)}`
|
|
55
|
+
const headers = [
|
|
56
|
+
`From: ${formatAddress(message.from)}`,
|
|
57
|
+
`To: ${message.to.map(formatAddress).join(', ')}`,
|
|
58
|
+
...(message.cc.length ? [`Cc: ${message.cc.map(formatAddress).join(', ')}`] : []),
|
|
59
|
+
...(message.replyTo ? [`Reply-To: ${formatAddress(message.replyTo)}`] : []),
|
|
60
|
+
`Subject: ${encodeWord(message.subject)}`,
|
|
61
|
+
`Date: ${(options.date ?? new Date()).toUTCString()}`,
|
|
62
|
+
`Message-ID: <${options.messageId}>`,
|
|
63
|
+
'MIME-Version: 1.0',
|
|
64
|
+
...Object.entries(message.headers).map(([k, v]) => `${k}: ${encodeWord(v)}`),
|
|
65
|
+
]
|
|
66
|
+
const part = (type: string, body: string | Uint8Array, extra: string[] = []) =>
|
|
67
|
+
[`Content-Type: ${type}`, 'Content-Transfer-Encoding: base64', ...extra, '', base64Lines(body)].join('\r\n')
|
|
68
|
+
const multipart = (kind: string, parts: string[]) => {
|
|
69
|
+
const b = boundary(kind)
|
|
70
|
+
return [
|
|
71
|
+
`Content-Type: multipart/${kind}; boundary="${b}"`,
|
|
72
|
+
'',
|
|
73
|
+
...parts.map((p) => `--${b}\r\n${p}`),
|
|
74
|
+
`--${b}--`,
|
|
75
|
+
].join('\r\n')
|
|
76
|
+
}
|
|
77
|
+
const bodies = [
|
|
78
|
+
...(message.text !== undefined ? [part('text/plain; charset=utf-8', message.text)] : []),
|
|
79
|
+
...(message.html !== undefined ? [part('text/html; charset=utf-8', message.html)] : []),
|
|
80
|
+
]
|
|
81
|
+
let body = bodies.length === 1 ? (bodies[0] as string) : multipart('alternative', bodies)
|
|
82
|
+
if (message.attachments.length) {
|
|
83
|
+
body = multipart('mixed', [
|
|
84
|
+
body,
|
|
85
|
+
...message.attachments.map((a) =>
|
|
86
|
+
part(`${a.type ?? 'application/octet-stream'}; name="${a.name}"`, a.content, [
|
|
87
|
+
`Content-Disposition: attachment; filename="${a.name}"`,
|
|
88
|
+
]),
|
|
89
|
+
),
|
|
90
|
+
])
|
|
91
|
+
}
|
|
92
|
+
return `${headers.join('\r\n')}\r\n${body}\r\n`
|
|
93
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { type Application, Command, flag, Logger, resolve, ServiceProvider } from '@cslug/core'
|
|
4
|
+
import { Mailable, type MailableClass } from './mailable'
|
|
5
|
+
import { type MailConfig, Mailer, renderMail } from './mailer'
|
|
6
|
+
import { address, type Message } from './message'
|
|
7
|
+
import { createTransport } from './transports'
|
|
8
|
+
|
|
9
|
+
/** A message as queued: attachments as base64 (the queue payload is JSON). */
|
|
10
|
+
type QueuedMessage = Omit<Message, 'attachments'> & { attachments: { name: string; type?: string; base64: string }[] }
|
|
11
|
+
|
|
12
|
+
const toQueued = (m: Message): QueuedMessage => ({
|
|
13
|
+
...m,
|
|
14
|
+
attachments: m.attachments.map((a) => ({
|
|
15
|
+
name: a.name,
|
|
16
|
+
type: a.type,
|
|
17
|
+
base64: Buffer.from(a.content).toString('base64'),
|
|
18
|
+
})),
|
|
19
|
+
})
|
|
20
|
+
const fromQueued = (m: QueuedMessage): Message => ({
|
|
21
|
+
...m,
|
|
22
|
+
attachments: m.attachments.map((a) => ({
|
|
23
|
+
name: a.name,
|
|
24
|
+
type: a.type,
|
|
25
|
+
content: new Uint8Array(Buffer.from(a.base64, 'base64')),
|
|
26
|
+
})),
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
type QueueModule = typeof import('@cslug/queue')
|
|
30
|
+
let mailJob: { cls: unknown } | undefined
|
|
31
|
+
|
|
32
|
+
/** The job (`cslug.mail`) that sends a queued, already rendered message; defined once, when the queue is installed. */
|
|
33
|
+
function sendMailJob(q: QueueModule) {
|
|
34
|
+
if (!mailJob) {
|
|
35
|
+
class SendMailJob extends q.Job<QueuedMessage> {
|
|
36
|
+
static jobName = 'cslug.mail'
|
|
37
|
+
static tries = 5
|
|
38
|
+
static backoff = q.Job.exponential('30s', { max: '30m', jitter: true })
|
|
39
|
+
async handle(message: QueuedMessage) {
|
|
40
|
+
await resolve(Mailer).send(fromQueued(message))
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
q.registerJob(SendMailJob)
|
|
44
|
+
mailJob = { cls: SendMailJob }
|
|
45
|
+
}
|
|
46
|
+
return mailJob.cls as Parameters<InstanceType<QueueModule['Queue']>['dispatch']>[0]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Binds `Mailer` with the transport `mail.transport` (`smtp`, `resend`, `postmark`, `brevo`, `log`, `array`).
|
|
51
|
+
* With @cslug/queue installed, queued mail goes through the job `cslug.mail` on `mail.queue`.
|
|
52
|
+
*/
|
|
53
|
+
export class MailProvider extends ServiceProvider {
|
|
54
|
+
register() {
|
|
55
|
+
this.commands([MailPreviewCommand])
|
|
56
|
+
this.app.singleton(Mailer, (c) => {
|
|
57
|
+
const config = this.app.config<MailConfig | undefined>('mail') ?? {}
|
|
58
|
+
const name = config.transport ?? 'log'
|
|
59
|
+
const transport = createTransport(name, config.transports?.[name] ?? {}, c.resolve(Logger))
|
|
60
|
+
return new Mailer(this.app, config, transport, c.resolve(Logger))
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async boot() {
|
|
65
|
+
try {
|
|
66
|
+
const q = await import('@cslug/queue')
|
|
67
|
+
if (!this.app.has(q.Queue)) return
|
|
68
|
+
const job = sendMailJob(q)
|
|
69
|
+
this.app.resolve(Mailer).enqueue = async (message, queue) => {
|
|
70
|
+
await this.app
|
|
71
|
+
.resolve(q.Queue)
|
|
72
|
+
.dispatch(job, toQueued(message) as never)
|
|
73
|
+
.onQueue(queue)
|
|
74
|
+
}
|
|
75
|
+
} catch {
|
|
76
|
+
// no @cslug/queue: queued mail is sent after COMMIT in this process
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Mailables in `app/mail/` with a `static preview()`. */
|
|
82
|
+
export async function previewableMailables(app: Application): Promise<MailableClass[]> {
|
|
83
|
+
const dir = join(app.rootDir, 'app/mail')
|
|
84
|
+
if (!existsSync(dir)) return []
|
|
85
|
+
const found: MailableClass[] = []
|
|
86
|
+
for (const file of (readdirSync(dir, { recursive: true }) as string[]).filter((f) => f.endsWith('.ts')).sort()) {
|
|
87
|
+
for (const value of Object.values(await import(join(dir, file)))) {
|
|
88
|
+
const cls = value as MailableClass
|
|
89
|
+
if (typeof cls === 'function' && cls.prototype instanceof Mailable && typeof cls.preview === 'function')
|
|
90
|
+
found.push(cls)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return found
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** `cslug mail:preview`: every mailable with a `static preview()`, in each locale, in the browser. */
|
|
97
|
+
export class MailPreviewCommand extends Command {
|
|
98
|
+
static signature = 'mail:preview'
|
|
99
|
+
static description = 'Preview mailables (static preview()) in the browser, in each locale'
|
|
100
|
+
static longRunning = true
|
|
101
|
+
static args = { port: flag.number().default(3100) }
|
|
102
|
+
|
|
103
|
+
async handle({ port }: Command.Args<typeof MailPreviewCommand>) {
|
|
104
|
+
const app = this.app
|
|
105
|
+
const mailables = await previewableMailables(app)
|
|
106
|
+
const locales = app.config<string[] | undefined>('i18n.locales') ?? ['en']
|
|
107
|
+
const from = address(app.config<{ address: string }>('mail.from') ?? 'preview@example.test')
|
|
108
|
+
const page = (body: string) =>
|
|
109
|
+
new Response(`<!doctype html><meta charset="utf-8">${body}`, {
|
|
110
|
+
headers: { 'content-type': 'text/html; charset=utf-8' },
|
|
111
|
+
})
|
|
112
|
+
const server = Bun.serve({
|
|
113
|
+
port,
|
|
114
|
+
fetch: async (req) => {
|
|
115
|
+
const url = new URL(req.url)
|
|
116
|
+
const [, name, locale, part] = url.pathname.split('/')
|
|
117
|
+
const cls = mailables.find((m) => m.name === name)
|
|
118
|
+
if (!cls || !locale) {
|
|
119
|
+
const links = mailables.flatMap((m) =>
|
|
120
|
+
locales.map(
|
|
121
|
+
(l) =>
|
|
122
|
+
`<li><a href="/${m.name}/${l}">${m.name} (${l})</a> · <a href="/${m.name}/${l}/text">text</a></li>`,
|
|
123
|
+
),
|
|
124
|
+
)
|
|
125
|
+
return page(
|
|
126
|
+
`<h1>Mail previews</h1><ul>${links.join('') || '<li>No mailable in app/mail/ has a static preview()</li>'}</ul>`,
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
const message = await renderMail(
|
|
130
|
+
await (cls.preview as () => Promise<Mailable>)(),
|
|
131
|
+
{ to: [address('preview@example.test')] },
|
|
132
|
+
{ locale, from },
|
|
133
|
+
)
|
|
134
|
+
if (part === 'text')
|
|
135
|
+
return new Response(message.text ?? '', { headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
136
|
+
return page(`<p><b>${message.subject}</b></p>${message.html ?? `<pre>${message.text ?? ''}</pre>`}`)
|
|
137
|
+
},
|
|
138
|
+
})
|
|
139
|
+
this.info(`Mail previews: http://localhost:${server.port}/ (${mailables.length} mailables, ${locales.join(', ')})`)
|
|
140
|
+
}
|
|
141
|
+
}
|
package/src/smtp.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { CslugError } from '@cslug/core'
|
|
2
|
+
import type { Socket } from 'bun'
|
|
3
|
+
|
|
4
|
+
export type SmtpConfig = {
|
|
5
|
+
host: string
|
|
6
|
+
port?: number
|
|
7
|
+
user?: string
|
|
8
|
+
password?: string
|
|
9
|
+
/** `true`: TLS from the start (port 465). Otherwise STARTTLS is used when the server offers it. */
|
|
10
|
+
secure?: boolean
|
|
11
|
+
/** `false`: refuse to send when STARTTLS is not offered (default: send in clear only to localhost). */
|
|
12
|
+
allowPlain?: boolean
|
|
13
|
+
/** Name sent in EHLO. Default: `localhost`. */
|
|
14
|
+
helo?: string
|
|
15
|
+
timeout?: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class SmtpError extends CslugError {
|
|
19
|
+
constructor(
|
|
20
|
+
message: string,
|
|
21
|
+
readonly reply?: string,
|
|
22
|
+
) {
|
|
23
|
+
super('mail.smtp', message)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type Reply = { code: number; text: string }
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A minimal SMTP client on `Bun.connect`: EHLO, STARTTLS (`socket.upgradeTLS`) or implicit TLS, AUTH PLAIN /
|
|
31
|
+
* LOGIN, MAIL FROM, RCPT TO, DATA (dot-stuffed), QUIT. One connection per message.
|
|
32
|
+
*/
|
|
33
|
+
export async function sendSmtp(
|
|
34
|
+
config: SmtpConfig,
|
|
35
|
+
envelope: { from: string; to: string[] },
|
|
36
|
+
mime: string,
|
|
37
|
+
): Promise<string> {
|
|
38
|
+
let buffer = ''
|
|
39
|
+
let waiting: ((r: Reply) => void) | undefined
|
|
40
|
+
let failed: ((e: Error) => void) | undefined
|
|
41
|
+
const replies: Reply[] = []
|
|
42
|
+
const onData = (_s: Socket, data: Buffer) => {
|
|
43
|
+
buffer += data.toString('utf8')
|
|
44
|
+
// a complete reply ends with a line "NNN text" (not "NNN-text")
|
|
45
|
+
const m = /(?:^|\r\n)(\d{3}) [^\r\n]*\r\n$/.exec(buffer)
|
|
46
|
+
if (!m) return
|
|
47
|
+
const reply = { code: Number(m[1]), text: buffer.trim() }
|
|
48
|
+
buffer = ''
|
|
49
|
+
if (waiting) {
|
|
50
|
+
const w = waiting
|
|
51
|
+
waiting = undefined
|
|
52
|
+
w(reply)
|
|
53
|
+
} else replies.push(reply)
|
|
54
|
+
}
|
|
55
|
+
const handlers = {
|
|
56
|
+
data: onData,
|
|
57
|
+
error: (_s: Socket, e: Error) => failed?.(e),
|
|
58
|
+
close: () => failed?.(new SmtpError('The SMTP server closed the connection')),
|
|
59
|
+
}
|
|
60
|
+
let socket: Socket = await Bun.connect({
|
|
61
|
+
hostname: config.host,
|
|
62
|
+
port: config.port ?? (config.secure ? 465 : 587),
|
|
63
|
+
tls: config.secure ? { serverName: config.host } : undefined,
|
|
64
|
+
socket: handlers,
|
|
65
|
+
})
|
|
66
|
+
const timeout = config.timeout ?? 30_000
|
|
67
|
+
const read = () =>
|
|
68
|
+
new Promise<Reply>((resolve, reject) => {
|
|
69
|
+
const queued = replies.shift()
|
|
70
|
+
if (queued) return resolve(queued)
|
|
71
|
+
const timer = setTimeout(() => reject(new SmtpError('The SMTP server did not answer in time')), timeout)
|
|
72
|
+
waiting = (r) => {
|
|
73
|
+
clearTimeout(timer)
|
|
74
|
+
resolve(r)
|
|
75
|
+
}
|
|
76
|
+
failed = (e) => {
|
|
77
|
+
clearTimeout(timer)
|
|
78
|
+
reject(e)
|
|
79
|
+
}
|
|
80
|
+
})
|
|
81
|
+
const command = async (line: string, expect: number[], shown = line) => {
|
|
82
|
+
socket.write(`${line}\r\n`)
|
|
83
|
+
const reply = await read()
|
|
84
|
+
if (!expect.includes(reply.code))
|
|
85
|
+
throw new SmtpError(`SMTP ${shown.split(' ')[0]} failed: ${reply.text}`, reply.text)
|
|
86
|
+
return reply
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const greeting = await read()
|
|
91
|
+
if (greeting.code !== 220) throw new SmtpError(`SMTP greeting: ${greeting.text}`, greeting.text)
|
|
92
|
+
const helo = config.helo ?? 'localhost'
|
|
93
|
+
let ehlo = await command(`EHLO ${helo}`, [250])
|
|
94
|
+
if (!config.secure) {
|
|
95
|
+
if (/STARTTLS/i.test(ehlo.text)) {
|
|
96
|
+
await command('STARTTLS', [220])
|
|
97
|
+
const [, tls] = socket.upgradeTLS({ tls: { serverName: config.host }, socket: handlers })
|
|
98
|
+
socket = tls
|
|
99
|
+
ehlo = await command(`EHLO ${helo}`, [250])
|
|
100
|
+
} else if (config.allowPlain === false || (config.allowPlain === undefined && !isLocal(config.host))) {
|
|
101
|
+
throw new SmtpError(`${config.host} does not offer STARTTLS; set allowPlain: true to send in clear`)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (config.user) {
|
|
105
|
+
if (/AUTH[^\r\n]*\bPLAIN\b/i.test(ehlo.text)) {
|
|
106
|
+
const token = Buffer.from(`\0${config.user}\0${config.password ?? ''}`).toString('base64')
|
|
107
|
+
await command(`AUTH PLAIN ${token}`, [235], 'AUTH PLAIN')
|
|
108
|
+
} else {
|
|
109
|
+
await command('AUTH LOGIN', [334])
|
|
110
|
+
await command(Buffer.from(config.user).toString('base64'), [334], 'AUTH user')
|
|
111
|
+
await command(Buffer.from(config.password ?? '').toString('base64'), [235], 'AUTH password')
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
await command(`MAIL FROM:<${envelope.from}>`, [250])
|
|
115
|
+
for (const to of envelope.to) await command(`RCPT TO:<${to}>`, [250, 251])
|
|
116
|
+
await command('DATA', [354])
|
|
117
|
+
const body = mime.replace(/\r?\n/g, '\r\n').replace(/^\./gm, '..')
|
|
118
|
+
const done = await command(`${body.replace(/\r\n$/, '')}\r\n.`, [250], 'DATA body')
|
|
119
|
+
await command('QUIT', [221]).catch(() => undefined)
|
|
120
|
+
return done.text
|
|
121
|
+
} finally {
|
|
122
|
+
failed = undefined
|
|
123
|
+
socket.end()
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const isLocal = (host: string) => ['localhost', '127.0.0.1', '::1'].includes(host) || host.endsWith('.local')
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { CslugError, type Logger } from '@cslug/core'
|
|
2
|
+
import { type Message, toMime } from './message'
|
|
3
|
+
import { type SmtpConfig, sendSmtp } from './smtp'
|
|
4
|
+
|
|
5
|
+
/** Sends a rendered message. */
|
|
6
|
+
export interface Transport {
|
|
7
|
+
send(message: Message): Promise<{ id: string }>
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const messageId = (from: string) => `${Bun.randomUUIDv7()}@${from.split('@')[1] ?? 'localhost'}`
|
|
11
|
+
const recipients = (m: Message) => [...m.to, ...m.cc, ...m.bcc].map((a) => a.address)
|
|
12
|
+
|
|
13
|
+
/** Any SMTP server (Mailpit, SES, a relay), through the built-in client. */
|
|
14
|
+
export class SmtpTransport implements Transport {
|
|
15
|
+
constructor(private readonly config: SmtpConfig) {}
|
|
16
|
+
async send(message: Message) {
|
|
17
|
+
const id = messageId(message.from.address)
|
|
18
|
+
await sendSmtp(
|
|
19
|
+
this.config,
|
|
20
|
+
{ from: message.from.address, to: recipients(message) },
|
|
21
|
+
toMime(message, { messageId: id }),
|
|
22
|
+
)
|
|
23
|
+
return { id }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Writes each message to the log (development). */
|
|
28
|
+
export class LogTransport implements Transport {
|
|
29
|
+
constructor(private readonly log: Logger) {}
|
|
30
|
+
async send(message: Message) {
|
|
31
|
+
const id = messageId(message.from.address)
|
|
32
|
+
this.log.info('mail.logged', { id, to: recipients(message), subject: message.subject, text: message.text })
|
|
33
|
+
return { id }
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Keeps messages in memory (`transport.messages`). */
|
|
38
|
+
export class ArrayTransport implements Transport {
|
|
39
|
+
readonly messages: Message[] = []
|
|
40
|
+
async send(message: Message) {
|
|
41
|
+
this.messages.push(message)
|
|
42
|
+
return { id: messageId(message.from.address) }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
type ApiConfig = { apiKey: string; endpoint?: string }
|
|
47
|
+
const b64 = (content: string | Uint8Array) => Buffer.from(content).toString('base64')
|
|
48
|
+
const named = (a: { address: string; name?: string }) => (a.name ? `${a.name} <${a.address}>` : a.address)
|
|
49
|
+
|
|
50
|
+
async function post(
|
|
51
|
+
url: string,
|
|
52
|
+
headers: Record<string, string>,
|
|
53
|
+
body: unknown,
|
|
54
|
+
pick: (r: Record<string, unknown>) => unknown,
|
|
55
|
+
) {
|
|
56
|
+
const res = await fetch(url, {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
59
|
+
body: JSON.stringify(body),
|
|
60
|
+
})
|
|
61
|
+
const text = await res.text()
|
|
62
|
+
if (!res.ok)
|
|
63
|
+
throw new CslugError('mail.transport', `${new URL(url).host} answered ${res.status}: ${text.slice(0, 300)}`)
|
|
64
|
+
const id = text ? pick(JSON.parse(text) as Record<string, unknown>) : undefined
|
|
65
|
+
return { id: String(id ?? '') }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Resend (`POST /emails`). */
|
|
69
|
+
export class ResendTransport implements Transport {
|
|
70
|
+
constructor(private readonly config: ApiConfig) {}
|
|
71
|
+
send(m: Message) {
|
|
72
|
+
return post(
|
|
73
|
+
`${this.config.endpoint ?? 'https://api.resend.com'}/emails`,
|
|
74
|
+
{ authorization: `Bearer ${this.config.apiKey}` },
|
|
75
|
+
{
|
|
76
|
+
from: named(m.from),
|
|
77
|
+
to: m.to.map(named),
|
|
78
|
+
cc: m.cc.map(named),
|
|
79
|
+
bcc: m.bcc.map(named),
|
|
80
|
+
reply_to: m.replyTo ? named(m.replyTo) : undefined,
|
|
81
|
+
subject: m.subject,
|
|
82
|
+
html: m.html,
|
|
83
|
+
text: m.text,
|
|
84
|
+
headers: m.headers,
|
|
85
|
+
tags: m.tags.map((t) => ({ name: 'tag', value: t })),
|
|
86
|
+
attachments: m.attachments.map((a) => ({ filename: a.name, content: b64(a.content) })),
|
|
87
|
+
},
|
|
88
|
+
(r) => r.id,
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Postmark (`POST /email`). */
|
|
94
|
+
export class PostmarkTransport implements Transport {
|
|
95
|
+
constructor(private readonly config: ApiConfig) {}
|
|
96
|
+
send(m: Message) {
|
|
97
|
+
return post(
|
|
98
|
+
`${this.config.endpoint ?? 'https://api.postmarkapp.com'}/email`,
|
|
99
|
+
{ 'x-postmark-server-token': this.config.apiKey, accept: 'application/json' },
|
|
100
|
+
{
|
|
101
|
+
From: named(m.from),
|
|
102
|
+
To: m.to.map(named).join(','),
|
|
103
|
+
Cc: m.cc.map(named).join(',') || undefined,
|
|
104
|
+
Bcc: m.bcc.map(named).join(',') || undefined,
|
|
105
|
+
ReplyTo: m.replyTo ? named(m.replyTo) : undefined,
|
|
106
|
+
Subject: m.subject,
|
|
107
|
+
HtmlBody: m.html,
|
|
108
|
+
TextBody: m.text,
|
|
109
|
+
Tag: m.tags[0],
|
|
110
|
+
Headers: Object.entries(m.headers).map(([Name, Value]) => ({ Name, Value })),
|
|
111
|
+
Attachments: m.attachments.map((a) => ({
|
|
112
|
+
Name: a.name,
|
|
113
|
+
Content: b64(a.content),
|
|
114
|
+
ContentType: a.type ?? 'application/octet-stream',
|
|
115
|
+
})),
|
|
116
|
+
},
|
|
117
|
+
(r) => r.MessageID,
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Brevo (`POST /v3/smtp/email`). */
|
|
123
|
+
export class BrevoTransport implements Transport {
|
|
124
|
+
constructor(private readonly config: ApiConfig) {}
|
|
125
|
+
send(m: Message) {
|
|
126
|
+
const person = (a: { address: string; name?: string }) => ({
|
|
127
|
+
email: a.address,
|
|
128
|
+
...(a.name ? { name: a.name } : {}),
|
|
129
|
+
})
|
|
130
|
+
return post(
|
|
131
|
+
`${this.config.endpoint ?? 'https://api.brevo.com'}/v3/smtp/email`,
|
|
132
|
+
{ 'api-key': this.config.apiKey, accept: 'application/json' },
|
|
133
|
+
{
|
|
134
|
+
sender: person(m.from),
|
|
135
|
+
to: m.to.map(person),
|
|
136
|
+
cc: m.cc.length ? m.cc.map(person) : undefined,
|
|
137
|
+
bcc: m.bcc.length ? m.bcc.map(person) : undefined,
|
|
138
|
+
replyTo: m.replyTo ? person(m.replyTo) : undefined,
|
|
139
|
+
subject: m.subject,
|
|
140
|
+
htmlContent: m.html,
|
|
141
|
+
textContent: m.text,
|
|
142
|
+
headers: Object.keys(m.headers).length ? m.headers : undefined,
|
|
143
|
+
tags: m.tags.length ? m.tags : undefined,
|
|
144
|
+
attachment: m.attachments.length
|
|
145
|
+
? m.attachments.map((a) => ({ name: a.name, content: b64(a.content) }))
|
|
146
|
+
: undefined,
|
|
147
|
+
},
|
|
148
|
+
(r) => r.messageId,
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** `config/mail.ts` → `transports.<name>`: the driver is the name unless `driver` says otherwise. */
|
|
154
|
+
export type TransportConfig = { driver?: string } & Record<string, unknown>
|
|
155
|
+
|
|
156
|
+
/** The transport for `config/mail.ts` → `transports.<name>`. */
|
|
157
|
+
export function createTransport(name: string, config: TransportConfig, log: Logger): Transport {
|
|
158
|
+
switch (config.driver ?? name) {
|
|
159
|
+
case 'smtp':
|
|
160
|
+
return new SmtpTransport(config as unknown as SmtpConfig)
|
|
161
|
+
case 'resend':
|
|
162
|
+
return new ResendTransport(config as unknown as ApiConfig)
|
|
163
|
+
case 'postmark':
|
|
164
|
+
return new PostmarkTransport(config as unknown as ApiConfig)
|
|
165
|
+
case 'brevo':
|
|
166
|
+
return new BrevoTransport(config as unknown as ApiConfig)
|
|
167
|
+
case 'log':
|
|
168
|
+
return new LogTransport(log)
|
|
169
|
+
case 'array':
|
|
170
|
+
return new ArrayTransport()
|
|
171
|
+
default:
|
|
172
|
+
throw new CslugError(
|
|
173
|
+
'mail.unknown_transport',
|
|
174
|
+
`Unknown mail transport "${config.driver ?? name}" (smtp, resend, postmark, brevo, log, array)`,
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
}
|