65 lines
2.1 KiB
TypeScript
65 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
||
import { auth } from "@/auth";
|
||
import { getMailSession } from "@/lib/mail-session";
|
||
import { sendMail } from "@/lib/smtp";
|
||
|
||
// POST /api/mail/send — supports both JSON and FormData (for attachments)
|
||
export async function POST(req: NextRequest) {
|
||
const session = await auth();
|
||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||
|
||
const creds = await getMailSession();
|
||
if (!creds) return NextResponse.json({ error: "Mail oturumu yok" }, { status: 401 });
|
||
|
||
const contentType = req.headers.get("content-type") ?? "";
|
||
|
||
let to: string, cc: string | undefined, subject: string, html: string, text: string | undefined;
|
||
let attachments: { filename: string; content: Buffer; contentType?: string }[] = [];
|
||
|
||
if (contentType.includes("multipart/form-data")) {
|
||
// FormData — with attachments
|
||
const formData = await req.formData();
|
||
to = formData.get("to") as string;
|
||
cc = (formData.get("cc") as string) || undefined;
|
||
subject = formData.get("subject") as string;
|
||
html = (formData.get("html") as string) || "";
|
||
text = (formData.get("text") as string) || undefined;
|
||
|
||
const files = formData.getAll("attachments") as File[];
|
||
for (const file of files) {
|
||
const buffer = Buffer.from(await file.arrayBuffer());
|
||
attachments.push({
|
||
filename: file.name,
|
||
content: buffer,
|
||
contentType: file.type || undefined,
|
||
});
|
||
}
|
||
} else {
|
||
// JSON — simple message
|
||
const body = await req.json();
|
||
to = body.to;
|
||
cc = body.cc || undefined;
|
||
subject = body.subject;
|
||
html = body.html || `<p>${body.text || ""}</p>`;
|
||
text = body.text || undefined;
|
||
}
|
||
|
||
if (!to || !subject) {
|
||
return NextResponse.json({ error: "Alıcı ve konu gerekli" }, { status: 400 });
|
||
}
|
||
|
||
const result = await sendMail(creds, {
|
||
to,
|
||
cc,
|
||
subject,
|
||
html,
|
||
text,
|
||
attachments: attachments.length > 0 ? attachments : undefined,
|
||
});
|
||
|
||
if (result.success) {
|
||
return NextResponse.json({ success: true, messageId: result.messageId });
|
||
}
|
||
return NextResponse.json({ error: result.error }, { status: 502 });
|
||
}
|