64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
import { simpleParser, ParsedMail, Attachment, HeaderValue, AddressObject } from 'mailparser';
|
|
import DOMPurify from 'dompurify';
|
|
|
|
// Create a window object for DOMPurify
|
|
const window = new JSDOM('').window;
|
|
const purify = DOMPurify(window);
|
|
|
|
// Check if we're in a browser environment
|
|
const isBrowser = typeof window !== 'undefined';
|
|
|
|
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 {
|
|
const response = await fetch('/api/parse-email', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ emailContent }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to parse email');
|
|
}
|
|
|
|
const data = await response.json();
|
|
return {
|
|
...data,
|
|
date: data.date ? new Date(data.date) : null
|
|
};
|
|
} catch (error) {
|
|
console.error('Error parsing email:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function cleanHtml(html: string): string {
|
|
try {
|
|
return purify.sanitize(html, {
|
|
ALLOWED_TAGS: ['p', 'br', 'div', 'span', 'a', 'img', 'strong', 'em', 'u', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
|
|
ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'style'],
|
|
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
|
|
});
|
|
} catch (error) {
|
|
console.error('Error cleaning HTML:', error);
|
|
return html;
|
|
}
|
|
}
|