-
Notifications
You must be signed in to change notification settings - Fork 1
/
MailListener.js
109 lines (94 loc) · 3.48 KB
/
MailListener.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
const EventEmitter = require('events').EventEmitter;
const MailParser = require('mailparser').MailParser;
const Imap = require('imap');
class MailListener extends EventEmitter {
constructor(options) {
super(options);
this.fetchUnreadOnStart = options.fetchUnreadOnStart;
this.markSeen = options.markSeen;
this.imap = new Imap({
user: options.user,
password: options.password,
host: options.host,
port: options.port,
tls: options.tls
});
this.mailbox = options.mailbox || 'INBOX';
}
start() {
this.imap.once('ready', (err) => {
if (err) {
return this.emit('error', err);
} else {
this.emit('server:connected');
return this.imap.openBox(this.mailbox, false, (err) => {
if (err) {
return this.emit('error', err);
} else {
if (this.fetchUnreadOnStart) {
this._parseUnreadEmails();
}
return this.imap.on('mail', (id) => {
this.emit('mail:arrived', id);
return this._parseUnreadEmails();
});
}
});
}
});
return this.imap.connect();
}
stop() {
return this.imap.logout(() => {
return this.emit('server:disconnected');
});
}
_parseUnreadEmails() {
return this.imap.search(['UNSEEN'], (err, searchResults) => {
if (err) {
return this.emit('error', err);
} else {
if (Array.isArray(searchResults) && searchResults.length === 0) {
return;
}
const fetch = this.imap.fetch(searchResults, {
bodies: '',
markSeen: this.markSeen ? true : undefined,
});
return fetch.on('message', (msg, id) => {
const parser = new MailParser();
const email = {};
parser.on('error', (err) => {
this.emit('error', err);
});
parser.on('headers', headers => {
email.headers = headers;
});
parser.on('data', data => {
if (data.type === 'text') {
email.data = data;
email.data.uid = id;
this.emit('mail:parsed', email);
} else if (data.type === 'attachment') {
// TODO handle stream
data.release();
}
});
msg.on('body', function (stream, info) {
let buffer = '';
stream.on('data', function (chunk) {
return buffer += chunk;
});
return stream.once('end', function () {
return parser.write(buffer);
});
});
return msg.on('end', function () {
return parser.end();
});
});
}
});
};
}
module.exports = MailListener;