Initial commit
This commit is contained in:
51
apps/backend/src/lib/mailer.ts
Normal file
51
apps/backend/src/lib/mailer.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import nodemailer from 'nodemailer'
|
||||
|
||||
let cachedTransporter: ReturnType<typeof nodemailer.createTransport> | null = null
|
||||
|
||||
function getTransporter() {
|
||||
if (cachedTransporter) return cachedTransporter
|
||||
|
||||
const smtpHost = Bun.env.SMTP_HOST
|
||||
const smtpPort = Number(Bun.env.SMTP_PORT ?? 587)
|
||||
const smtpUser = Bun.env.SMTP_USER
|
||||
const smtpPass = Bun.env.SMTP_PASS
|
||||
|
||||
if (!smtpHost || !smtpUser || !smtpPass) {
|
||||
throw new Error(
|
||||
'Missing SMTP env vars. Set SMTP_HOST, SMTP_PORT, SMTP_USER and SMTP_PASS.',
|
||||
)
|
||||
}
|
||||
|
||||
cachedTransporter = nodemailer.createTransport({
|
||||
host: smtpHost,
|
||||
port: smtpPort,
|
||||
secure: smtpPort === 465,
|
||||
auth: {
|
||||
user: smtpUser,
|
||||
pass: smtpPass,
|
||||
},
|
||||
})
|
||||
|
||||
return cachedTransporter
|
||||
}
|
||||
|
||||
export async function sendMail(input: {
|
||||
to: string
|
||||
subject: string
|
||||
html: string
|
||||
text: string
|
||||
}) {
|
||||
const smtpFrom = Bun.env.SMTP_FROM
|
||||
|
||||
if (!smtpFrom) {
|
||||
throw new Error('Missing SMTP_FROM env var.')
|
||||
}
|
||||
|
||||
await getTransporter().sendMail({
|
||||
from: smtpFrom,
|
||||
to: input.to,
|
||||
subject: input.subject,
|
||||
html: input.html,
|
||||
text: input.text,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user