Files

97 lines
2.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import nodemailer from 'nodemailer'
import type { Transporter } from 'nodemailer'
type MailPayload = {
subject: string
text: string
html: string
replyTo?: string
}
let transporter: Transporter | null = null
let transporterKey = ''
function getMailConfig() {
const config = useRuntimeConfig()
return {
enabled: String(config.mailEnabled) !== 'false',
host: String(config.mailSmtpHost || 'smtp.exmail.qq.com'),
port: Number(config.mailSmtpPort || 465),
secure: String(config.mailSmtpSecure) !== 'false',
user: String(config.mailUser || ''),
pass: String(config.mailPass || ''),
from: String(config.mailFrom || config.mailUser || ''),
to: String(config.mailTo || 'info@umedglobal.com.cn')
}
}
function getTransporter(): Transporter | null {
const mail = getMailConfig()
if (!mail.enabled || !mail.user || !mail.pass || !mail.to) return null
const key = `${mail.host}:${mail.port}:${mail.user}`
if (!transporter || transporterKey !== key) {
transporter = nodemailer.createTransport({
host: mail.host,
port: mail.port,
secure: mail.secure,
auth: {
user: mail.user,
pass: mail.pass
}
})
transporterKey = key
}
return transporter
}
function escapeHtml(value: string): string {
return value
.replaceAll('&', '&')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
}
export async function sendMail(payload: MailPayload): Promise<boolean> {
const mail = getMailConfig()
const transport = getTransporter()
if (!transport) {
console.warn('[mail] SMTP 未配置,跳过发送邮件')
return false
}
try {
await transport.sendMail({
from: mail.from,
to: mail.to,
replyTo: payload.replyTo,
subject: payload.subject,
text: payload.text,
html: payload.html
})
return true
} catch (error) {
console.error('[mail] 发送失败:', error)
return false
}
}
export function buildMailHtml(title: string, rows: Array<{ label: string; value: string }>): string {
const body = rows
.map(
(row) =>
`<tr><td style="padding:8px 12px;border:1px solid #e5e7eb;background:#f8fafc;width:180px;font-weight:600;">${escapeHtml(row.label)}</td><td style="padding:8px 12px;border:1px solid #e5e7eb;white-space:pre-wrap;">${escapeHtml(row.value)}</td></tr>`
)
.join('')
return `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="font-family:system-ui,sans-serif;color:#111827;"><h2 style="margin:0 0 16px;">${escapeHtml(title)}</h2><table style="border-collapse:collapse;width:100%;max-width:720px;">${body}</table></body></html>`
}
export function buildMailText(title: string, rows: Array<{ label: string; value: string }>): string {
const lines = rows.map((row) => `${row.label}:${row.value}`)
return [title, '', ...lines].join('\n')
}