-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsmtp.js
437 lines (328 loc) · 9.65 KB
/
smtp.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
var Util = require('util'),
OS = require('os'),
Net = require('net'),
Events = require('events'),
U = require('./util');
exports.createClient = createClient;
exports.Client = Client;
exports.BadReply = BadReply;
// ## Client ##
// An SMTP client connects to a server and maintains connection state.
function createClient(opt) {
return new Client(opt);
}
Util.inherits(Client, Events.EventEmitter);
function Client(opt) {
Events.EventEmitter.call(this);
this.options = opt;
this.timeout = opt.timeout || 0
if (!(this.host = (opt && opt.host)))
throw new Error('missing required host');
if (opt.secure || opt.username) {
this.useTLS = true;
if (typeof opt.secure == 'object')
this.credentials = opt.secure;
}
this.port = opt.port || (this.useTLS ? 587 : 25);
this.domain = opt.domain;
if (opt.username)
this.setLogin(opt.username, opt.password);
this.useSocket(new Net.Socket());
}
// Send a message.
Client.prototype.mail = function(from, to) {
var self = this;
this.domain = this.domain || OS.hostname();
process.nextTick(function() {
self.connect();
});
return new ClientTransaction(this, from, to);
};
// Connect to the mail server.
Client.prototype.connect = function() {
var self = this;
if (!this.domain)
this.emit('error', new Error('Missing required domain.'));
else if (this.sock.readyState != 'closed')
this.emit('error', new Error('Session already started.'));
else {
this.sock.setTimeout(this.timeout);
this.sock
.on('error', function(err) {
self.emit('error', err);
})
.on('timeout', function(err) {
self.emit('error', new Error('Conection timeout'));
})
.once('connect', function() {
self.reset(220);
})
.connect(this.port, this.host, function() {
self.sock.removeAllListeners('timeout');
});
}
return this;
};
// Stop listening to the mail server.
Client.prototype.clear = function() {
this.sock.removeAllListeners('data');
return this;
};
// Switch which socket is used (see starttls).
Client.prototype.useSocket = function(sock) {
this.sock = sock;
return this;
};
// ### Read Responses ###
// Reset client state, say hello.
Client.prototype.reset = function(wait) {
var self = this,
replies = [];
this.session = { use8BITMIME: undefined };
U.eachLine(this.sock, function(line) {
var probe;
if (!(probe = line.match(/^(\d{3})([\- ])(.*)/))) {
self.emit('error', new Error('Badly formatted reply: ' + Util.inspect(line)));
return;
}
U.debug('READ (((%s%s%s)))', probe[1], probe[2], probe[3]);
replies.push(new Reply(parseInt(probe[1]), probe[3]));
if (probe[2] == ' ') {
replies.unshift('reply');
self.emit.apply(self, replies);
replies.splice(0, replies.length);
}
});
wait ? this.withReply(wait, ehlo) : ehlo();
function ehlo() {
self.hello(function() {
self.emit('ready');
});
}
return this;
};
Client.prototype.withReply = function(code, callback) {
var self = this;
if (callback === undefined)
this.once('reply', code);
else
this.once('reply', function(reply) {
if (reply.code != code)
self.emit('error', new BadReply('Expected ' + code, reply));
else
callback.apply(this, arguments);
});
return this;
};
// ### Send Commands ##
// Write a line.
Client.prototype.puts = function(data) {
this.write(data + '\r\n');
return this;
};
// Write some data.
Client.prototype.write = function(data) {
try {
U.debug('SEND (((%s)))', data);
return this.sock.write(data);
} catch(e) {
this.emit('error', e);
}
};
// Write some final data, terminate the connection.
Client.prototype.end = function(data) {
U.debug('SEND (((%s)))', data);
return this.sock.end(data);
};
// Send a command called `name`.
Client.prototype.command = function(name, args, callback) {
var cmd = name.toUpperCase();
if (typeof args == 'string')
cmd += ' ' + args;
this.puts(cmd);
callback = callback || args;
if (typeof callback == 'function')
this.withReply(250, callback);
return this;
};
// ### Specific Commands ###
// Say hello to the server. The server replies with a list of
// extensions it supports. Process this list of extensions by calling
// methods named `smtpEXTENSION()`.
Client.prototype.hello = function(ready) {
var self = this;
self.command('ehlo', self.domain, function() {
U.aEach(arguments, extend, ready);
});
function extend(reply, index, next) {
var probe = reply.text.match(/^(\S+)\s*(.*)$/),
method = probe && self['smtp' + probe[1].toUpperCase()];
method ? method.call(self, next, probe[2]) : next();
}
return self;
};
Client.prototype.quit = function() {
this.end('QUIT\r\n');
return this;
};
// ### STARTTLS extension ###
// See: <http://tools.ietf.org/html/rfc3207>
Client.prototype.smtpSTARTTLS = function(next) {
var self = this;
if (!this.useTLS)
return next();
else
this.command('starttls').withReply(220, secure);
function secure() {
var clear = require('./starttls').starttls(self.clear().sock, false, function() {
if (!clear.authorized)
self.emit('error', new Error('STARTTLS: failed to secure stream'));
else {
self.secure = true;
self.useSocket(clear).reset();
}
});
}
return this;
};
// ### AUTH extension ###
// See: <http://www.faqs.org/rfcs/rfc2554.html>
Client.prototype.setLogin = function(username, password) {
this.username = username;
this.password = password;
return this;
};
Client.prototype.smtpAUTH = function(next, mechanisms) {
var names = mechanisms.toUpperCase().split(/\s+/),
method;
if (!this.username)
next();
else if (!this.secure && !this.options.insecureAuth)
self.emit('error', new Error('AUTH: stream is not secure (use `insecureAuth: true` to override).'));
else
for (var i = 0, l = names.length; i < l; i++) {
method = this['auth' + names[i]];
if (method) {
method.call(this, this.username, this.password, next);
break;
}
}
};
// #### LOGIN mechanism ####
// See: <http://www.fehcom.de/qmail/smtpauth.html#FRAMEWORK>
Client.prototype.authLOGIN = function(username, password, next) {
var self = this;
this.command('auth', 'login')
.withReply(334, sendUsername);
function sendUsername() {
self.puts(new Buffer(username).toString('base64'))
.withReply(334, sendPassword);
}
function sendPassword() {
self.puts(new Buffer(password).toString('base64'))
.withReply(235, next);
}
return this;
};
// ### 8BITMIME Extension ###
// Default to sending 8BITMIME even if the server doesn't advertise
// support for it. If the server does advertise support, add BODY to
// the `MAIL FROM` command.
//
// To require a 7BIT body, use the `mimeTransport: '7BIT` option.
//
// See: <http://cr.yp.to/smtp/8bitmime.html>, <http://tools.ietf.org/html/rfc6152>
Client.prototype.smtp8BITMIME = function(next) {
this.session.use8BITMIME = true;
next();
};
Client.prototype.mimeTransport = function() {
return this.session.use8BITMIME && (this.options.mimeTransport || '8BITMIME');
};
// Only require 7bit encoding if it's explicitly requested.
Client.prototype.require7Bit = function() {
return this.options.mimeTransport == '7BIT';
};
// ## Reply ##
// A reply encapsulates a single reply from the server (a status code
// and a message).
function Reply(code, text) {
this.code = code;
this.text = text;
}
Reply.prototype.toString = function() {
return this.code + ' ' + this.text;
};
Util.inherits(BadReply, Error);
function BadReply(reason, reply) {
Error.call(this, reason);
this.reply = reply;
};
BadReply.prototype.toString = function() {
return this.message + ': ' + this.reply.toString();
};
// ## ClientTransaction ##
// Transmit a message envelope, then notify the caller with a `ready`
// event. The caller can then use `write()` or `end()` to transmit a
// message body.
Util.inherits(ClientTransaction, Events.EventEmitter);
function ClientTransaction(client, from, to) {
Events.EventEmitter.call(this);
var self = this;
this.client = client;
this.done = false;
this.newline = true;
client.once('ready', sendFrom);
function sendFrom() {
var transport = client.mimeTransport(),
args = '<' + from + '>' + (transport ? ' BODY=' + transport : '');
client.command('mail from:', args, function() {
U.aEach(to, sendTo, data);
});
}
function sendTo(mailbox, index, next) {
client.command('rcpt to:', '<' + mailbox + '>', next);
}
function data() {
client.command('data').withReply(354, ready);
}
function ready() {
self.emit('ready');
}
}
Object.defineProperty(ClientTransaction.prototype, 'session', {
get: function() {
return this.client.session;
}
});
ClientTransaction.prototype.write = function(data) {
if (this.done) {
this.client.emit('error', new Error('The transaction has ended.'));
return this;
}
else if (this.client.require7Bit() && !U.is7Bit(data)) {
this.client.emit('error', new Error('Data must be 7-bit ASCII.'));
return this;
}
this.client.write(U.stuffDots(data, this.newline));
this.newline = /\n$/.test(data);
return this;
};
ClientTransaction.prototype.puts = function(data) {
return this.write(data + '\r\n');
};
ClientTransaction.prototype.end = function(data) {
var self = this;
if (this.done)
throw new Error('The transaction has ended.');
if (data !== undefined)
this.write(data);
if (!this.newline)
this.client.write('\r\n');
this.client.write('.\r\n');
this.done = true;
this.client.withReply(250, function() {
self.emit('end');
});
return this;
};