-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathemailUtils.js
More file actions
63 lines (54 loc) · 1.73 KB
/
Copy pathemailUtils.js
File metadata and controls
63 lines (54 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const imaps = require('imap-simple');
const simpleParser = require('mailparser').simpleParser;
const { JSDOM } = require('jsdom');
const { decode } = require('html-entities');
async function connectToImap(config) {
try {
const connection = await imaps.connect(config);
await connection.openBox('INBOX');
return connection;
} catch (error) {
throw new Error(`Failed to connect to IMAP: ${error.message}`);
}
}
async function fetchEmails(connection, searchCriteria, fetchOptions) {
try {
return await connection.search(searchCriteria, fetchOptions);
} catch (error) {
throw new Error(`Failed to fetch emails: ${error.message}`);
}
}
async function parseEmail(message) {
const fullMessage = message.parts.find(part => part.which === '');
const parsedEmail = await simpleParser(fullMessage.body);
let textContent = parsedEmail.text;
let htmlContent = parsedEmail.html;
let links = [];
if (htmlContent) {
const dom = new JSDOM(htmlContent);
textContent = dom.window.document.body.textContent || textContent;
links = [...new Set(Array.from(dom.window.document.querySelectorAll('a'))
.map(a => ({
text: a.textContent.trim() || "Link",
href: a.href.length > 50 ? `${a.href.substring(0, 47)}...` : a.href
})))];
}
return {
from: parsedEmail.from.text,
to: parsedEmail.to.text,
subject: parsedEmail.subject,
date: parsedEmail.date,
text: decode(textContent).trim(),
attachments: parsedEmail.attachments.map(att => ({
filename: att.filename,
contentType: att.contentType,
size: att.size
})),
links
};
}
module.exports = {
connectToImap,
fetchEmails,
parseEmail
};