import { readBody, createError } from 'h3' import { getDb } from '../utils/db' import { getConfig } from '../utils/config' import { sendMail } from '../utils/email' import { isValidEmail } from '../utils/validation' /** * 联系表单:真实落库 + 尽力发送邮件(SMTP 未配置时 delivered=false,但数据不丢) */ export default defineEventHandler(async (event) => { const body = await readBody(event) const name = String(body?.name ?? '').trim() const email = String(body?.email ?? '').trim().toLowerCase() const subject = String(body?.subject ?? '').trim() const message = String(body?.message ?? '').trim() if (!name || !subject || !message) { throw createError({ statusCode: 400, message: '请完整填写姓名、主题与留言内容', data: { code: 'VALIDATION_ERROR' } }) } if (!isValidEmail(email)) { throw createError({ statusCode: 400, message: '邮箱格式不正确', data: { code: 'VALIDATION_ERROR' } }) } const { contactTo } = getConfig() const result = contactTo ? await sendMail( contactTo, `[站点联系] ${subject}`, `姓名: ${name}\n邮箱: ${email}\n主题: ${subject}\n\n${message}`, ) : { sent: false, skipped: true } const db = getDb() db.prepare('INSERT INTO contacts (name, email, subject, message, delivered) VALUES (?, ?, ?, ?, ?)').run( name, email, subject, message, result.sent ? 1 : 0, ) return { ok: true, delivered: result.sent } })