70 lines
2.2 KiB
TypeScript
70 lines
2.2 KiB
TypeScript
import { simpleParser, ParsedMail, Attachment, HeaderValue, AddressObject } from 'mailparser';
|
|
import DOMPurify from 'dompurify';
|
|
import { JSDOM } from 'jsdom';
|
|
|
|
// 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: Attachment[];
|
|
headers: Record<string, HeaderValue>;
|
|
}
|
|
|
|
function getAddressText(address: AddressObject | AddressObject[] | undefined): string | null {
|
|
if (!address) return null;
|
|
if (Array.isArray(address)) {
|
|
return address.map(addr => addr.value?.[0]?.address || '').filter(Boolean).join(', ');
|
|
}
|
|
return address.value?.[0]?.address || null;
|
|
}
|
|
|
|
export async function decodeEmail(emailContent: string): Promise<ParsedEmail> {
|
|
if (isBrowser) {
|
|
throw new Error('decodeEmail can only be used on the server side');
|
|
}
|
|
|
|
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 ? cleanHtml(parsed.html) : null,
|
|
text: parsed.text || null,
|
|
attachments: parsed.attachments || [],
|
|
headers: Object.fromEntries(parsed.headers)
|
|
};
|
|
} 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;
|
|
}
|
|
}
|