@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.
@@ -0,0 +1,39 @@
1
+ // Resend: https://resend.com/docs/api-reference/emails/send-email
2
+ import { addr, b64, request, requireOption } from './http.js'
3
+
4
+ export function resend({ apiKey, endpoint = 'https://api.resend.com', fetch } = {}) {
5
+ requireOption(apiKey, 'resend', 'apiKey')
6
+ return {
7
+ name: 'resend',
8
+ async send(msg) {
9
+ const payload = {
10
+ from: addr(msg.from),
11
+ to: msg.to.map(addr),
12
+ subject: msg.subject,
13
+ html: msg.html || undefined,
14
+ text: msg.text || undefined,
15
+ }
16
+ if (msg.cc.length) payload.cc = msg.cc.map(addr)
17
+ if (msg.bcc.length) payload.bcc = msg.bcc.map(addr)
18
+ if (msg.replyTo.length) payload.reply_to = msg.replyTo.map(addr)
19
+ if (Object.keys(msg.headers).length) payload.headers = msg.headers
20
+ if (Object.keys(msg.tags).length) {
21
+ payload.tags = Object.entries(msg.tags).map(([name, value]) => ({ name, value: String(value) }))
22
+ }
23
+ if (msg.attachments.length) {
24
+ payload.attachments = msg.attachments.map((a) => ({
25
+ filename: a.filename,
26
+ content: b64(a.content),
27
+ content_type: a.contentType,
28
+ ...(a.cid ? { content_id: a.cid } : {}),
29
+ }))
30
+ }
31
+ const { body } = await request('Resend', fetch, `${endpoint}/emails`, {
32
+ method: 'POST',
33
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
34
+ body: JSON.stringify(payload),
35
+ })
36
+ return { status: 'sent', id: body?.id ?? null }
37
+ },
38
+ }
39
+ }
@@ -0,0 +1,46 @@
1
+ // SendGrid: https://www.twilio.com/docs/sendgrid/api-reference/mail-send/mail-send
2
+ import { b64, request, requireOption } from './http.js'
3
+
4
+ const person = (a) => (a.name ? { email: a.address, name: a.name } : { email: a.address })
5
+
6
+ export function sendgrid({ apiKey, endpoint = 'https://api.sendgrid.com', fetch } = {}) {
7
+ requireOption(apiKey, 'sendgrid', 'apiKey')
8
+ return {
9
+ name: 'sendgrid',
10
+ async send(msg) {
11
+ const personalization = {}
12
+ if (msg.to.length) personalization.to = msg.to.map(person)
13
+ if (msg.cc.length) personalization.cc = msg.cc.map(person)
14
+ if (msg.bcc.length) personalization.bcc = msg.bcc.map(person)
15
+ const content = []
16
+ if (msg.text) content.push({ type: 'text/plain', value: msg.text }) // text must come first
17
+ if (msg.html) content.push({ type: 'text/html', value: msg.html })
18
+ const payload = {
19
+ personalizations: [personalization],
20
+ from: person(msg.from),
21
+ subject: msg.subject,
22
+ content,
23
+ }
24
+ if (msg.replyTo.length) payload.reply_to_list = msg.replyTo.map(person)
25
+ if (Object.keys(msg.headers).length) payload.headers = msg.headers
26
+ if (Object.keys(msg.tags).length) {
27
+ payload.custom_args = Object.fromEntries(Object.entries(msg.tags).map(([k, v]) => [k, String(v)]))
28
+ }
29
+ if (msg.attachments.length) {
30
+ payload.attachments = msg.attachments.map((a) => ({
31
+ content: b64(a.content),
32
+ filename: a.filename,
33
+ type: a.contentType,
34
+ disposition: a.cid ? 'inline' : 'attachment',
35
+ ...(a.cid ? { content_id: a.cid } : {}),
36
+ }))
37
+ }
38
+ const { res } = await request('SendGrid', fetch, `${endpoint}/v3/mail/send`, {
39
+ method: 'POST',
40
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
41
+ body: JSON.stringify(payload),
42
+ })
43
+ return { status: 'sent', id: res.headers?.get?.('x-message-id') ?? null }
44
+ },
45
+ }
46
+ }
@@ -0,0 +1,87 @@
1
+ // Amazon SES (API v2, SendEmail with a raw MIME message, so
2
+ // attachments, inline images and custom headers all work):
3
+ // https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html
4
+ //
5
+ // Credentials default to the standard AWS environment variables. The
6
+ // request is signed with Signature Version 4 here; no AWS SDK needed.
7
+ import crypto from 'node:crypto'
8
+ import { buildMime } from '../mime.js'
9
+ import { request, requireOption } from './http.js'
10
+
11
+ const hmac = (key, data) => crypto.createHmac('sha256', key).update(data).digest()
12
+ const sha256 = (data) => crypto.createHash('sha256').update(data).digest('hex')
13
+
14
+ // AWS SigV4 signing key: HMAC chain over date, region, service.
15
+ export function signingKey(secret, date, region, service) {
16
+ return hmac(hmac(hmac(hmac(`AWS4${secret}`, date), region), service), 'aws4_request')
17
+ }
18
+
19
+ // Headers (including Authorization) for a signed AWS JSON request.
20
+ export function signAwsRequest({ method, url, body, region, service, accessKeyId, secretAccessKey, sessionToken, now = new Date() }) {
21
+ const u = new URL(url)
22
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '')
23
+ const date = amzDate.slice(0, 8)
24
+ const headers = {
25
+ 'content-type': 'application/json',
26
+ host: u.host,
27
+ 'x-amz-date': amzDate,
28
+ ...(sessionToken ? { 'x-amz-security-token': sessionToken } : {}),
29
+ }
30
+ const names = Object.keys(headers).sort()
31
+ const canonical = [
32
+ method,
33
+ u.pathname.split('/').map((s) => encodeURIComponent(decodeURIComponent(s))).join('/'),
34
+ u.searchParams.toString(),
35
+ names.map((n) => `${n}:${headers[n]}\n`).join(''),
36
+ names.join(';'),
37
+ sha256(body),
38
+ ].join('\n')
39
+ const scope = `${date}/${region}/${service}/aws4_request`
40
+ const toSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256(canonical)].join('\n')
41
+ const signature = crypto
42
+ .createHmac('sha256', signingKey(secretAccessKey, date, region, service))
43
+ .update(toSign)
44
+ .digest('hex')
45
+ return {
46
+ ...headers,
47
+ authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${signature}`,
48
+ }
49
+ }
50
+
51
+ export function ses({
52
+ region = process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION,
53
+ accessKeyId = process.env.AWS_ACCESS_KEY_ID,
54
+ secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY,
55
+ sessionToken = process.env.AWS_SESSION_TOKEN,
56
+ configurationSet,
57
+ endpoint,
58
+ fetch,
59
+ } = {}) {
60
+ requireOption(region, 'ses', 'region (or AWS_REGION)')
61
+ requireOption(accessKeyId, 'ses', 'accessKeyId (or AWS_ACCESS_KEY_ID)')
62
+ requireOption(secretAccessKey, 'ses', 'secretAccessKey (or AWS_SECRET_ACCESS_KEY)')
63
+ const url = `${endpoint ?? `https://email.${region}.amazonaws.com`}/v2/email/outbound-emails`
64
+ return {
65
+ name: 'ses',
66
+ async send(msg) {
67
+ const { raw } = buildMime(msg)
68
+ const payload = {
69
+ Content: { Raw: { Data: Buffer.from(raw).toString('base64') } },
70
+ // Explicit destinations, so Bcc (not in the headers) is delivered.
71
+ Destination: {
72
+ ToAddresses: msg.to.map((a) => a.address),
73
+ CcAddresses: msg.cc.map((a) => a.address),
74
+ BccAddresses: msg.bcc.map((a) => a.address),
75
+ },
76
+ }
77
+ if (configurationSet) payload.ConfigurationSetName = configurationSet
78
+ const tags = Object.entries(msg.tags)
79
+ if (tags.length) payload.EmailTags = tags.map(([Name, Value]) => ({ Name, Value: String(Value) }))
80
+ const body = JSON.stringify(payload)
81
+ const headers = signAwsRequest({ method: 'POST', url, body, region, service: 'ses', accessKeyId, secretAccessKey, sessionToken })
82
+ delete headers.host // fetch sets it
83
+ const { body: res } = await request('Amazon SES', fetch, url, { method: 'POST', headers, body })
84
+ return { status: 'sent', id: res?.MessageId ?? null }
85
+ },
86
+ }
87
+ }
@@ -0,0 +1,16 @@
1
+ import { SmtpClient } from '../SmtpClient.js'
2
+ import { buildMime } from '../mime.js'
3
+
4
+ // smtp({ host, port, secure, user, password, clientName, requireTLS, timeoutMs })
5
+ export function smtp(options = {}) {
6
+ if (!options.host) throw new Error('The smtp mail transport needs `host`')
7
+ return {
8
+ name: 'smtp',
9
+ async send(msg) {
10
+ const built = buildMime(msg)
11
+ const client = new SmtpClient({ port: 587, ...options })
12
+ const { response } = await client.sendRaw(built)
13
+ return { status: 'sent', id: built.messageId, response }
14
+ },
15
+ }
16
+ }
@@ -1,16 +0,0 @@
1
- import { MailLog } from '../models/MailLog.js'
2
-
3
- export class LogDriver {
4
- async deliver({ to, subject, html, text }) {
5
- const body = html || text || ''
6
- console.log(`\nšŸ“§ [mail:log] To: ${to}\n Subject: ${subject}\n${body}\n`)
7
- await MailLog.create({
8
- recipient: to,
9
- subject,
10
- body,
11
- driver: 'log',
12
- status: 'captured',
13
- })
14
- return { status: 'captured' }
15
- }
16
- }
@@ -1,20 +0,0 @@
1
- import { SmtpClient } from '../SmtpClient.js'
2
-
3
- export class SmtpDriver {
4
- constructor(config) {
5
- this.config = config
6
- }
7
-
8
- async deliver({ to, subject, html, text }) {
9
- const client = new SmtpClient({
10
- host: this.config.host,
11
- port: this.config.port,
12
- secure: this.config.secure,
13
- user: this.config.user,
14
- password: this.config.password,
15
- clientName: this.config.clientName,
16
- })
17
- await client.send({ from: this.config.from, to, subject, html, text })
18
- return { status: 'sent' }
19
- }
20
- }