export const prerender = false; import type { APIRoute } from 'astro'; import nodemailer from 'nodemailer'; import { getAccount } from '../../../lib/mail-accounts'; export const POST: APIRoute = async ({ request }) => { const ct = request.headers.get('content-type') || ''; let accountId: string | null = null; let to: string | null = null; let cc: string | null = null; let subject: string | null = null; let text: string | null = null; let html: string | null = null; let replyToMessageId: string | null = null; let attachments: { filename: string; content: Buffer; contentType: string }[] = []; if (ct.includes('multipart/form-data')) { const fd = await request.formData(); accountId = fd.get('account') as string; to = fd.get('to') as string; cc = fd.get('cc') as string; subject = fd.get('subject') as string; text = fd.get('text') as string; html = fd.get('html') as string; replyToMessageId = fd.get('replyToMessageId') as string; for (const file of fd.getAll('attachments')) { if (file instanceof File) { attachments.push({ filename: file.name, content: Buffer.from(await file.arrayBuffer()), contentType: file.type || 'application/octet-stream', }); } } } else { const body = await request.json().catch(() => null); if (!body) return json({ error: 'Bad request' }, 400); ({ account: accountId, to, cc, subject, text, html, replyToMessageId } = body); } const acct = accountId ? getAccount(accountId) : undefined; if (!acct) return json({ error: 'Unknown account' }, 400); const transport = nodemailer.createTransport({ host: acct.smtp.host, port: acct.smtp.port, secure: true, auth: { user: acct.smtp.user, pass: acct.smtp.password }, }); try { const info = await transport.sendMail({ from: `${acct.name} <${acct.email}>`, to: to || undefined, cc: cc || undefined, subject: subject || undefined, text: text || undefined, html: html || undefined, attachments: attachments.length > 0 ? attachments : undefined, ...(replyToMessageId ? { inReplyTo: replyToMessageId, references: replyToMessageId } : {}), }); return json({ ok: true, messageId: info.messageId }); } catch (e: any) { return json({ error: e.message }, 500); } }; function json(data: object, status = 200) { return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } }); }