ts-utils/src/email.ts
2024-11-26 16:06:50 +01:00

34 lines
880 B
TypeScript

/**
* Parses a raw email string into its constituent parts, including subject, headers, and body.
*
* @param emailText The raw email text to parse.
* @returns An object containing the extracted email components.
*/
export function parseEmail(emailText: string) {
const lines = emailText.split('\n');
const headers: { [key: string]: string } = {};
let bodyLines = [];
let isBody = false;
for (let line of lines) {
if (!isBody) {
if (line.trim() === '') {
isBody = true;
continue;
}
const colonIndex = line.indexOf(':');
if (colonIndex !== -1) {
const key = line.slice(0, colonIndex);
headers[key] = line.slice(colonIndex + 1).trim();
}
} else
bodyLines.push(line);
}
return {
subject: headers['Subject'] || 'No subject',
headers,
body: bodyLines.join('\n').trim()
};
}