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('<', '<') .replaceAll('>', '>') .replaceAll('"', '"') } export async function sendMail(payload: MailPayload): Promise { 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) => `${escapeHtml(row.label)}${escapeHtml(row.value)}` ) .join('') return `

${escapeHtml(title)}

${body}
` } 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') }