49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { simpleParser, AddressObject } from 'mailparser';
|
|
|
|
function getEmailAddress(address: AddressObject | AddressObject[] | undefined): string | null {
|
|
if (!address) return null;
|
|
if (Array.isArray(address)) {
|
|
return address.map(a => a.text).join(', ');
|
|
}
|
|
return address.text;
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const body = await request.json();
|
|
const { email } = body;
|
|
|
|
if (!email || typeof email !== 'string') {
|
|
return NextResponse.json(
|
|
{ error: 'Invalid email content' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const parsed = await simpleParser(email);
|
|
|
|
return NextResponse.json({
|
|
subject: parsed.subject || null,
|
|
from: getEmailAddress(parsed.from),
|
|
to: getEmailAddress(parsed.to),
|
|
cc: getEmailAddress(parsed.cc),
|
|
bcc: getEmailAddress(parsed.bcc),
|
|
date: parsed.date || null,
|
|
html: parsed.html || null,
|
|
text: parsed.textAsHtml || parsed.text || null,
|
|
attachments: parsed.attachments?.map(att => ({
|
|
filename: att.filename,
|
|
contentType: att.contentType,
|
|
size: att.size
|
|
})) || [],
|
|
headers: parsed.headers || {}
|
|
});
|
|
} catch (error) {
|
|
console.error('Error parsing email:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to parse email' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|