73 lines
1.8 KiB
TypeScript
73 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { parseEmail } from '@/lib/server/email-parser';
|
|
import { sanitizeHtml } from '@/lib/utils/dom-purify-config';
|
|
|
|
interface EmailAddress {
|
|
name?: string;
|
|
address: string;
|
|
}
|
|
|
|
// Helper to extract email addresses from mailparser Address objects
|
|
function getEmailAddresses(addresses: any): EmailAddress[] {
|
|
if (!addresses) return [];
|
|
|
|
// Handle various address formats
|
|
if (Array.isArray(addresses)) {
|
|
return addresses.map(addr => ({
|
|
name: addr.name || undefined,
|
|
address: addr.address
|
|
}));
|
|
}
|
|
|
|
if (typeof addresses === 'object') {
|
|
const result: EmailAddress[] = [];
|
|
// Handle mailparser format with text, html, value properties
|
|
if (addresses.value) {
|
|
addresses.value.forEach((addr: any) => {
|
|
result.push({
|
|
name: addr.name || undefined,
|
|
address: addr.address
|
|
});
|
|
});
|
|
return result;
|
|
}
|
|
|
|
// Handle direct object with address property
|
|
if (addresses.address) {
|
|
return [{
|
|
name: addresses.name || undefined,
|
|
address: addresses.address
|
|
}];
|
|
}
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
|
|
if (!body.email) {
|
|
return NextResponse.json(
|
|
{ error: 'Missing email content' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const parsedEmail = await parseEmail(body.email);
|
|
|
|
// Process HTML content if available
|
|
if (parsedEmail.html) {
|
|
parsedEmail.html = sanitizeHtml(parsedEmail.html);
|
|
}
|
|
|
|
return NextResponse.json(parsedEmail);
|
|
} catch (error) {
|
|
console.error('Error parsing email:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to parse email', details: error instanceof Error ? error.message : String(error) },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|