40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import { sanitizeHtml } from '@/lib/utils/email-formatter';
|
|
import { simpleParser } from 'mailparser';
|
|
|
|
function getAddressText(addresses: any): string | null {
|
|
if (!addresses) return null;
|
|
|
|
try {
|
|
if (Array.isArray(addresses)) {
|
|
return addresses.map(a => a.address || '').join(', ');
|
|
} else if (typeof addresses === 'object') {
|
|
return addresses.address || null;
|
|
}
|
|
return null;
|
|
} catch (error) {
|
|
console.error('Error formatting addresses:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function parseEmail(emailContent: string) {
|
|
try {
|
|
const parsed = await simpleParser(emailContent);
|
|
|
|
return {
|
|
subject: parsed.subject || null,
|
|
from: getAddressText(parsed.from),
|
|
to: getAddressText(parsed.to),
|
|
cc: getAddressText(parsed.cc),
|
|
bcc: getAddressText(parsed.bcc),
|
|
date: parsed.date || null,
|
|
html: parsed.html ? sanitizeHtml(parsed.html as string) : null,
|
|
text: parsed.text || null,
|
|
attachments: parsed.attachments || [],
|
|
headers: Object.fromEntries(parsed.headers)
|
|
};
|
|
} catch (error) {
|
|
console.error('Error parsing email:', error);
|
|
throw error;
|
|
}
|
|
}
|