Neah/app/api/parse-email/route.ts
2025-04-25 21:17:33 +02:00

92 lines
3.3 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 {
console.log('[DEBUG] Parse-email API called');
const body = await request.json();
const emailContent = body.email || body.emailContent;
if (!emailContent || typeof emailContent !== 'string') {
console.error('[DEBUG] Parse-email API error: Invalid email content');
return NextResponse.json(
{ error: 'Invalid email content' },
{ status: 400 }
);
}
console.log('[DEBUG] Parse-email API processing email content, length:', emailContent.length);
console.log('[DEBUG] Content sample:', emailContent.substring(0, 100) + '...');
try {
const parsed = await simpleParser(emailContent);
console.log('[DEBUG] Parse-email API successfully parsed email:', {
hasSubject: !!parsed.subject,
hasHtml: !!parsed.html,
hasText: !!parsed.text,
hasTextAsHtml: !!parsed.textAsHtml,
fromCount: parsed.from ? (Array.isArray(parsed.from) ? parsed.from.length : 1) : 0,
attachmentCount: parsed.attachments?.length || 0
});
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 || parsed.textAsHtml || null,
text: parsed.text || null,
attachments: parsed.attachments?.map(att => ({
filename: att.filename,
contentType: att.contentType,
size: att.size
})) || [],
headers: parsed.headers || {}
});
} catch (parseError) {
console.error('[DEBUG] Parse-email API error parsing email:', parseError);
// Try simpler parsing method for more resilience
try {
console.log('[DEBUG] Attempting fallback parsing method');
const resultObj: any = { text: emailContent, html: null };
// Simple check if it might be HTML
if (emailContent.includes('<html') || emailContent.includes('<body')) {
resultObj.html = emailContent;
} else {
// Convert plain text to HTML
resultObj.html = emailContent
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\n/g, '<br>');
}
console.log('[DEBUG] Fallback parsing generated simple result');
return NextResponse.json(resultObj);
} catch (fallbackError) {
console.error('[DEBUG] Even fallback parsing failed:', fallbackError);
throw parseError; // Throw the original error
}
}
} catch (error) {
console.error('[DEBUG] Parse-email API unhandled error:', error);
return NextResponse.json(
{ error: 'Failed to parse email', details: error instanceof Error ? error.message : 'Unknown error' },
{ status: 500 }
);
}
}