119 lines
2.9 KiB
TypeScript
119 lines
2.9 KiB
TypeScript
'use client';
|
|
|
|
import DOMPurify from 'dompurify';
|
|
|
|
export interface ParsedEmail {
|
|
subject: string | null;
|
|
from: string | null;
|
|
to: string | null;
|
|
cc: string | null;
|
|
bcc: string | null;
|
|
date: Date | null;
|
|
html: string | null;
|
|
text: string | null;
|
|
attachments: Array<{
|
|
filename: string;
|
|
contentType: string;
|
|
size: number;
|
|
}>;
|
|
headers: Record<string, any>;
|
|
}
|
|
|
|
export async function decodeEmail(emailContent: string): Promise<ParsedEmail> {
|
|
try {
|
|
// Ensure the email content is properly formatted
|
|
const formattedContent = emailContent?.trim();
|
|
if (!formattedContent) {
|
|
return {
|
|
subject: null,
|
|
from: null,
|
|
to: null,
|
|
cc: null,
|
|
bcc: null,
|
|
date: null,
|
|
html: null,
|
|
text: 'No content available',
|
|
attachments: [],
|
|
headers: {}
|
|
};
|
|
}
|
|
|
|
const response = await fetch('/api/parse-email', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ email: formattedContent }),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
console.error('API Error:', data);
|
|
return {
|
|
subject: null,
|
|
from: null,
|
|
to: null,
|
|
cc: null,
|
|
bcc: null,
|
|
date: null,
|
|
html: null,
|
|
text: data.error || 'Failed to parse email',
|
|
attachments: [],
|
|
headers: {}
|
|
};
|
|
}
|
|
|
|
// If we have a successful response but no content
|
|
if (!data.html && !data.text) {
|
|
return {
|
|
...data,
|
|
date: data.date ? new Date(data.date) : null,
|
|
html: null,
|
|
text: 'No content available',
|
|
attachments: data.attachments || [],
|
|
headers: data.headers || {}
|
|
};
|
|
}
|
|
|
|
return {
|
|
...data,
|
|
date: data.date ? new Date(data.date) : null,
|
|
text: data.text || null,
|
|
html: data.html || null,
|
|
attachments: data.attachments || [],
|
|
headers: data.headers || {}
|
|
};
|
|
} catch (error) {
|
|
console.error('Error parsing email:', error);
|
|
return {
|
|
subject: null,
|
|
from: null,
|
|
to: null,
|
|
cc: null,
|
|
bcc: null,
|
|
date: null,
|
|
html: null,
|
|
text: 'Error parsing email content',
|
|
attachments: [],
|
|
headers: {}
|
|
};
|
|
}
|
|
}
|
|
|
|
export function cleanHtml(html: string): string {
|
|
try {
|
|
// Enhanced configuration to preserve more HTML elements for complex emails
|
|
return DOMPurify.sanitize(html, {
|
|
ADD_TAGS: ['style', 'meta', 'link', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'hr'],
|
|
ADD_ATTR: ['*', 'colspan', 'rowspan', 'cellpadding', 'cellspacing', 'border', 'bgcolor', 'width', 'height', 'align', 'valign', 'class', 'id', 'style'],
|
|
ALLOW_UNKNOWN_PROTOCOLS: true,
|
|
WHOLE_DOCUMENT: true,
|
|
KEEP_CONTENT: true,
|
|
RETURN_DOM: false
|
|
});
|
|
} catch (error) {
|
|
console.error('Error cleaning HTML:', error);
|
|
return html;
|
|
}
|
|
}
|