@tylix/mail 1.2.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/Mailable.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
+
// A reusable message. build() returns the message without `to`:
|
|
2
|
+
// { subject, view?, data?, html?, text?, attachments?, cc?, ... }
|
|
3
|
+
//
|
|
4
|
+
// await new WelcomeMail(user).send(user.email, config.mail)
|
|
5
|
+
// await mailer.send(new WelcomeMail(user), user.email) // standalone
|
|
1
6
|
export class Mailable {
|
|
2
7
|
build() {
|
|
3
8
|
throw new Error('Mailable subclasses must implement build()')
|
|
4
9
|
}
|
|
5
10
|
|
|
6
11
|
async send(to, config) {
|
|
7
|
-
const { subject, view, data } = this.build()
|
|
8
12
|
const { Mail } = await import('./Mailer.js')
|
|
9
|
-
return Mail.send({
|
|
13
|
+
return Mail.send({ ...(await this.build()), to }, config)
|
|
10
14
|
}
|
|
11
15
|
}
|
package/Mailer.js
CHANGED
|
@@ -1,20 +1,62 @@
|
|
|
1
|
-
|
|
1
|
+
// Mail: the Tylix-app API, built on createMailer().
|
|
2
|
+
//
|
|
3
|
+
// await Mail.send({ to, subject, view, data }, config.mail)
|
|
4
|
+
//
|
|
5
|
+
// `config.mail.driver` picks the transport: log (default), smtp, resend,
|
|
6
|
+
// sendgrid, postmark, mailgun, ses or memory. Every send is recorded in
|
|
7
|
+
// the mail_logs table when @tylix/orm is installed (the /dev/mail page
|
|
8
|
+
// reads it); without it, mail still sends.
|
|
2
9
|
import path from 'node:path'
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
import { LogDriver } from './drivers/LogDriver.js'
|
|
10
|
+
import { createMailer, createFakeTransport } from './createMailer.js'
|
|
11
|
+
import * as transports from './transports/index.js'
|
|
6
12
|
import { MailLog } from './models/MailLog.js'
|
|
7
13
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
function
|
|
11
|
-
if (config.
|
|
12
|
-
|
|
14
|
+
// A transport for config.mail. config.transport (an object with send())
|
|
15
|
+
// wins over config.driver.
|
|
16
|
+
export function transportFromConfig(config = {}) {
|
|
17
|
+
if (config.transport && typeof config.transport.send === 'function') return config.transport
|
|
18
|
+
switch (config.driver ?? 'log') {
|
|
19
|
+
case 'smtp':
|
|
20
|
+
return transports.smtp({
|
|
21
|
+
host: config.host,
|
|
22
|
+
port: Number(config.port) || 587,
|
|
23
|
+
secure: config.secure,
|
|
24
|
+
user: config.user,
|
|
25
|
+
password: config.password,
|
|
26
|
+
clientName: config.clientName,
|
|
27
|
+
requireTLS: config.requireTLS,
|
|
28
|
+
})
|
|
29
|
+
case 'resend':
|
|
30
|
+
return transports.resend({ apiKey: config.apiKey })
|
|
31
|
+
case 'sendgrid':
|
|
32
|
+
return transports.sendgrid({ apiKey: config.apiKey })
|
|
33
|
+
case 'postmark':
|
|
34
|
+
return transports.postmark({ serverToken: config.serverToken ?? config.apiKey, messageStream: config.messageStream })
|
|
35
|
+
case 'mailgun':
|
|
36
|
+
return transports.mailgun({ apiKey: config.apiKey, domain: config.domain, region: config.region })
|
|
37
|
+
case 'ses':
|
|
38
|
+
return transports.ses({
|
|
39
|
+
region: config.region,
|
|
40
|
+
accessKeyId: config.accessKeyId,
|
|
41
|
+
secretAccessKey: config.secretAccessKey,
|
|
42
|
+
sessionToken: config.sessionToken,
|
|
43
|
+
configurationSet: config.configurationSet,
|
|
44
|
+
})
|
|
45
|
+
case 'memory':
|
|
46
|
+
return transports.memory()
|
|
47
|
+
case 'log':
|
|
48
|
+
return transports.log()
|
|
49
|
+
default:
|
|
50
|
+
throw new Error(
|
|
51
|
+
`Unknown mail driver "${config.driver}". Use log, smtp, resend, sendgrid, postmark, mailgun, ses or memory.`,
|
|
52
|
+
)
|
|
53
|
+
}
|
|
13
54
|
}
|
|
14
55
|
|
|
15
56
|
// A logging failure (for example the mail_logs table not existing yet)
|
|
16
57
|
// must never change the outcome of the send itself.
|
|
17
|
-
async function
|
|
58
|
+
async function record(entry) {
|
|
59
|
+
if (!MailLog.available) return
|
|
18
60
|
try {
|
|
19
61
|
await MailLog.create(entry)
|
|
20
62
|
} catch (logErr) {
|
|
@@ -22,46 +64,57 @@ async function logSafely(entry) {
|
|
|
22
64
|
}
|
|
23
65
|
}
|
|
24
66
|
|
|
67
|
+
const recipients = (msg) => [...msg.to, ...msg.cc, ...msg.bcc].map((a) => a.address).join(', ')
|
|
68
|
+
|
|
69
|
+
// The body kept in mail_logs. Templates escape "&" as "&" (right
|
|
70
|
+
// for the mail that is sent), but the /dev/mail pages pick links out of
|
|
71
|
+
// this text with a regex, so a reset link with "&email=" would lose its
|
|
72
|
+
// email. The log keeps "&" plain, as it always did.
|
|
73
|
+
const logBody = (msg) => (msg.html || msg.text || '').replace(/&/g, '&')
|
|
74
|
+
|
|
75
|
+
let fakeTransport = null
|
|
76
|
+
|
|
77
|
+
export function mailerFromConfig(config = {}) {
|
|
78
|
+
return createMailer({
|
|
79
|
+
transport: fakeTransport ?? transportFromConfig(config),
|
|
80
|
+
from: config.from,
|
|
81
|
+
replyTo: config.replyTo,
|
|
82
|
+
views: config.views ?? path.join(process.cwd(), 'resources', 'mail'),
|
|
83
|
+
onSent: fakeTransport
|
|
84
|
+
? undefined
|
|
85
|
+
: ({ status, transport, message }) =>
|
|
86
|
+
record({ recipient: recipients(message), subject: message.subject, body: logBody(message), driver: transport, status }),
|
|
87
|
+
onError: fakeTransport
|
|
88
|
+
? undefined
|
|
89
|
+
: (err, { transport, message }) =>
|
|
90
|
+
record({ recipient: recipients(message), subject: message.subject, body: logBody(message), driver: transport, status: 'failed', error: err.message }),
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
|
|
25
94
|
export class Mail {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
95
|
+
// message: { to, cc?, bcc?, from?, replyTo?, subject, view?, data?,
|
|
96
|
+
// html?, text?, attachments?, headers?, tags? }
|
|
97
|
+
// or a Mailable instance.
|
|
98
|
+
static async send(message, config = {}) {
|
|
99
|
+
return mailerFromConfig(config).send(message)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Renders a message (view included) without sending it.
|
|
103
|
+
static async preview(message, config = {}) {
|
|
104
|
+
return mailerFromConfig(config).preview(message)
|
|
105
|
+
}
|
|
38
106
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
107
|
+
// In tests: every Mail.send() is captured instead of delivered.
|
|
108
|
+
// const mail = Mail.fake()
|
|
109
|
+
// ...
|
|
110
|
+
// mail.assertSent({ to: 'ada@example.com', subject: /Welcome/ })
|
|
111
|
+
// Mail.restore()
|
|
112
|
+
static fake() {
|
|
113
|
+
fakeTransport = createFakeTransport()
|
|
114
|
+
return fakeTransport
|
|
115
|
+
}
|
|
42
116
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (config.driver === 'smtp') {
|
|
46
|
-
await logSafely({
|
|
47
|
-
recipient: recipientLabel,
|
|
48
|
-
subject,
|
|
49
|
-
body: html,
|
|
50
|
-
driver: 'smtp',
|
|
51
|
-
status: result.status,
|
|
52
|
-
})
|
|
53
|
-
}
|
|
54
|
-
return result
|
|
55
|
-
} catch (err) {
|
|
56
|
-
await logSafely({
|
|
57
|
-
recipient: recipientLabel,
|
|
58
|
-
subject,
|
|
59
|
-
body: html,
|
|
60
|
-
driver: config.driver,
|
|
61
|
-
status: 'failed',
|
|
62
|
-
error: err.message,
|
|
63
|
-
})
|
|
64
|
-
throw err
|
|
65
|
-
}
|
|
117
|
+
static restore() {
|
|
118
|
+
fakeTransport = null
|
|
66
119
|
}
|
|
67
|
-
}
|
|
120
|
+
}
|
package/README.md
CHANGED
|
@@ -1,25 +1,98 @@
|
|
|
1
1
|
# @tylix/mail
|
|
2
2
|
|
|
3
|
-
Email for
|
|
4
|
-
|
|
3
|
+
Email for any Node.js app. Send through SMTP, Resend, SendGrid, Postmark,
|
|
4
|
+
Mailgun or Amazon SES with one API. Includes templates, attachments,
|
|
5
|
+
inline images, and a fake for tests. No dependencies.
|
|
6
|
+
|
|
7
|
+
It also plugs into Tylix apps, with Mailables and a log of sent mail.
|
|
5
8
|
|
|
6
9
|
```sh
|
|
7
10
|
npm install @tylix/mail
|
|
8
11
|
```
|
|
9
12
|
|
|
10
|
-
##
|
|
13
|
+
## Quick start (any Node app)
|
|
11
14
|
|
|
12
15
|
```js
|
|
13
|
-
import {
|
|
16
|
+
import { createMailer, transports } from '@tylix/mail'
|
|
17
|
+
|
|
18
|
+
const mailer = createMailer({
|
|
19
|
+
transport: transports.resend({ apiKey: process.env.RESEND_API_KEY }),
|
|
20
|
+
from: 'Acme <hello@acme.dev>',
|
|
21
|
+
views: './emails', // emails/welcome.html (+ optional welcome.txt)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
await mailer.send({
|
|
25
|
+
to: 'Ada Lovelace <ada@example.com>',
|
|
26
|
+
subject: 'Welcome to Acme',
|
|
27
|
+
view: 'welcome',
|
|
28
|
+
data: { name: 'Ada' },
|
|
29
|
+
})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Messages
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
await mailer.send({
|
|
36
|
+
from: 'Billing <billing@acme.dev>', // overrides the mailer default
|
|
37
|
+
to: ['ada@example.com', { name: 'Bob', address: 'bob@example.com' }],
|
|
38
|
+
cc: 'accounts@example.com',
|
|
39
|
+
bcc: 'archive@acme.dev', // only in the envelope, never in the headers
|
|
40
|
+
replyTo: 'support@acme.dev',
|
|
41
|
+
subject: 'Invoice #1042',
|
|
42
|
+
html: '<p>Thanks! <img src="cid:logo"></p>',
|
|
43
|
+
text: 'Thanks!', // generated from html when omitted
|
|
44
|
+
attachments: [
|
|
45
|
+
{ path: './invoices/1042.pdf' },
|
|
46
|
+
{ filename: 'data.csv', content: 'a,b\n1,2' },
|
|
47
|
+
{ filename: 'logo.png', path: './logo.png', cid: 'logo' }, // inline image
|
|
48
|
+
],
|
|
49
|
+
headers: { 'X-Entity-Ref-ID': 'inv-1042' },
|
|
50
|
+
tags: { tag: 'billing', customer: 42 },
|
|
51
|
+
})
|
|
52
|
+
```
|
|
14
53
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
54
|
+
The result is `{ status: 'sent', id, transport, message }`. `id` is the
|
|
55
|
+
provider's message id. Header injection (line breaks in addresses,
|
|
56
|
+
subjects or headers) is rejected before anything is sent.
|
|
57
|
+
|
|
58
|
+
## Transports
|
|
59
|
+
|
|
60
|
+
| Transport | Options |
|
|
61
|
+
| --- | --- |
|
|
62
|
+
| `transports.smtp()` | `host`, `port` (587 = STARTTLS, `secure: true` for 465), `user`, `password`, `requireTLS`, `clientName` |
|
|
63
|
+
| `transports.resend()` | `apiKey` |
|
|
64
|
+
| `transports.sendgrid()` | `apiKey` |
|
|
65
|
+
| `transports.postmark()` | `serverToken`, `messageStream` |
|
|
66
|
+
| `transports.mailgun()` | `apiKey`, `domain`, `region: 'us' \| 'eu'` |
|
|
67
|
+
| `transports.ses()` | `region`, `accessKeyId`, `secretAccessKey`, `sessionToken`, `configurationSet`. Defaults to the standard `AWS_*` variables. Requests are signed with SigV4, no AWS SDK needed |
|
|
68
|
+
| `transports.log()` | prints mail instead of sending (the default) |
|
|
69
|
+
| `transports.memory()` | keeps mail in `.messages` |
|
|
70
|
+
|
|
71
|
+
Provider errors throw `MailTransportError` with `.provider`, `.status`
|
|
72
|
+
and `.response`.
|
|
73
|
+
|
|
74
|
+
A custom transport is any object with
|
|
75
|
+
`send(message) → { status, id }`. It receives the normalized message
|
|
76
|
+
(parsed addresses, loaded attachments as Buffers).
|
|
77
|
+
|
|
78
|
+
## Templates
|
|
79
|
+
|
|
80
|
+
With `views: './emails'`, `view: 'welcome'` renders `emails/welcome.html`,
|
|
81
|
+
plus `emails/welcome.txt` as the text part when that file exists.
|
|
82
|
+
|
|
83
|
+
```html
|
|
84
|
+
<h1>Hi {{ user.name }}</h1> <!-- escaped -->
|
|
85
|
+
{{{ trustedHtml }}} <!-- inserted as-is -->
|
|
86
|
+
{{#if items}}
|
|
87
|
+
<ul>{{#each items}}<li>{{ @index }}. {{ title }}</li>{{/each}}</ul>
|
|
88
|
+
{{#else}}
|
|
89
|
+
<p>Nothing yet.</p>
|
|
90
|
+
{{/if}}
|
|
19
91
|
```
|
|
20
92
|
|
|
21
|
-
|
|
22
|
-
|
|
93
|
+
A missing variable throws, so a typo never mails `undefined`. To use
|
|
94
|
+
another engine (MJML, React Email, Handlebars…), pass a function:
|
|
95
|
+
`views: async (view, data) => ({ html, text })`.
|
|
23
96
|
|
|
24
97
|
## Mailables
|
|
25
98
|
|
|
@@ -36,22 +109,61 @@ export class WelcomeMail extends Mailable {
|
|
|
36
109
|
}
|
|
37
110
|
}
|
|
38
111
|
|
|
39
|
-
await new WelcomeMail(user)
|
|
112
|
+
await mailer.send(new WelcomeMail(user), user.email)
|
|
40
113
|
```
|
|
41
114
|
|
|
42
|
-
|
|
115
|
+
## Testing
|
|
116
|
+
|
|
117
|
+
```js
|
|
118
|
+
import { createMailer, createFakeTransport } from '@tylix/mail'
|
|
119
|
+
|
|
120
|
+
const fake = createFakeTransport()
|
|
121
|
+
const mailer = createMailer({ transport: fake, from: 'a@acme.dev', views: './emails' })
|
|
122
|
+
|
|
123
|
+
await signUp('ada@example.com') // your code, sending through `mailer`
|
|
124
|
+
|
|
125
|
+
fake.assertSent({ to: 'ada@example.com', subject: /Welcome/ })
|
|
126
|
+
fake.assertSent({ view: 'welcome' }, 1) // exactly once
|
|
127
|
+
fake.assertNotSent({ to: 'eve@example.com' })
|
|
128
|
+
fake.last().html // the rendered message
|
|
129
|
+
```
|
|
43
130
|
|
|
44
|
-
|
|
131
|
+
`mailer.preview(message)` returns the rendered message plus `raw`, the
|
|
132
|
+
complete `.eml` text.
|
|
45
133
|
|
|
46
|
-
|
|
134
|
+
## In Tylix apps
|
|
47
135
|
|
|
48
|
-
|
|
49
|
-
(`MAIL_SECURE=true` for port 465; port 587 upgrades with STARTTLS)
|
|
50
|
-
- `log` (default): records mail instead of sending it. In development the
|
|
51
|
-
starter shows them at `/dev/mail`, so verification and reset links work
|
|
52
|
-
without a mail server.
|
|
136
|
+
The starter configures mail from `.env`:
|
|
53
137
|
|
|
54
|
-
|
|
138
|
+
```sh
|
|
139
|
+
MAIL_DRIVER=resend # log | smtp | resend | sendgrid | postmark | mailgun | ses
|
|
140
|
+
MAIL_FROM="Acme <hello@acme.dev>"
|
|
141
|
+
MAIL_API_KEY=re_...
|
|
142
|
+
# smtp: MAIL_HOST MAIL_PORT MAIL_USER MAIL_PASSWORD MAIL_SECURE
|
|
143
|
+
# mailgun: MAIL_DOMAIN MAIL_REGION ses: MAIL_REGION + AWS_* credentials
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```js
|
|
147
|
+
import { Mail } from '@tylix/mail'
|
|
148
|
+
|
|
149
|
+
await Mail.send({ to: 'ada@example.com', subject: 'Welcome', view: 'welcome', data: { name: 'Ada' } }, config.mail)
|
|
150
|
+
await new WelcomeMail(user).send(user.email, config.mail)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Views live in `resources/mail/`. Every send is recorded in the
|
|
154
|
+
`mail_logs` table (`MailLog`), and in development the starter shows them
|
|
155
|
+
at `/dev/mail`, so verification and reset links work without a mail
|
|
156
|
+
server. `tylix make:mail Welcome` creates a Mailable.
|
|
157
|
+
|
|
158
|
+
In tests, `Mail.fake()` captures every `Mail.send()` until
|
|
159
|
+
`Mail.restore()`:
|
|
160
|
+
|
|
161
|
+
```js
|
|
162
|
+
const mail = Mail.fake()
|
|
163
|
+
await request(app).post('/api/auth/register').send({ email: 'ada@example.com' })
|
|
164
|
+
mail.assertSent({ to: 'ada@example.com', view: 'verify-email' })
|
|
165
|
+
Mail.restore()
|
|
166
|
+
```
|
|
55
167
|
|
|
56
168
|
## License
|
|
57
169
|
|
package/SmtpClient.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import net from 'node:net'
|
|
2
2
|
import tls from 'node:tls'
|
|
3
|
-
import
|
|
3
|
+
import { assertNoLineBreaks, buildMime, normalizeMessage } from './mime.js'
|
|
4
4
|
|
|
5
5
|
const DEFAULT_TIMEOUT_MS = 10_000
|
|
6
6
|
|
|
@@ -138,109 +138,6 @@ function connectSocket(options, timeoutMs) {
|
|
|
138
138
|
})
|
|
139
139
|
}
|
|
140
140
|
|
|
141
|
-
// --- Message building helpers -------------------------------------------
|
|
142
|
-
|
|
143
|
-
// Any CR or LF in a header value would let the caller add headers of
|
|
144
|
-
// their own (or extra SMTP commands, for the envelope addresses).
|
|
145
|
-
function assertNoLineBreaks(value, label) {
|
|
146
|
-
if (typeof value !== 'string' || /[\r\n]/.test(value)) {
|
|
147
|
-
throw new Error(`Invalid ${label}: line breaks are not allowed`)
|
|
148
|
-
}
|
|
149
|
-
return value
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// Envelope and header addresses must be a plain "user@host". This is
|
|
153
|
-
// also what MAIL FROM:<...> / RCPT TO:<...> require.
|
|
154
|
-
function assertAddress(value, label) {
|
|
155
|
-
assertNoLineBreaks(value, label)
|
|
156
|
-
if (!value.includes('@') || /[<>\s]/.test(value)) {
|
|
157
|
-
throw new Error(`Invalid ${label}: expected a plain email address`)
|
|
158
|
-
}
|
|
159
|
-
return value
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// RFC 2047: non-ASCII header text is sent as encoded words. Each word
|
|
163
|
-
// stays under the 75-character limit, and multi-byte characters are
|
|
164
|
-
// never split across words.
|
|
165
|
-
function encodeHeaderValue(value) {
|
|
166
|
-
assertNoLineBreaks(value, 'header value')
|
|
167
|
-
if (/^[\x20-\x7e]*$/.test(value)) return value
|
|
168
|
-
|
|
169
|
-
const words = []
|
|
170
|
-
let chunk = ''
|
|
171
|
-
let bytes = 0
|
|
172
|
-
for (const ch of value) {
|
|
173
|
-
const size = Buffer.byteLength(ch)
|
|
174
|
-
if (bytes + size > 45) {
|
|
175
|
-
words.push(chunk)
|
|
176
|
-
chunk = ''
|
|
177
|
-
bytes = 0
|
|
178
|
-
}
|
|
179
|
-
chunk += ch
|
|
180
|
-
bytes += size
|
|
181
|
-
}
|
|
182
|
-
if (chunk) words.push(chunk)
|
|
183
|
-
|
|
184
|
-
return words
|
|
185
|
-
.map((w) => `=?UTF-8?B?${Buffer.from(w).toString('base64')}?=`)
|
|
186
|
-
.join('\r\n ')
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// Base64 body parts need no line-ending normalisation or dot-stuffing:
|
|
190
|
-
// the encoded text only has A-Z a-z 0-9 + / = and is wrapped at 76.
|
|
191
|
-
function base64Lines(value) {
|
|
192
|
-
const encoded = Buffer.from(value, 'utf-8').toString('base64')
|
|
193
|
-
return (encoded.match(/.{1,76}/g) ?? []).join('\r\n')
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// Rough plain-text fallback so the text/plain part is never empty.
|
|
197
|
-
function htmlToText(html) {
|
|
198
|
-
return html
|
|
199
|
-
.replace(/<style[\s\S]*?<\/style>/gi, '')
|
|
200
|
-
.replace(/<br\s*\/?>|<\/p>|<\/div>|<\/h[1-6]>/gi, '\n')
|
|
201
|
-
.replace(/<[^>]+>/g, '')
|
|
202
|
-
.replace(/ /g, ' ')
|
|
203
|
-
.replace(/&/g, '&')
|
|
204
|
-
.replace(/\n{3,}/g, '\n\n')
|
|
205
|
-
.trim()
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
function buildMessage({ from, recipients, subject, html, text }) {
|
|
209
|
-
const boundary = `tylix-${crypto.randomBytes(12).toString('hex')}`
|
|
210
|
-
const domain = from.split('@')[1]
|
|
211
|
-
// RFC 5322 date, with a numeric zone instead of "GMT".
|
|
212
|
-
const date = new Date().toUTCString().replace('GMT', '+0000')
|
|
213
|
-
|
|
214
|
-
const plain = text || htmlToText(html || '')
|
|
215
|
-
|
|
216
|
-
const message = [
|
|
217
|
-
`From: ${from}`,
|
|
218
|
-
`To: ${recipients.join(', ')}`,
|
|
219
|
-
`Subject: ${encodeHeaderValue(subject)}`,
|
|
220
|
-
`Date: ${date}`,
|
|
221
|
-
`Message-ID: <${crypto.randomUUID()}@${domain}>`,
|
|
222
|
-
'MIME-Version: 1.0',
|
|
223
|
-
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
|
224
|
-
'',
|
|
225
|
-
`--${boundary}`,
|
|
226
|
-
'Content-Type: text/plain; charset=utf-8',
|
|
227
|
-
'Content-Transfer-Encoding: base64',
|
|
228
|
-
'',
|
|
229
|
-
base64Lines(plain),
|
|
230
|
-
`--${boundary}`,
|
|
231
|
-
'Content-Type: text/html; charset=utf-8',
|
|
232
|
-
'Content-Transfer-Encoding: base64',
|
|
233
|
-
'',
|
|
234
|
-
base64Lines(html || ''),
|
|
235
|
-
`--${boundary}--`,
|
|
236
|
-
].join('\r\n')
|
|
237
|
-
|
|
238
|
-
// Dot-stuffing per RFC 5321, then the terminator. Nothing in the
|
|
239
|
-
// message above can start a line with "." today, but this keeps it
|
|
240
|
-
// safe if a part is ever sent unencoded.
|
|
241
|
-
return `${message.replace(/(^|\r\n)\./g, '$1..')}\r\n.`
|
|
242
|
-
}
|
|
243
|
-
|
|
244
141
|
// --- Client ----------------------------------------------------------------
|
|
245
142
|
|
|
246
143
|
export class SmtpClient {
|
|
@@ -255,7 +152,9 @@ export class SmtpClient {
|
|
|
255
152
|
// nearly all of them; set it to your app's hostname for production.
|
|
256
153
|
clientName = 'localhost',
|
|
257
154
|
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
155
|
+
requireTLS,
|
|
258
156
|
}) {
|
|
157
|
+
this.requireTLS = requireTLS
|
|
259
158
|
this.host = host
|
|
260
159
|
this.port = port
|
|
261
160
|
this.secure = secure
|
|
@@ -274,9 +173,16 @@ export class SmtpClient {
|
|
|
274
173
|
|
|
275
174
|
checkCode(await this.reader.read(this.timeoutMs), [220])
|
|
276
175
|
writeCommand(this.socket, `EHLO ${this.clientName}`)
|
|
277
|
-
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
278
|
-
|
|
279
|
-
|
|
176
|
+
this.ehlo = checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
177
|
+
|
|
178
|
+
// STARTTLS on port 587 (unless requireTLS is false), or on any port
|
|
179
|
+
// when requireTLS is true. Other ports stay plain, as local test
|
|
180
|
+
// servers (Mailpit, MailHog) expect.
|
|
181
|
+
const upgrade = this.port === 587 ? this.requireTLS !== false : this.requireTLS === true
|
|
182
|
+
if (!this.secure && upgrade) {
|
|
183
|
+
if (!/^250[ -]STARTTLS/im.test(this.ehlo)) {
|
|
184
|
+
throw new Error(`${this.host}:${this.port} does not offer STARTTLS`)
|
|
185
|
+
}
|
|
280
186
|
writeCommand(this.socket, 'STARTTLS')
|
|
281
187
|
checkCode(await this.reader.read(this.timeoutMs), [220])
|
|
282
188
|
|
|
@@ -304,42 +210,47 @@ export class SmtpClient {
|
|
|
304
210
|
this.reader = new SmtpResponseReader(this.socket)
|
|
305
211
|
|
|
306
212
|
writeCommand(this.socket, `EHLO ${this.clientName}`)
|
|
307
|
-
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
213
|
+
this.ehlo = checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
308
214
|
}
|
|
309
215
|
|
|
310
216
|
if (this.user && this.password) {
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
217
|
+
// AUTH PLAIN when the server offers it (one round trip), else LOGIN.
|
|
218
|
+
if (/AUTH[ =][^\r\n]*\bPLAIN\b/i.test(this.ehlo ?? '')) {
|
|
219
|
+
const token = Buffer.from(`\0${this.user}\0${this.password}`).toString('base64')
|
|
220
|
+
writeCommand(this.socket, `AUTH PLAIN ${token}`)
|
|
221
|
+
checkCode(await this.reader.read(this.timeoutMs), [235])
|
|
222
|
+
} else {
|
|
223
|
+
writeCommand(this.socket, 'AUTH LOGIN')
|
|
224
|
+
checkCode(await this.reader.read(this.timeoutMs), [334])
|
|
225
|
+
writeCommand(this.socket, Buffer.from(this.user).toString('base64'))
|
|
226
|
+
checkCode(await this.reader.read(this.timeoutMs), [334])
|
|
227
|
+
writeCommand(this.socket, Buffer.from(this.password).toString('base64'))
|
|
228
|
+
checkCode(await this.reader.read(this.timeoutMs), [235])
|
|
229
|
+
}
|
|
317
230
|
}
|
|
318
231
|
}
|
|
319
232
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
text,
|
|
334
|
-
})
|
|
233
|
+
// Simple form kept for existing callers: builds the message itself.
|
|
234
|
+
async send(message) {
|
|
235
|
+
const msg = normalizeMessage(message)
|
|
236
|
+
return this.sendRaw(buildMime(msg))
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Sends an already-built message (see mime.js buildMime) to the
|
|
240
|
+
// envelope recipients: to, cc and bcc each get a RCPT TO.
|
|
241
|
+
async sendRaw({ raw, envelope }) {
|
|
242
|
+
assertNoLineBreaks(envelope.from, 'envelope from')
|
|
243
|
+
for (const r of envelope.to) assertNoLineBreaks(r, 'envelope recipient')
|
|
244
|
+
// Dot-stuffing per RFC 5321, then the terminator.
|
|
245
|
+
const data = `${raw.replace(/\r\n$/, '').replace(/(^|\r\n)\./g, '$1..')}\r\n.`
|
|
335
246
|
|
|
336
247
|
try {
|
|
337
248
|
await this.connect()
|
|
338
249
|
|
|
339
|
-
writeCommand(this.socket, `MAIL FROM:<${from}>`)
|
|
250
|
+
writeCommand(this.socket, `MAIL FROM:<${envelope.from}>`)
|
|
340
251
|
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
341
252
|
|
|
342
|
-
for (const recipient of
|
|
253
|
+
for (const recipient of envelope.to) {
|
|
343
254
|
writeCommand(this.socket, `RCPT TO:<${recipient}>`)
|
|
344
255
|
checkCode(await this.reader.read(this.timeoutMs), [250, 251])
|
|
345
256
|
}
|
|
@@ -347,16 +258,16 @@ export class SmtpClient {
|
|
|
347
258
|
writeCommand(this.socket, 'DATA')
|
|
348
259
|
checkCode(await this.reader.read(this.timeoutMs), [354])
|
|
349
260
|
|
|
350
|
-
writeCommand(this.socket,
|
|
351
|
-
checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
261
|
+
writeCommand(this.socket, data)
|
|
262
|
+
const accepted = checkCode(await this.reader.read(this.timeoutMs), [250])
|
|
352
263
|
|
|
353
264
|
writeCommand(this.socket, 'QUIT')
|
|
354
|
-
// Give the server a moment to acknowledge before the socket closes.
|
|
355
265
|
// The message is already accepted, so a missing reply is not an error.
|
|
356
266
|
await this.reader.read(2000).catch(() => {})
|
|
267
|
+
return { response: accepted.trim() }
|
|
357
268
|
} finally {
|
|
358
269
|
this.reader?.detach()
|
|
359
270
|
this.socket?.end()
|
|
360
271
|
}
|
|
361
272
|
}
|
|
362
|
-
}
|
|
273
|
+
}
|