forked from jcreigno/nodejs-mail-notifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (84 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
88
89
90
91
92
/*jslint node: true, vars: true, indent: 4 */
'use strict';
var util = require('util'),
Imap = require('imap'),
MailParser = require('mailparser').MailParser,
EventEmitter = require('events').EventEmitter;
function Notifier(opts) {
EventEmitter.call(this);
var self = this;
self.options = opts;
if (self.options.username) { //backward compat
self.options.user = self.options.username;
}
self.connected = false;
self.imap = new Imap(opts);
self.imap.on('end', function () {
self.connected = false;
self.emit('end');
});
self.imap.on('error', function (err) {
self.emit('error', err);
});
}
util.inherits(Notifier, EventEmitter);
module.exports = function (opts) {
return new Notifier(opts);
};
Notifier.prototype.start = function () {
var self = this;
self.imap.once('ready', function () {
self.connected = true;
self.imap.openBox(self.options.box || 'INBOX', false, function () {
self.scan();
});
self.imap.on('mail', function (id) {
self.scan();
});
});
self.imap.connect();
return this;
};
Notifier.prototype.scan = function () {
var self = this;
self.imap.search(self.options.search || ['UNSEEN'], function (err, seachResults) {
if (err) {
self.emit('error', err);
}
if (!seachResults || seachResults.length === 0) {
util.log('no new mail in INBOX');
return;
}
var fetch = self.imap.fetch(seachResults, {
markSeen: self.options.markSeen !== false,
bodies: ''
});
fetch.on('message', function (msg) {
var mp = new MailParser();
mp.once('end', function (mail) {
self.emit('mail', mail);
});
msg.on('body', function (stream, info) {
stream.on('data', function (chunk) {
mp.write(chunk);
});
stream.once('end', function () {
mp.end();
});
});
});
fetch.once('end', function () {
util.log('Done fetching all messages!');
});
fetch.on('error', function () {
self.emit('error', err);
});
});
return this;
};
Notifier.prototype.stop = function () {
if (this.connected) {
this.imap.end();
}
return this;
};