forked from Nick-Triller/mail-sink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmtp-server.js
92 lines (82 loc) · 2.03 KB
/
smtp-server.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
var smtp = require("smtp-protocol");
var MailParser = require("mailparser").MailParser;
var fs = require("fs");
var path = require("path");
var mails = [];
var config;
function randomInt(low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
/**
* Processes a mail
* @param mail
*/
function process(parsed) {
mails.push(parsed);
// Log to console if enabled
if (!config.quiet) {
console.log(parsed.headers);
console.log(parsed.html || parsed.text);
console.log();
}
// Write to file if enabled
if (config.dump) {
var filename = new Date().getTime() +
"-" + randomInt(10000, 99999) + ".json";
var savePath = path.join(config.dump, filename);
var text = JSON.stringify(parsed, null, 2);
fs.writeFile(savePath, text, function (err) {
if (err) {
return console.log(err);
}
});
}
//trim list of emails if necessary
while (mails.length > config.maxEmails) {
mails.splice(1, 1);
}
}
/**
* Returs a new MailParser instance. Use a new instance for each email.
* @returns {*|MailParser} MailParser instance
*/
function getMailparser() {
var mailParser = new MailParser();
mailParser.on("end", process);
return mailParser;
}
function start() {
smtp.createServer(function (req) {
if (config.whitelist) {
req.on("from", function (from, ack) {
if (config.whitelist.length == 0 || config.whitelist.indexOf(from) !== -1)
ack.accept();
else ack.reject()
});
}
req.on("message", function (stream, ack) {
// New MailParser instance for each mail
var mailParser = getMailparser();
// Receive data
stream.on("data", function (d) {
mailParser.write(d);
});
// All data received
stream.on("end", function () {
mailParser.end("");
});
ack.accept();
});
}).listen(config.smtpPort);
}
module.exports = {
start: function () {
start()
},
getMails: function () {
return mails;
},
setConfig: function (configArg) {
config = configArg;
}
};