-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifier.js
114 lines (91 loc) · 2.51 KB
/
notifier.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const Imap = require('imap');
const { simpleParser } = require('mailparser');
// Your email credentials
const EMAIL = process.env.EMAIL;
const PASSWORD = process.env.PASSWORD;
// IMAP server and port
const IMAP_SERVER = 'imap.gmail.com';
const IMAP_PORT = 993;
const imap = new Imap({
user: EMAIL,
password: PASSWORD,
host: IMAP_SERVER,
port: IMAP_PORT,
tls: true,
tlsOptions: {
rejectUnauthorized: false
}
});
let seenEmails = {}; // Dictionary to store seen email UIDs
function openInbox(callback) {
imap.openBox('INBOX', false, callback);
}
function processEmail(rawEmail, uid) {
if (seenEmails[uid]) {
return;
}
seenEmails[uid] = true;
simpleParser(rawEmail)
.then(parsedEmail => {
console.log('New Email: ', parsedEmail.subject);
})
.catch(err => {
console.error('Error parsing email:', err);
});
}
function fetchUnseenEmails() {
imap.search(['UNSEEN'], (err, results) => {
if (err) {
console.error('Error searching for unseen emails:', err);
return;
}
if (!results.length) {
console.log('No new emails');
return;
}
const fetch = imap.fetch(results, { bodies: ['HEADER.FIELDS (SUBJECT)'], struct: true });
fetch.on('message', (msg, seqno) => {
let rawEmail = '';
let uid;
msg.on('attributes', attrs => {
uid = attrs.uid;
});
msg.on('body', (stream, info) => {
stream.on('data', chunk => {
rawEmail += chunk.toString('utf8');
});
});
msg.on('end', () => {
processEmail(rawEmail, uid);
});
});
fetch.on('error', err => {
console.error('Error fetching emails:', err);
});
fetch.on('end', () => {
//console.log('Finished fetching emails');
imap.once('idle', () => {
fetchUnseenEmails();
});
});
});
}
imap.on('ready', () => {
openInbox((err, box) => {
if (err) {
console.error('Error opening inbox:', err);
return;
}
fetchUnseenEmails();
imap.on('mail', mail => {
fetchUnseenEmails();
});
});
});
imap.on('error', err => {
console.error('IMAP error:', err);
});
imap.on('end', () => {
console.log('IMAP connection ended');
});
imap.connect();