mailship/src/mailer.ts

64 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-08-24 20:12:32 +00:00
import nodemailer from 'nodemailer'
import { SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_FROM, MAILSHIP_NAME, BASE_URL } from './env.js'
import type { Subscription } from './alert.js'
import { render } from './templates.js'
2026-08-25 19:15:33 +00:00
const secure = Number(SMTP_PORT) === 465
2026-08-24 20:12:32 +00:00
const transporter = nodemailer.createTransport({
host: SMTP_HOST,
port: Number(SMTP_PORT),
2026-08-25 19:15:33 +00:00
secure,
requireTLS: !secure,
2026-08-24 20:12:32 +00:00
auth: {
user: SMTP_USER,
pass: SMTP_PASSWORD,
},
})
export const sendConfirm = (sub: Subscription) => {
const href = `${BASE_URL}/confirm?token=${sub.key}`
2026-08-25 19:15:33 +00:00
return transporter
.sendMail({
from: SMTP_FROM,
to: sub.email,
subject: 'Confirm your email digest',
html: `
<h3>Welcome to ${MAILSHIP_NAME}!</h3>
<p>Please confirm that you would like to receive ${sub.frequency} digests by clicking the link below:</p>
<p><a href="${href}">Confirm Digest</a></p>
`,
2026-08-25 19:15:33 +00:00
text: `Please confirm that you would like to receive ${sub.frequency} digests by visiting: ${href}`,
})
.catch(error => {
console.error('mailer: confirmation email failed', {
to: sub.email,
smtp: { host: SMTP_HOST, port: SMTP_PORT },
error: error?.message || error,
})
throw error
})
}
export const sendDigest = async (sub: Subscription, variables: Record<string, any>) => {
2026-08-25 19:15:33 +00:00
return transporter
.sendMail({
from: SMTP_FROM,
to: sub.email,
subject: 'New activity',
html: await render('emails/digest.mjml', {
...variables,
name: sub.email.split('@')[0],
unsubscribeUrl: `${BASE_URL}/unsubscribe?token=${sub.key}`,
}),
})
.catch(error => {
console.error('mailer: digest email failed', {
to: sub.email,
smtp: { host: SMTP_HOST, port: SMTP_PORT },
error: error?.message || error,
})
throw error
})
}