-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (73 loc) · 2.42 KB
/
index.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
const Imap = require('imap')
const { simpleParser } = require('mailparser');
const nodemailer = require('nodemailer')
require('dotenv').config()
const AUTO_REPLY_ADDRESS = '[email protected]'
function sendEmail(recipientEmails = [], subject, body) {
console.log(`Auto replying to ${recipientEmails}`)
// for you to implement
}
function manageInbox() {
const imap = new Imap({
user: process.env.GMAIL_USER,
password: process.env.GMAIL_PASSWORD,
host: 'imap.gmail.com',
port: 993,
tls: true,
tlsOptions: { servername: 'imap.gmail.com' }
});
function getEmail(start, number) {
console.log(`Getting email from seq: ${start}:${start + number}`)
const f = imap.seq.fetch(`${start}:${start + number}`, {
bodies: '',
struct: true
});
f.on('message', function (msg, seqno) {
const prefix = '#' + seqno;
msg.on('body', stream => {
simpleParser(stream, async (err, parsed) => {
const { from, to, subject, date, textAsHtml, text } = parsed;
console.log("-------------------");
console.log("Email No. %s", prefix)
console.log({ from: from.value[0], to: to.value, subject, date, textAsHtml, text });
console.log("-------------------");
if (from.value[0].address == AUTO_REPLY_ADDRESS) {
sendEmail([from.value[0].address], `Re: ${subject}`, `Noted with thanks.\nRight on it, boss!\n\nHave a great day,\n${process.env.YOUR_NAME}`)
}
});
});
});
}
imap.once('error', function (err) {
console.log(`Error: ${err}`);
});
imap.once('end', function () {
console.log('Connection ended');
});
imap.on('ready', () => {
imap.openBox('INBOX', true, (err, box) => {
if (err) console.log(err)
else console.log('Recipient is ready for accepting')
})
})
let numberOfEmails = 0
function processIncomingEmail(number) {
if (numberOfEmails == 0) {
console.log(`Current number of emails in inbox: ${number}`)
numberOfEmails = number
} else {
getEmail(numberOfEmails + 1, number - 1)
numberOfEmails += number
console.log(`Number of emails updated to ${numberOfEmails}`)
}
}
imap.on('expunge', number => {
if (number <= numberOfEmails) {
console.log(`Email #${number} was deleted`)
numberOfEmails -= 1
console.log(`Number of emails updated to ${numberOfEmails}`)
}
})
imap.connect();
}
manageInbox()