emailjs 1.0.11 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/smtp/message.js CHANGED
@@ -1,628 +1,737 @@
1
- var stream = require('stream');
2
- var util = require('util');
3
- var fs = require('fs');
4
- var os = require('os');
5
- var path = require('path');
6
- var moment = require('moment');
7
- var mimelib = require('mimelib');
8
- var addressparser = require('addressparser');
9
- var CRLF = "\r\n";
10
- var MIMECHUNK = 76; // MIME standard wants 76 char chunks when sending out.
11
- var BASE64CHUNK= 24; // BASE64 bits needed before padding is used
12
- var MIME64CHUNK= MIMECHUNK * 6; // meets both base64 and mime divisibility
13
- var BUFFERSIZE = MIMECHUNK*24*7; // size of the message stream buffer
14
- var counter = 0;
15
-
16
- // support for nodejs without Buffer.concat native function
17
- if(!Buffer.concat)
18
- {
19
- require("bufferjs/concat");
1
+ const fs = require('fs');
2
+ const { hostname } = require('os');
3
+ const { Stream } = require('stream');
4
+ const addressparser = require('addressparser');
5
+ const { mimeWordEncode } = require('emailjs-mime-codec');
6
+ const { getRFC2822Date } = require('./date');
7
+
8
+ const CRLF = '\r\n';
9
+
10
+ /**
11
+ * MIME standard wants 76 char chunks when sending out.
12
+ * @type {76}
13
+ */
14
+ const MIMECHUNK = 76;
15
+
16
+ /**
17
+ * meets both base64 and mime divisibility
18
+ * @type {456}
19
+ */
20
+ const MIME64CHUNK = /** @type {456} */ (MIMECHUNK * 6);
21
+
22
+ /**
23
+ * size of the message stream buffer
24
+ * @type {12768}
25
+ */
26
+ const BUFFERSIZE = /** @type {12768} */ (MIMECHUNK * 24 * 7);
27
+
28
+ /**
29
+ * @type {number}
30
+ */
31
+ let counter = 0;
32
+
33
+ /**
34
+ * @returns {string} the generated boundary
35
+ */
36
+ function generate_boundary() {
37
+ let text = '';
38
+ const possible =
39
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'()+_,-./:=?";
40
+
41
+ for (let i = 0; i < 69; i++) {
42
+ text += possible.charAt(Math.floor(Math.random() * possible.length));
43
+ }
44
+
45
+ return text;
20
46
  }
21
47
 
22
- var generate_boundary = function()
23
- {
24
- var text = "";
25
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'()+_,-./:=?";
26
-
27
- for(var i=0; i < 69; i++)
28
- text += possible.charAt(Math.floor(Math.random() * possible.length));
48
+ /**
49
+ * @param {string} l the person to parse into an address
50
+ * @returns {string} the parsed address
51
+ */
52
+ function person2address(l) {
53
+ return addressparser(l)
54
+ .map(({ name, address }) => {
55
+ return name
56
+ ? `${mimeWordEncode(name).replace(/,/g, '=2C')} <${address}>`
57
+ : address;
58
+ })
59
+ .join(', ');
60
+ }
29
61
 
30
- return text;
31
- };
62
+ /**
63
+ * @param {string} header_name the header name to fix
64
+ * @returns {string} the fixed header name
65
+ */
66
+ function fix_header_name_case(header_name) {
67
+ return header_name
68
+ .toLowerCase()
69
+ .replace(/^(.)|-(.)/g, match => match.toUpperCase());
70
+ }
32
71
 
33
- function person2address(l)
34
- {
35
- var addresses = addressparser(l);
36
- return addresses.map(function(addr) {
37
- return addr.name ? mimelib.encodeMimeWord(addr.name, 'Q', 'utf-8').replace(/,/g, '=2C') + ' ' + '<' + addr.address + '>' : addr.address;
38
- }).join(', ');
72
+ class Message {
73
+ /**
74
+ * @typedef {Object} MessageHeaders
75
+ * @property {string?} content-type
76
+ * @property {string} [subject]
77
+ * @property {string} [text]
78
+ * @property {MessageAttachment} [attachment]
79
+ * @param {MessageHeaders} headers hash of message headers
80
+ */
81
+ constructor(headers) {
82
+ this.attachments = [];
83
+
84
+ /**
85
+ * @type {MessageAttachment}
86
+ */
87
+ this.alternative = null;
88
+ this.header = {
89
+ 'message-id': `<${new Date().getTime()}.${counter++}.${
90
+ process.pid
91
+ }@${hostname()}>`,
92
+ date: getRFC2822Date(),
93
+ };
94
+
95
+ this.content = 'text/plain; charset=utf-8';
96
+ for (const header in headers) {
97
+ // allow user to override default content-type to override charset or send a single non-text message
98
+ if (/^content-type$/i.test(header)) {
99
+ this.content = headers[header];
100
+ } else if (header === 'text') {
101
+ this.text = headers[header];
102
+ } else if (
103
+ header === 'attachment' &&
104
+ typeof headers[header] === 'object'
105
+ ) {
106
+ const attachment = headers[header];
107
+ if (Array.isArray(attachment)) {
108
+ for (let i = 0; i < attachment.length; i++) {
109
+ this.attach(attachment[i]);
110
+ }
111
+ } else {
112
+ this.attach(attachment);
113
+ }
114
+ } else if (header === 'subject') {
115
+ this.header.subject = mimeWordEncode(headers.subject);
116
+ } else if (/^(cc|bcc|to|from)/i.test(header)) {
117
+ this.header[header.toLowerCase()] = person2address(headers[header]);
118
+ } else {
119
+ // allow any headers the user wants to set??
120
+ // if(/cc|bcc|to|from|reply-to|sender|subject|date|message-id/i.test(header))
121
+ this.header[header.toLowerCase()] = headers[header];
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * @param {MessageAttachment} options attachment options
128
+ * @returns {Message} the current instance for chaining
129
+ */
130
+ attach(options) {
131
+ /*
132
+ legacy support, will remove eventually...
133
+ arguments -> (path, type, name, headers)
134
+ */
135
+ if (typeof options === 'string' && arguments.length > 1) {
136
+ options = {
137
+ path: options,
138
+ type: arguments[1],
139
+ name: arguments[2],
140
+ };
141
+ }
142
+
143
+ // sender can specify an attachment as an alternative
144
+ if (options.alternative) {
145
+ this.alternative = options;
146
+ this.alternative.charset = options.charset || 'utf-8';
147
+ this.alternative.type = options.type || 'text/html';
148
+ this.alternative.inline = true;
149
+ } else {
150
+ this.attachments.push(options);
151
+ }
152
+
153
+ return this;
154
+ }
155
+
156
+ /**
157
+ * legacy support, will remove eventually...
158
+ * should use Message.attach() instead
159
+ * @param {string} html html data
160
+ * @param {string} [charset='utf-8'] the charset to encode as
161
+ * @returns {Message} the current Message instance
162
+ */
163
+ attach_alternative(html, charset) {
164
+ this.alternative = {
165
+ data: html,
166
+ charset: charset || 'utf-8',
167
+ type: 'text/html',
168
+ inline: true,
169
+ };
170
+
171
+ return this;
172
+ }
173
+
174
+ /**
175
+ * @param {function(boolean, string): void} callback This callback is displayed as part of the Requester class.
176
+ * @returns {void}
177
+ */
178
+ valid(callback) {
179
+ if (!this.header.from) {
180
+ callback(false, 'message does not have a valid sender');
181
+ }
182
+
183
+ if (!(this.header.to || this.header.cc || this.header.bcc)) {
184
+ callback(false, 'message does not have a valid recipient');
185
+ } else if (this.attachments.length === 0) {
186
+ callback(true, undefined);
187
+ } else {
188
+ const failed = [];
189
+
190
+ this.attachments.forEach(attachment => {
191
+ if (attachment.path) {
192
+ if (fs.existsSync(attachment.path) == false) {
193
+ failed.push(`${attachment.path} does not exist`);
194
+ }
195
+ } else if (attachment.stream) {
196
+ if (!attachment.stream.readable) {
197
+ failed.push('attachment stream is not readable');
198
+ }
199
+ } else if (!attachment.data) {
200
+ failed.push('attachment has no data associated with it');
201
+ }
202
+ });
203
+
204
+ callback(failed.length === 0, failed.join(', '));
205
+ }
206
+ }
207
+
208
+ /**
209
+ * returns a stream of the current message
210
+ * @returns {MessageStream} a stream of the current message
211
+ */
212
+ stream() {
213
+ return new MessageStream(this);
214
+ }
215
+
216
+ /**
217
+ * @param {function(Error, string): void} callback the function to call with the error and buffer
218
+ * @returns {void}
219
+ */
220
+ read(callback) {
221
+ let buffer = '';
222
+ const str = this.stream();
223
+ str.on('data', data => (buffer += data));
224
+ str.on('end', err => callback(err, buffer));
225
+ str.on('error', err => callback(err, buffer));
226
+ }
39
227
  }
40
228
 
41
- var fix_header_name_case = function(header_name) {
42
- return header_name.toLowerCase().replace(/^(.)|-(.)/g, function(match) {
43
- return match.toUpperCase();
44
- });
45
- };
46
-
47
- var Message = function(headers)
48
- {
49
- this.attachments = [];
50
- this.alternative = null;
51
- var now = new Date();
52
- this.header = {
53
- "message-id":"<" + now.getTime() + "." + (counter++) + "." + process.pid + "@" + os.hostname() +">",
54
- "date":moment().locale('en').format("ddd, DD MMM YYYY HH:mm:ss ZZ")
55
- };
56
- this.content = "text/plain; charset=utf-8";
57
-
58
- for(var header in headers)
59
- {
60
- // allow user to override default content-type to override charset or send a single non-text message
61
- if(/^content-type$/i.test(header))
62
- {
63
- this.content = headers[header];
64
- }
65
- else if(header == 'text')
66
- {
67
- this.text = headers[header];
68
- }
69
- else if(header == "attachment" && typeof (headers[header]) == "object")
70
- {
71
- if(Array.isArray(headers[header])) {
72
- var that = this;
73
-
74
- for (var i = 0, l = headers[header].length; i < l; i++) {
75
- this.attach(headers[header][i]);
76
- }
77
- } else {
78
- this.attach(headers[header]);
79
- }
80
- }
81
- else if(header == 'subject')
82
- {
83
- this.header.subject = mimelib.encodeMimeWord(headers.subject, 'Q', 'utf-8');
84
- }
85
- else if(/^(cc|bcc|to|from)/i.test(header))
86
- {
87
- this.header[header.toLowerCase()] = person2address(headers[header]);
88
- }
89
- else
90
- {
91
- // allow any headers the user wants to set??
92
- // if(/cc|bcc|to|from|reply-to|sender|subject|date|message-id/i.test(header))
93
- this.header[header.toLowerCase()] = headers[header];
94
- }
95
- }
96
- };
97
-
98
- Message.prototype =
99
- {
100
- attach: function(options)
101
- {
102
- /*
103
- legacy support, will remove eventually...
104
- arguments -> (path, type, name, headers)
105
- */
106
- if (arguments.length > 1)
107
- options = {path:options, type:arguments[1], name:arguments[2]};
108
-
109
- // sender can specify an attachment as an alternative
110
- if(options.alternative)
111
- {
112
- this.alternative = options;
113
- this.alternative.charset = options.charset || "utf-8";
114
- this.alternative.type = options.type || "text/html";
115
- this.alternative.inline = true;
116
- }
117
- else
118
- this.attachments.push(options);
119
-
120
- return this;
121
- },
122
-
123
- /*
124
- legacy support, will remove eventually...
125
- should use Message.attach() instead
126
- */
127
- attach_alternative: function(html, charset)
128
- {
129
- this.alternative =
130
- {
131
- data: html,
132
- charset: charset || "utf-8",
133
- type: "text/html",
134
- inline: true
135
- };
136
-
137
- return this;
138
- },
139
-
140
- valid: function(callback)
141
- {
142
- var self = this;
143
-
144
- if(!self.header.from)
145
- {
146
- callback(false, "message does not have a valid sender");
147
- }
148
- if(!(self.header.to || self.header.cc || self.header.bcc))
149
- {
150
- callback(false, "message does not have a valid recipient");
151
- }
152
- else if(self.attachments.length === 0)
153
- {
154
- callback(true);
155
- }
156
- else
157
- {
158
- var check = [];
159
- var failed = [];
160
-
161
- self.attachments.forEach(function(attachment, index)
162
- {
163
- if(attachment.path)
164
- {
165
- // migrating path->fs for existsSync)
166
- if(!(fs.existsSync || path.existsSync)(attachment.path))
167
- failed.push(attachment.path + " does not exist");
168
- }
169
- else if(attachment.stream)
170
- {
171
- if(!attachment.stream.readable)
172
- failed.push("attachment stream is not readable");
173
- }
174
- else if(!attachment.data)
175
- {
176
- failed.push("attachment has no data associated with it");
177
- }
178
- });
179
-
180
- callback(failed.length === 0, failed.join(", "));
181
- }
182
- },
183
-
184
- stream: function()
185
- {
186
- return new MessageStream(this);
187
- },
188
-
189
- read: function(callback)
190
- {
191
- var buffer = "";
192
-
193
- var capture = function(data)
194
- {
195
- buffer += data;
196
- };
197
-
198
- var output = function(err)
199
- {
200
- callback(err, buffer);
201
- };
202
-
203
- var str = this.stream();
204
-
205
- str.on('data', capture);
206
- str.on('end', output);
207
- str.on('error', output);
208
- }
209
- };
210
-
211
- var MessageStream = function(message)
212
- {
213
- var self = this;
214
-
215
- stream.Stream.call(self);
216
-
217
- self.message = message;
218
- self.readable = true;
219
- self.paused = false;
220
- self.buffer = new Buffer(MIMECHUNK*24*7);
221
- self.bufferIndex = 0;
222
-
223
- var output_process = function(next, args)
224
- {
225
- if(self.paused)
226
- {
227
- self.resumed = function() { next.apply(null, args); };
228
- }
229
- else
230
- {
231
- next.apply(null, args);
232
- }
233
-
234
- next.apply(null, args);
235
- };
236
-
237
- var output_mixed = function()
238
- {
239
- var boundary = generate_boundary();
240
- var data = ["Content-Type: multipart/mixed; boundary=\"", boundary, "\"", CRLF, CRLF, "--", boundary, CRLF];
241
-
242
- output(data.join(''));
243
-
244
- if(!self.message.alternative)
245
- {
246
- output_text(self.message);
247
- output_message(boundary, self.message.attachments, 0, close);
248
- }
249
- else
250
- {
251
- output_alternative(self.message, function() { output_message(boundary, self.message.attachments, 0, close); });
252
- }
253
- };
254
-
255
- var output_message = function(boundary, list, index, callback)
256
- {
257
- if(index < list.length)
258
- {
259
- output(["--", boundary, CRLF].join(''));
260
-
261
- if(list[index].related)
262
- {
263
- output_related(list[index], function() { output_message(boundary, list, index + 1, callback); });
264
- }
265
- else
266
- {
267
- output_attachment(list[index], function() { output_message(boundary, list, index + 1, callback); });
268
- }
269
- }
270
- else
271
- {
272
- output([CRLF, "--", boundary, "--", CRLF, CRLF].join(''));
273
- callback();
274
- }
275
- };
276
-
277
- var output_attachment_headers = function(attachment)
278
- {
279
- var data = [],
280
- header,
281
- headers =
282
- {
283
- 'content-type': attachment.type +
284
- (attachment.charset ? "; charset=" + attachment.charset : "") +
285
- (attachment.method ? "; method=" + attachment.method : ""),
286
- 'content-transfer-encoding': 'base64',
287
- 'content-disposition': attachment.inline ? 'inline' : 'attachment; filename="' + mimelib.encodeMimeWord(attachment.name, 'Q', 'utf-8') + '"'
288
- };
289
-
290
- for(header in (attachment.headers || {}))
291
- {
292
- // allow sender to override default headers
293
- headers[header.toLowerCase()] = attachment.headers[header];
294
- }
295
-
296
- for(header in headers)
297
- {
298
- data = data.concat([fix_header_name_case(header), ': ', headers[header], CRLF]);
299
- }
300
-
301
- output(data.concat([CRLF]).join(''));
302
- };
303
-
304
- var output_attachment = function(attachment, callback)
305
- {
306
- var build = attachment.path ? output_file : attachment.stream ? output_stream : output_data;
307
- output_attachment_headers(attachment);
308
- build(attachment, callback);
309
- };
310
-
311
- var output_data = function(attachment, callback)
312
- {
313
- output_base64(attachment.encoded ? attachment.data : new Buffer(attachment.data).toString("base64"), callback);
314
- };
315
-
316
- var output_file = function(attachment, next)
317
- {
318
- var chunk = MIME64CHUNK*16;
319
- var buffer = new Buffer(chunk);
320
- var closed = function(fd) { if(fs.close) { fs.close(fd); } };
321
- var opened = function(err, fd)
322
- {
323
- if(!err)
324
- {
325
- var read = function(err, bytes)
326
- {
327
- if(!err && self.readable)
328
- {
329
- var encoding = attachment && attachment.headers ? attachment.headers['content-transfer-encoding'] || 'base64' : 'base64';
330
-
331
- if (encoding === 'ascii' || encoding === '7bit') {
332
- encoding = 'ascii';
333
- } else if(encoding === 'binary' || encoding === '8bit') {
334
- encoding = 'binary';
335
- } else {
336
- encoding = 'base64';
337
- }
338
-
339
- // guaranteed to be encoded without padding unless it is our last read
340
- output_base64(buffer.toString(encoding, 0, bytes), function()
341
- {
342
- if(bytes == chunk) // we read a full chunk, there might be more
343
- {
344
- fs.read(fd, buffer, 0, chunk, null, read);
345
- }
346
- else // that was the last chunk, we are done reading the file
347
- {
348
- self.removeListener("error", closed);
349
- fs.close(fd, next);
350
- }
351
- });
352
- }
353
- else
354
- {
355
- self.emit('error', err || {message:"message stream was interrupted somehow!"});
356
- }
357
- };
358
-
359
- fs.read(fd, buffer, 0, chunk, null, read);
360
- self.once("error", closed);
361
- }
362
- else
363
- self.emit('error', err);
364
- };
365
-
366
- fs.open(attachment.path, 'r', opened);
367
- };
368
-
369
- var output_stream = function(attachment, callback)
370
- {
371
- if(attachment.stream.readable)
372
- {
373
- var previous = null;
374
-
375
- attachment.stream.resume();
376
- attachment.stream.on('end', function()
377
- {
378
- output_base64((previous || new Buffer(0)).toString("base64"), callback);
379
- self.removeListener('pause', attachment.stream.pause);
380
- self.removeListener('resume', attachment.stream.resume);
381
- self.removeListener('error', attachment.stream.resume);
382
- });
383
-
384
- attachment.stream.on('data', function(buffer)
385
- {
386
- // do we have bytes from a previous stream data event?
387
- if(previous)
388
- {
389
- var buffer2 = Buffer.concat([previous, buffer]);
390
- previous = null; // free up the buffer
391
- buffer = null; // free up the buffer
392
- buffer = buffer2;
393
- }
394
-
395
- var padded = buffer.length % (MIME64CHUNK);
396
-
397
- // encode as much of the buffer to base64 without empty bytes
398
- if(padded)
399
- {
400
- previous = new Buffer(padded);
401
- // copy dangling bytes into previous buffer
402
- buffer.copy(previous, 0, buffer.length - padded);
403
- }
404
-
405
- output_base64(buffer.toString("base64", 0, buffer.length - padded));
406
- });
407
-
408
- self.on('pause', attachment.stream.pause);
409
- self.on('resume', attachment.stream.resume);
410
- self.on('error', attachment.stream.resume);
411
- }
412
- else
413
- self.emit('error', {message:"stream not readable"});
414
- };
415
-
416
- var output_base64 = function(data, callback)
417
- {
418
- var loops = Math.ceil(data.length / MIMECHUNK);
419
- var loop = 0;
420
-
421
- while(loop < loops)
422
- {
423
- output(data.substring(MIMECHUNK * loop, MIMECHUNK * (loop + 1)) + CRLF);
424
- loop++;
425
- }
426
-
427
- if(callback)
428
- callback();
429
- };
430
-
431
- var output_text = function(message)
432
- {
433
- var data = [];
434
-
435
- data = data.concat(["Content-Type:", message.content, CRLF, "Content-Transfer-Encoding: 7bit", CRLF]);
436
- data = data.concat(["Content-Disposition: inline", CRLF, CRLF]);
437
- data = data.concat([message.text || "", CRLF, CRLF]);
438
-
439
- output(data.join(''));
440
- };
441
-
442
- var output_alternative = function(message, callback)
443
- {
444
- var data = [], boundary = generate_boundary();
445
-
446
- data = data.concat(["Content-Type: multipart/alternative; boundary=\"", boundary, "\"", CRLF, CRLF]);
447
- data = data.concat(["--", boundary, CRLF]);
448
-
449
- output(data.join(''));
450
- output_text(message);
451
- output(["--", boundary, CRLF].join(''));
452
-
453
- var finish = function()
454
- {
455
- output([CRLF, "--", boundary, "--", CRLF, CRLF].join(''));
456
- callback();
457
- };
458
-
459
- if(message.alternative.related)
460
- {
461
- output_related(message.alternative, finish);
462
- }
463
- else
464
- {
465
- output_attachment(message.alternative, finish);
466
- }
467
- };
468
-
469
- var output_related = function(message, callback)
470
- {
471
- var data = [], boundary = generate_boundary();
472
-
473
- data = data.concat(["Content-Type: multipart/related; boundary=\"", boundary, "\"", CRLF, CRLF]);
474
- data = data.concat(["--", boundary, CRLF]);
475
-
476
- output(data.join(''));
477
-
478
- output_attachment(message, function()
479
- {
480
- output_message(boundary, message.related, 0, function()
481
- {
482
- output([CRLF, "--", boundary, "--", CRLF, CRLF].join(''));
483
- callback();
484
- });
485
- });
486
- };
487
-
488
- var output_header_data = function()
489
- {
490
- if(self.message.attachments.length || self.message.alternative)
491
- {
492
- output("MIME-Version: 1.0" + CRLF);
493
- output_mixed();
494
- }
495
- else // you only have a text message!
496
- {
497
- output_text(self.message);
498
- close();
499
- }
500
- };
501
-
502
- var output_header = function()
503
- {
504
- var data = [];
505
-
506
- for(var header in self.message.header)
507
- {
508
- // do not output BCC in the headers (regex) nor custom Object.prototype functions...
509
- if(!(/bcc/i.test(header)) && self.message.header.hasOwnProperty (header))
510
- data = data.concat([fix_header_name_case(header), ": ", self.message.header[header], CRLF]);
511
- }
512
-
513
- output(data.join(''));
514
- output_header_data();
515
- };
516
-
517
- var output = function(data, callback, args)
518
- {
519
- var bytes = Buffer.byteLength(data);
520
-
521
- // can we buffer the data?
522
- if(bytes + self.bufferIndex < self.buffer.length)
523
- {
524
- self.buffer.write(data, self.bufferIndex);
525
- self.bufferIndex += bytes;
526
-
527
- if(callback)
528
- callback.apply(null, args);
529
- }
530
- // we can't buffer the data, so ship it out!
531
- else if(bytes > self.buffer.length)
532
- {
533
- if(self.bufferIndex)
534
- {
535
- self.emit('data', self.buffer.toString("utf-8", 0, self.bufferIndex));
536
- self.bufferIndex = 0;
537
- }
538
-
539
- var loops = Math.ceil(data.length / self.buffer.length);
540
- var loop = 0;
541
-
542
- while(loop < loops)
543
- {
544
- self.emit('data', data.substring(self.buffer.length*loop, self.buffer.length*(loop + 1)));
545
- loop++;
546
- }
547
- }
548
- else // we need to clean out the buffer, it is getting full
549
- {
550
- if(!self.paused)
551
- {
552
- self.emit('data', self.buffer.toString("utf-8", 0, self.bufferIndex));
553
- self.buffer.write(data, 0);
554
- self.bufferIndex = bytes;
555
-
556
- // we could get paused after emitting data...
557
- if(self.paused)
558
- {
559
- self.once("resume", function() { callback.apply(null, args); });
560
- }
561
- else if(callback)
562
- {
563
- callback.apply(null, args);
564
- }
565
- }
566
- else // we can't empty out the buffer, so let's wait till we resume before adding to it
567
- {
568
- self.once("resume", function() { output(data, callback, args); });
569
- }
570
- }
571
- };
572
-
573
- var close = function(err)
574
- {
575
- if(err)
576
- {
577
- self.emit("error", err);
578
- }
579
- else
580
- {
581
- self.emit('data', self.buffer.toString("utf-8", 0, self.bufferIndex));
582
- self.emit('end');
583
- }
584
-
585
- self.buffer = null;
586
- self.bufferIndex = 0;
587
- self.readable = false;
588
- self.removeAllListeners("resume");
589
- self.removeAllListeners("pause");
590
- self.removeAllListeners("error");
591
- self.removeAllListeners("data");
592
- self.removeAllListeners("end");
593
- };
594
-
595
- self.once("destroy", close);
596
- process.nextTick(output_header);
597
- };
598
-
599
- util.inherits(MessageStream, stream.Stream);
600
-
601
- MessageStream.prototype.pause = function()
602
- {
603
- this.paused = true;
604
- this.emit('pause');
605
- };
606
-
607
- MessageStream.prototype.resume = function()
608
- {
609
- this.paused = false;
610
- this.emit('resume');
611
- };
612
-
613
- MessageStream.prototype.destroy = function()
614
- {
615
- this.emit("destroy", self.bufferIndex > 0 ? {message:"message stream destroyed"} : null);
616
- };
617
-
618
- MessageStream.prototype.destroySoon = function()
619
- {
620
- this.emit("destroy");
621
- };
229
+ /**
230
+ * @typedef {Object} MessageAttachmentHeaders
231
+ * @property {string} content-type
232
+ * @property {string} content-transfer-encoding
233
+ * @property {string} content-disposition
234
+ */
235
+
236
+ /**
237
+ * @typedef {Object} MessageAttachment
238
+ * @property {string} [name]
239
+ * @property {string} [type]
240
+ * @property {string} [charset]
241
+ * @property {string} [method]
242
+ * @property {string} [path]
243
+ * @property {NodeJS.ReadWriteStream} [stream]
244
+ * @property {boolean} [inline]
245
+ * @property {MessageAttachment} [alternative]
246
+ * @property {MessageAttachment[]} [related]
247
+ * @property {*} [encoded]
248
+ * @property {*} [data]
249
+ * @property {MessageAttachmentHeaders} [headers]
250
+ */
251
+
252
+ class MessageStream extends Stream {
253
+ /**
254
+ * @param {Message} message the message to stream
255
+ */
256
+ constructor(message) {
257
+ super();
258
+
259
+ /**
260
+ * @type {Message}
261
+ */
262
+ this.message = message;
263
+
264
+ /**
265
+ * @type {boolean}
266
+ */
267
+ this.readable = true;
268
+
269
+ /**
270
+ * @type {boolean}
271
+ */
272
+ this.paused = false;
273
+
274
+ /**
275
+ * @type {Buffer}
276
+ */
277
+ this.buffer = Buffer.alloc(MIMECHUNK * 24 * 7);
278
+
279
+ /**
280
+ * @type {number}
281
+ */
282
+ this.bufferIndex = 0;
283
+
284
+ /**
285
+ * @returns {void}
286
+ */
287
+ const output_mixed = () => {
288
+ const boundary = generate_boundary();
289
+ output(
290
+ `Content-Type: multipart/mixed; boundary="${boundary}"${CRLF}${CRLF}--${boundary}${CRLF}`
291
+ );
292
+
293
+ if (this.message.alternative == null) {
294
+ output_text(this.message);
295
+ output_message(boundary, this.message.attachments, 0, close);
296
+ } else {
297
+ const cb = () =>
298
+ output_message(boundary, this.message.attachments, 0, close);
299
+ output_alternative(this.message, cb);
300
+ }
301
+ };
302
+
303
+ /**
304
+ * @param {string} boundary the boundary text between outputs
305
+ * @param {MessageAttachment[]} list the list of potential messages to output
306
+ * @param {number} index the index of the list item to output
307
+ * @param {function(): void} callback the function to call if index is greater than upper bound
308
+ * @returns {void}
309
+ */
310
+ const output_message = (boundary, list, index, callback) => {
311
+ if (index < list.length) {
312
+ output(`--${boundary}${CRLF}`);
313
+ if (list[index].related) {
314
+ output_related(list[index], () =>
315
+ output_message(boundary, list, index + 1, callback)
316
+ );
317
+ } else {
318
+ output_attachment(list[index], () =>
319
+ output_message(boundary, list, index + 1, callback)
320
+ );
321
+ }
322
+ } else {
323
+ output(`${CRLF}--${boundary}--${CRLF}${CRLF}`);
324
+ callback();
325
+ }
326
+ };
327
+
328
+ /**
329
+ * @param {MessageAttachment} attachment the metadata to use as headers
330
+ * @returns {void}
331
+ */
332
+ const output_attachment_headers = attachment => {
333
+ let data = [];
334
+ const headers = {
335
+ 'content-type':
336
+ attachment.type +
337
+ (attachment.charset ? `; charset=${attachment.charset}` : '') +
338
+ (attachment.method ? `; method=${attachment.method}` : ''),
339
+ 'content-transfer-encoding': 'base64',
340
+ 'content-disposition': attachment.inline
341
+ ? 'inline'
342
+ : `attachment; filename="${mimeWordEncode(attachment.name)}"`,
343
+ };
344
+
345
+ // allow sender to override default headers
346
+ for (const header in attachment.headers || {}) {
347
+ headers[header.toLowerCase()] = attachment.headers[header];
348
+ }
349
+
350
+ for (const header in headers) {
351
+ data = data.concat([
352
+ fix_header_name_case(header),
353
+ ': ',
354
+ headers[header],
355
+ CRLF,
356
+ ]);
357
+ }
358
+
359
+ output(data.concat([CRLF]).join(''));
360
+ };
361
+
362
+ /**
363
+ * @param {MessageAttachment} attachment the metadata to use as headers
364
+ * @param {function(): void} callback the function to call after output is finished
365
+ * @returns {void}
366
+ */
367
+ const output_attachment = (attachment, callback) => {
368
+ const build = attachment.path
369
+ ? output_file
370
+ : attachment.stream
371
+ ? output_stream
372
+ : output_data;
373
+ output_attachment_headers(attachment);
374
+ build(attachment, callback);
375
+ };
376
+
377
+ /**
378
+ * @param {MessageAttachment} attachment the metadata to use as headers
379
+ * @param {function(): void} callback the function to call after output is finished
380
+ * @returns {void}
381
+ */
382
+ const output_data = (attachment, callback) => {
383
+ output_base64(
384
+ attachment.encoded
385
+ ? attachment.data
386
+ : Buffer.from(attachment.data).toString('base64'),
387
+ callback
388
+ );
389
+ };
390
+
391
+ /**
392
+ * @param {MessageAttachment} attachment the metadata to use as headers
393
+ * @param {function(NodeJS.ErrnoException): void} next the function to call when the file is closed
394
+ * @returns {void}
395
+ */
396
+ const output_file = (attachment, next) => {
397
+ const chunk = MIME64CHUNK * 16;
398
+ const buffer = Buffer.alloc(chunk);
399
+ const closed = fd => fs.closeSync(fd);
400
+
401
+ /**
402
+ * @param {Error} err the error to emit
403
+ * @param {number} fd the file descriptor
404
+ * @returns {void}
405
+ */
406
+ const opened = (err, fd) => {
407
+ if (!err) {
408
+ const read = (err, bytes) => {
409
+ if (!err && this.readable) {
410
+ let encoding =
411
+ attachment && attachment.headers
412
+ ? attachment.headers['content-transfer-encoding'] || 'base64'
413
+ : 'base64';
414
+ if (encoding === 'ascii' || encoding === '7bit') {
415
+ encoding = 'ascii';
416
+ } else if (encoding === 'binary' || encoding === '8bit') {
417
+ encoding = 'binary';
418
+ } else {
419
+ encoding = 'base64';
420
+ }
421
+ // guaranteed to be encoded without padding unless it is our last read
422
+ output_base64(buffer.toString(encoding, 0, bytes), () => {
423
+ if (bytes == chunk) {
424
+ // we read a full chunk, there might be more
425
+ fs.read(fd, buffer, 0, chunk, null, read);
426
+ } // that was the last chunk, we are done reading the file
427
+ else {
428
+ this.removeListener('error', closed);
429
+ fs.close(fd, next);
430
+ }
431
+ });
432
+ } else {
433
+ this.emit(
434
+ 'error',
435
+ err || { message: 'message stream was interrupted somehow!' }
436
+ );
437
+ }
438
+ };
439
+
440
+ fs.read(fd, buffer, 0, chunk, null, read);
441
+ this.once('error', closed);
442
+ } else {
443
+ this.emit('error', err);
444
+ }
445
+ };
446
+
447
+ fs.open(attachment.path, 'r', opened);
448
+ };
449
+
450
+ /**
451
+ * @param {MessageAttachment} attachment the metadata to use as headers
452
+ * @param {function(): void} callback the function to call after output is finished
453
+ * @returns {void}
454
+ */
455
+ const output_stream = (attachment, callback) => {
456
+ if (attachment.stream.readable) {
457
+ let previous = Buffer.alloc(0);
458
+
459
+ attachment.stream.resume();
460
+
461
+ attachment.stream.on('end', () => {
462
+ output_base64(previous.toString('base64'), callback);
463
+ this.removeListener('pause', attachment.stream.pause);
464
+ this.removeListener('resume', attachment.stream.resume);
465
+ this.removeListener('error', attachment.stream.resume);
466
+ });
467
+
468
+ attachment.stream.on('data', buff => {
469
+ // do we have bytes from a previous stream data event?
470
+ let buffer = Buffer.isBuffer(buff) ? buff : Buffer.from(buff);
471
+
472
+ if (previous.byteLength > 0) {
473
+ buffer = Buffer.concat([previous, buffer]);
474
+ }
475
+
476
+ const padded = buffer.length % MIME64CHUNK;
477
+ previous = Buffer.alloc(padded);
478
+
479
+ // encode as much of the buffer to base64 without empty bytes
480
+ if (padded > 0) {
481
+ // copy dangling bytes into previous buffer
482
+ buffer.copy(previous, 0, buffer.length - padded);
483
+ }
484
+ output_base64(buffer.toString('base64', 0, buffer.length - padded));
485
+ });
486
+
487
+ this.on('pause', attachment.stream.pause);
488
+ this.on('resume', attachment.stream.resume);
489
+ this.on('error', attachment.stream.resume);
490
+ } else {
491
+ this.emit('error', { message: 'stream not readable' });
492
+ }
493
+ };
494
+
495
+ /**
496
+ * @param {string} data the data to output as base64
497
+ * @param {function(): void} [callback] the function to call after output is finished
498
+ * @returns {void}
499
+ */
500
+ const output_base64 = (data, callback) => {
501
+ const loops = Math.ceil(data.length / MIMECHUNK);
502
+ let loop = 0;
503
+ while (loop < loops) {
504
+ output(data.substring(MIMECHUNK * loop, MIMECHUNK * (loop + 1)) + CRLF);
505
+ loop++;
506
+ }
507
+ if (callback) {
508
+ callback();
509
+ }
510
+ };
511
+
512
+ /**
513
+ * @param {Message} message the message to output
514
+ * @returns {void}
515
+ */
516
+ const output_text = message => {
517
+ let data = [];
518
+
519
+ data = data.concat([
520
+ 'Content-Type:',
521
+ message.content,
522
+ CRLF,
523
+ 'Content-Transfer-Encoding: 7bit',
524
+ CRLF,
525
+ ]);
526
+ data = data.concat(['Content-Disposition: inline', CRLF, CRLF]);
527
+ data = data.concat([message.text || '', CRLF, CRLF]);
528
+
529
+ output(data.join(''));
530
+ };
531
+
532
+ /**
533
+ * @param {Message} message the message to output
534
+ * @param {function(): void} callback the function to call after output is finished
535
+ * @returns {void}
536
+ */
537
+ const output_alternative = (message, callback) => {
538
+ const boundary = generate_boundary();
539
+ output(
540
+ `Content-Type: multipart/alternative; boundary="${boundary}"${CRLF}${CRLF}--${boundary}${CRLF}`
541
+ );
542
+ output_text(message);
543
+ output(`--${boundary}${CRLF}`);
544
+
545
+ /**
546
+ * @returns {void}
547
+ */
548
+ const finish = () => {
549
+ output([CRLF, '--', boundary, '--', CRLF, CRLF].join(''));
550
+ callback();
551
+ };
552
+
553
+ if (message.alternative.related) {
554
+ output_related(message.alternative, finish);
555
+ } else {
556
+ output_attachment(message.alternative, finish);
557
+ }
558
+ };
559
+
560
+ /**
561
+ * @param {MessageAttachment} message the message to output
562
+ * @param {function(): void} callback the function to call after output is finished
563
+ * @returns {void}
564
+ */
565
+ const output_related = (message, callback) => {
566
+ const boundary = generate_boundary();
567
+ output(
568
+ `Content-Type: multipart/related; boundary="${boundary}"${CRLF}${CRLF}--${boundary}${CRLF}`
569
+ );
570
+ output_attachment(message, () => {
571
+ output_message(boundary, message.related, 0, () => {
572
+ output(`${CRLF}--${boundary}--${CRLF}${CRLF}`);
573
+ callback();
574
+ });
575
+ });
576
+ };
577
+
578
+ /**
579
+ * @returns {void}
580
+ */
581
+ const output_header_data = () => {
582
+ if (this.message.attachments.length || this.message.alternative) {
583
+ output(`MIME-Version: 1.0${CRLF}`);
584
+ output_mixed();
585
+ } // you only have a text message!
586
+ else {
587
+ output_text(this.message);
588
+ close();
589
+ }
590
+ };
591
+
592
+ /**
593
+ * @returns {void}
594
+ */
595
+ const output_header = () => {
596
+ let data = [];
597
+
598
+ for (const header in this.message.header) {
599
+ // do not output BCC in the headers (regex) nor custom Object.prototype functions...
600
+ if (
601
+ !/bcc/i.test(header) &&
602
+ this.message.header.hasOwnProperty(header)
603
+ ) {
604
+ data = data.concat([
605
+ fix_header_name_case(header),
606
+ ': ',
607
+ this.message.header[header],
608
+ CRLF,
609
+ ]);
610
+ }
611
+ }
612
+
613
+ output(data.join(''));
614
+ output_header_data();
615
+ };
616
+
617
+ /**
618
+ * @param {string} data the data to output
619
+ * @param {function(...args): void} [callback] the function
620
+ * @param {*[]} [args] array of arguments to pass to the callback
621
+ * @returns {void}
622
+ */
623
+ const output = (data, callback, args) => {
624
+ const bytes = Buffer.byteLength(data);
625
+
626
+ // can we buffer the data?
627
+ if (bytes + this.bufferIndex < this.buffer.length) {
628
+ this.buffer.write(data, this.bufferIndex);
629
+ this.bufferIndex += bytes;
630
+ if (callback) {
631
+ callback.apply(null, args);
632
+ }
633
+ }
634
+ // we can't buffer the data, so ship it out!
635
+ else if (bytes > this.buffer.length) {
636
+ if (this.bufferIndex) {
637
+ this.emit('data', this.buffer.toString('utf-8', 0, this.bufferIndex));
638
+ this.bufferIndex = 0;
639
+ }
640
+
641
+ const loops = Math.ceil(data.length / this.buffer.length);
642
+ let loop = 0;
643
+ while (loop < loops) {
644
+ this.emit(
645
+ 'data',
646
+ data.substring(
647
+ this.buffer.length * loop,
648
+ this.buffer.length * (loop + 1)
649
+ )
650
+ );
651
+ loop++;
652
+ }
653
+ } // we need to clean out the buffer, it is getting full
654
+ else {
655
+ if (!this.paused) {
656
+ this.emit('data', this.buffer.toString('utf-8', 0, this.bufferIndex));
657
+ this.buffer.write(data, 0);
658
+ this.bufferIndex = bytes;
659
+ // we could get paused after emitting data...
660
+ if (this.paused) {
661
+ this.once('resume', () => callback.apply(null, args));
662
+ } else if (callback) {
663
+ callback.apply(null, args);
664
+ }
665
+ } // we can't empty out the buffer, so let's wait till we resume before adding to it
666
+ else {
667
+ this.once('resume', () => output(data, callback, args));
668
+ }
669
+ }
670
+ };
671
+
672
+ /**
673
+ * @param {*} [err] the error to emit
674
+ * @returns {void}
675
+ */
676
+ const close = err => {
677
+ if (err) {
678
+ this.emit('error', err);
679
+ } else {
680
+ this.emit('data', this.buffer.toString('utf-8', 0, this.bufferIndex));
681
+ this.emit('end');
682
+ }
683
+ this.buffer = null;
684
+ this.bufferIndex = 0;
685
+ this.readable = false;
686
+ this.removeAllListeners('resume');
687
+ this.removeAllListeners('pause');
688
+ this.removeAllListeners('error');
689
+ this.removeAllListeners('data');
690
+ this.removeAllListeners('end');
691
+ };
692
+
693
+ this.once('destroy', close);
694
+ process.nextTick(output_header);
695
+ }
696
+
697
+ /**
698
+ * pause the stream
699
+ * @returns {void}
700
+ */
701
+ pause() {
702
+ this.paused = true;
703
+ this.emit('pause');
704
+ }
705
+
706
+ /**
707
+ * resume the stream
708
+ * @returns {void}
709
+ */
710
+ resume() {
711
+ this.paused = false;
712
+ this.emit('resume');
713
+ }
714
+
715
+ /**
716
+ * destroy the stream
717
+ * @returns {void}
718
+ */
719
+ destroy() {
720
+ this.emit(
721
+ 'destroy',
722
+ this.bufferIndex > 0 ? { message: 'message stream destroyed' } : null
723
+ );
724
+ }
725
+
726
+ /**
727
+ * destroy the stream at first opportunity
728
+ * @returns {void}
729
+ */
730
+ destroySoon() {
731
+ this.emit('destroy');
732
+ }
733
+ }
622
734
 
623
735
  exports.Message = Message;
624
736
  exports.BUFFERSIZE = BUFFERSIZE;
625
- exports.create = function(headers)
626
- {
627
- return new Message(headers);
628
- };
737
+ exports.create = headers => new Message(headers);