-
Notifications
You must be signed in to change notification settings - Fork 230
/
email.js
2126 lines (2117 loc) · 75.3 KB
/
email.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { existsSync, open, read, closeSync, close } from 'fs';
import { hostname } from 'os';
import { Stream } from 'stream';
import { TextEncoder, TextDecoder } from 'util';
import { createHmac } from 'crypto';
import { EventEmitter } from 'events';
import { Socket } from 'net';
import { connect, TLSSocket, createSecureContext } from 'tls';
/*
* Operator tokens and which tokens are expected to end the sequence
*/
const OPERATORS = new Map([
['"', '"'],
['(', ')'],
['<', '>'],
[',', ''],
// Groups are ended by semicolons
[':', ';'],
// Semicolons are not a legal delimiter per the RFC2822 grammar other
// than for terminating a group, but they are also not valid for any
// other use in this context. Given that some mail clients have
// historically allowed the semicolon as a delimiter equivalent to the
// comma in their UI, it makes sense to treat them the same as a comma
// when used outside of a group.
[';', ''],
]);
/**
* Tokenizes the original input string
*
* @param {string | string[] | undefined} address string(s) to tokenize
* @return {AddressToken[]} An array of operator|text tokens
*/
function tokenizeAddress(address = '') {
var _a, _b;
const tokens = [];
let token = undefined;
let operator = undefined;
for (const character of address.toString()) {
if (((_a = operator === null || operator === void 0 ? void 0 : operator.length) !== null && _a !== void 0 ? _a : 0) > 0 && character === operator) {
tokens.push({ type: 'operator', value: character });
token = undefined;
operator = undefined;
}
else if (((_b = operator === null || operator === void 0 ? void 0 : operator.length) !== null && _b !== void 0 ? _b : 0) === 0 && OPERATORS.has(character)) {
tokens.push({ type: 'operator', value: character });
token = undefined;
operator = OPERATORS.get(character);
}
else {
if (token == null) {
token = { type: 'text', value: character };
tokens.push(token);
}
else {
token.value += character;
}
}
}
return tokens
.map((x) => {
x.value = x.value.trim();
return x;
})
.filter((x) => x.value.length > 0);
}
/**
* Converts tokens for a single address into an address object
*
* @param {AddressToken[]} tokens Tokens object
* @return {AddressObject[]} addresses object array
*/
function convertAddressTokens(tokens) {
const addressObjects = [];
const groups = [];
let addresses = [];
let comments = [];
let texts = [];
let state = 'text';
let isGroup = false;
function handleToken(token) {
if (token.type === 'operator') {
switch (token.value) {
case '<':
state = 'address';
break;
case '(':
state = 'comment';
break;
case ':':
state = 'group';
isGroup = true;
break;
default:
state = 'text';
break;
}
}
else if (token.value.length > 0) {
switch (state) {
case 'address':
addresses.push(token.value);
break;
case 'comment':
comments.push(token.value);
break;
case 'group':
groups.push(token.value);
break;
default:
texts.push(token.value);
break;
}
}
}
// Filter out <addresses>, (comments) and regular text
for (const token of tokens) {
handleToken(token);
}
// If there is no text but a comment, replace the two
if (texts.length === 0 && comments.length > 0) {
texts = [...comments];
comments = [];
}
// http://tools.ietf.org/html/rfc2822#appendix-A.1.3
if (isGroup) {
addressObjects.push({
name: texts.length === 0 ? undefined : texts.join(' '),
group: groups.length > 0 ? addressparser(groups.join(',')) : [],
});
}
else {
// If no address was found, try to detect one from regular text
if (addresses.length === 0 && texts.length > 0) {
for (let i = texts.length - 1; i >= 0; i--) {
if (texts[i].match(/^[^@\s]+@[^@\s]+$/)) {
addresses = texts.splice(i, 1);
break;
}
}
// still no address
if (addresses.length === 0) {
for (let i = texts.length - 1; i >= 0; i--) {
texts[i] = texts[i]
.replace(/\s*\b[^@\s]+@[^@\s]+\b\s*/, (address) => {
if (addresses.length === 0) {
addresses = [address.trim()];
return ' ';
}
else {
return address;
}
})
.trim();
if (addresses.length > 0) {
break;
}
}
}
}
// If there's still is no text but a comment exixts, replace the two
if (texts.length === 0 && comments.length > 0) {
texts = [...comments];
comments = [];
}
// Keep only the first address occurence, push others to regular text
if (addresses.length > 1) {
texts = [...texts, ...addresses.splice(1)];
}
if (addresses.length === 0 && isGroup) {
return [];
}
else {
// Join values with spaces
let address = addresses.join(' ');
let name = texts.length === 0 ? address : texts.join(' ');
if (address === name) {
if (address.match(/@/)) {
name = '';
}
else {
address = '';
}
}
addressObjects.push({ address, name });
}
}
return addressObjects;
}
/**
* Parses structured e-mail addresses from an address field
*
* Example:
*
* "Name <address@domain>"
*
* will be converted to
*
* [{name: "Name", address: "address@domain"}]
*
* @param {string | string[] | undefined} address Address field
* @return {AddressObject[]} An array of address objects
*/
function addressparser(address) {
const addresses = [];
let tokens = [];
for (const token of tokenizeAddress(address)) {
if (token.type === 'operator' &&
(token.value === ',' || token.value === ';')) {
if (tokens.length > 0) {
addresses.push(...convertAddressTokens(tokens));
}
tokens = [];
}
else {
tokens.push(token);
}
}
if (tokens.length > 0) {
addresses.push(...convertAddressTokens(tokens));
}
return addresses;
}
/**
* @param {Date} [date] an optional date to convert to RFC2822 format
* @param {boolean} [useUtc] whether to parse the date as UTC (default: false)
* @returns {string} the converted date
*/
function getRFC2822Date(date = new Date(), useUtc = false) {
if (useUtc) {
return getRFC2822DateUTC(date);
}
const dates = date
.toString()
.replace('GMT', '')
.replace(/\s\(.*\)$/, '')
.split(' ');
dates[0] = dates[0] + ',';
const day = dates[1];
dates[1] = dates[2];
dates[2] = day;
return dates.join(' ');
}
/**
* @param {Date} [date] an optional date to convert to RFC2822 format (UTC)
* @returns {string} the converted date
*/
function getRFC2822DateUTC(date = new Date()) {
const dates = date.toUTCString().split(' ');
dates.pop(); // remove timezone
dates.push('+0000');
return dates.join(' ');
}
/**
* RFC 2822 regex
* @see https://tools.ietf.org/html/rfc2822#section-3.3
* @see https://github.com/moment/moment/blob/a831fc7e2694281ce31e4f090bbcf90a690f0277/src/lib/create/from-string.js#L101
*/
const rfc2822re = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
/**
* @param {string} [date] a string to check for conformance to the [rfc2822](https://tools.ietf.org/html/rfc2822#section-3.3) standard
* @returns {boolean} the result of the conformance check
*/
function isRFC2822Date(date) {
return rfc2822re.test(date);
}
// adapted from https://github.com/emailjs/emailjs-mime-codec/blob/6909c706b9f09bc0e5c3faf48f723cca53e5b352/src/mimecodec.js
const encoder = new TextEncoder();
/**
* @see https://tools.ietf.org/html/rfc2045#section-6.7
*/
const RANGES = [
[0x09],
[0x0a],
[0x0d],
[0x20, 0x3c],
[0x3e, 0x7e], // >?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}
];
const LOOKUP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
const MAX_CHUNK_LENGTH = 16383; // must be multiple of 3
const MAX_MIME_WORD_LENGTH = 52;
const MAX_B64_MIME_WORD_BYTE_LENGTH = 39;
function tripletToBase64(num) {
return (LOOKUP[(num >> 18) & 0x3f] +
LOOKUP[(num >> 12) & 0x3f] +
LOOKUP[(num >> 6) & 0x3f] +
LOOKUP[num & 0x3f]);
}
function encodeChunk(uint8, start, end) {
let output = '';
for (let i = start; i < end; i += 3) {
output += tripletToBase64((uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]);
}
return output;
}
function encodeBase64(data) {
const len = data.length;
const extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
let output = '';
// go through the array every three bytes, we'll deal with trailing stuff later
for (let i = 0, len2 = len - extraBytes; i < len2; i += MAX_CHUNK_LENGTH) {
output += encodeChunk(data, i, i + MAX_CHUNK_LENGTH > len2 ? len2 : i + MAX_CHUNK_LENGTH);
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
const tmp = data[len - 1];
output += LOOKUP[tmp >> 2];
output += LOOKUP[(tmp << 4) & 0x3f];
output += '==';
}
else if (extraBytes === 2) {
const tmp = (data[len - 2] << 8) + data[len - 1];
output += LOOKUP[tmp >> 10];
output += LOOKUP[(tmp >> 4) & 0x3f];
output += LOOKUP[(tmp << 2) & 0x3f];
output += '=';
}
return output;
}
/**
* Splits a mime encoded string. Needed for dividing mime words into smaller chunks
*
* @param {string} str Mime encoded string to be split up
* @param {number} maxlen Maximum length of characters for one part (minimum 12)
* @return {string[]} lines
*/
function splitMimeEncodedString(str, maxlen = 12) {
const minWordLength = 12; // require at least 12 symbols to fit possible 4 octet UTF-8 sequences
const maxWordLength = Math.max(maxlen, minWordLength);
const lines = [];
while (str.length) {
let curLine = str.substr(0, maxWordLength);
const match = curLine.match(/=[0-9A-F]?$/i); // skip incomplete escaped char
if (match) {
curLine = curLine.substr(0, match.index);
}
let done = false;
while (!done) {
let chr;
done = true;
const match = str.substr(curLine.length).match(/^=([0-9A-F]{2})/i); // check if not middle of a unicode char sequence
if (match) {
chr = parseInt(match[1], 16);
// invalid sequence, move one char back anc recheck
if (chr < 0xc2 && chr > 0x7f) {
curLine = curLine.substr(0, curLine.length - 3);
done = false;
}
}
}
if (curLine.length) {
lines.push(curLine);
}
str = str.substr(curLine.length);
}
return lines;
}
/**
*
* @param {number} nr number
* @returns {boolean} if number is in range
*/
function checkRanges(nr) {
return RANGES.reduce((val, range) => val ||
(range.length === 1 && nr === range[0]) ||
(range.length === 2 && nr >= range[0] && nr <= range[1]), false);
}
/**
* Encodes all non printable and non ascii bytes to =XX form, where XX is the
* byte value in hex. This function does not convert linebreaks etc. it
* only escapes character sequences
*
* NOTE: Encoding support depends on util.TextDecoder, which is severely limited
* prior to Node.js 13.
*
* @see https://nodejs.org/api/util.html#util_whatwg_supported_encodings
* @see https://github.com/nodejs/node/issues/19214
*
* @param {string|Uint8Array} data Either a string or an Uint8Array
* @param {string} encoding WHATWG supported encoding
* @return {string} Mime encoded string
*/
function mimeEncode(data = '', encoding = 'utf-8') {
const decoder = new TextDecoder(encoding);
const buffer = typeof data === 'string'
? encoder.encode(data)
: encoder.encode(decoder.decode(data));
return buffer.reduce((aggregate, ord, index) => checkRanges(ord) &&
!((ord === 0x20 || ord === 0x09) &&
(index === buffer.length - 1 ||
buffer[index + 1] === 0x0a ||
buffer[index + 1] === 0x0d))
? // if the char is in allowed range, then keep as is, unless it is a ws in the end of a line
aggregate + String.fromCharCode(ord)
: `${aggregate}=${ord < 0x10 ? '0' : ''}${ord
.toString(16)
.toUpperCase()}`, '');
}
/**
* Encodes a string or an Uint8Array to an UTF-8 MIME Word
*
* NOTE: Encoding support depends on util.TextDecoder, which is severely limited
* prior to Node.js 13.
*
* @see https://tools.ietf.org/html/rfc2047
* @see https://nodejs.org/api/util.html#util_whatwg_supported_encodings
* @see https://github.com/nodejs/node/issues/19214
*
* @param {string|Uint8Array} data String to be encoded
* @param {'Q' | 'B'} mimeWordEncoding='Q' Encoding for the mime word, either Q or B
* @param {string} encoding WHATWG supported encoding
* @return {string} Single or several mime words joined together
*/
function mimeWordEncode(data, mimeWordEncoding = 'Q', encoding = 'utf-8') {
let parts = [];
const decoder = new TextDecoder(encoding);
const str = typeof data === 'string' ? data : decoder.decode(data);
if (mimeWordEncoding === 'Q') {
const encodedStr = mimeEncode(str, encoding).replace(/[^a-z0-9!*+\-/=]/gi, (chr) => chr === ' '
? '_'
: '=' +
(chr.charCodeAt(0) < 0x10 ? '0' : '') +
chr.charCodeAt(0).toString(16).toUpperCase());
parts =
encodedStr.length < MAX_MIME_WORD_LENGTH
? [encodedStr]
: splitMimeEncodedString(encodedStr, MAX_MIME_WORD_LENGTH);
}
else {
// Fits as much as possible into every line without breaking utf-8 multibyte characters' octets up across lines
let j = 0;
let i = 0;
while (i < str.length) {
if (encoder.encode(str.substring(j, i)).length >
MAX_B64_MIME_WORD_BYTE_LENGTH) {
// we went one character too far, substring at the char before
parts.push(str.substring(j, i - 1));
j = i - 1;
}
else {
i++;
}
}
// add the remainder of the string
str.substring(j) && parts.push(str.substring(j));
parts = parts.map((x) => encoder.encode(x)).map((x) => encodeBase64(x));
}
return parts
.map((p) => `=?UTF-8?${mimeWordEncoding}?${p}?= `)
.join('')
.trim();
}
const CRLF$1 = '\r\n';
/**
* MIME standard wants 76 char chunks when sending out.
*/
const MIMECHUNK = 76;
/**
* meets both base64 and mime divisibility
*/
const MIME64CHUNK = (MIMECHUNK * 6);
/**
* size of the message stream buffer
*/
const BUFFERSIZE = (MIMECHUNK * 24 * 7);
let counter = 0;
function generateBoundary() {
let text = '';
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'()+_,-./:=?";
for (let i = 0; i < 69; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function convertPersonToAddress(person) {
return addressparser(person)
.map(({ name, address }) => {
return name
? `${mimeWordEncode(name).replace(/,/g, '=2C')} <${address}>`
: address;
})
.join(', ');
}
function convertDashDelimitedTextToSnakeCase(text) {
return text
.toLowerCase()
.replace(/^(.)|-(.)/g, (match) => match.toUpperCase());
}
class Message {
/**
* Construct an rfc2822-compliant message object.
*
* Special notes:
* - The `from` field is required.
* - At least one `to`, `cc`, or `bcc` header is also required.
* - You can also add whatever other headers you want.
*
* @see https://tools.ietf.org/html/rfc2822
* @param {Partial<MessageHeaders>} headers Message headers
*/
constructor(headers) {
this.attachments = [];
this.header = {
'message-id': `<${new Date().getTime()}.${counter++}.${process.pid}@${hostname()}>`,
date: getRFC2822Date(),
};
this.content = 'text/plain; charset=utf-8';
this.alternative = null;
for (const header in headers) {
// allow user to override default content-type to override charset or send a single non-text message
if (/^content-type$/i.test(header)) {
this.content = headers[header];
}
else if (header === 'text') {
this.text = headers[header];
}
else if (header === 'attachment' &&
typeof headers[header] === 'object') {
const attachment = headers[header];
if (Array.isArray(attachment)) {
for (let i = 0; i < attachment.length; i++) {
this.attach(attachment[i]);
}
}
else if (attachment != null) {
this.attach(attachment);
}
}
else if (header === 'subject') {
this.header.subject = mimeWordEncode(headers.subject);
}
else if (/^(cc|bcc|to|from)/i.test(header)) {
this.header[header.toLowerCase()] = convertPersonToAddress(headers[header]);
}
else {
// allow any headers the user wants to set??
this.header[header.toLowerCase()] = headers[header];
}
}
}
/**
* Attach a file to the message.
*
* Can be called multiple times, each adding a new attachment.
*
* @public
* @param {MessageAttachment} options attachment options
* @returns {Message} the current instance for chaining
*/
attach(options) {
// sender can specify an attachment as an alternative
if (options.alternative) {
this.alternative = options;
this.alternative.charset = options.charset || 'utf-8';
this.alternative.type = options.type || 'text/html';
this.alternative.inline = true;
}
else {
this.attachments.push(options);
}
return this;
}
/**
* @public
* @returns {{ isValid: boolean, validationError: (string | undefined) }} an object specifying whether this message is validly formatted, and the first validation error if it is not.
*/
checkValidity() {
if (typeof this.header.from !== 'string' &&
Array.isArray(this.header.from) === false) {
return {
isValid: false,
validationError: 'Message must have a `from` header',
};
}
if (typeof this.header.to !== 'string' &&
Array.isArray(this.header.to) === false &&
typeof this.header.cc !== 'string' &&
Array.isArray(this.header.cc) === false &&
typeof this.header.bcc !== 'string' &&
Array.isArray(this.header.bcc) === false) {
return {
isValid: false,
validationError: 'Message must have at least one `to`, `cc`, or `bcc` header',
};
}
if (this.attachments.length > 0) {
const failed = [];
this.attachments.forEach((attachment) => {
if (attachment.path) {
if (existsSync(attachment.path) === false) {
failed.push(`${attachment.path} does not exist`);
}
}
else if (attachment.stream) {
if (!attachment.stream.readable) {
failed.push('attachment stream is not readable');
}
}
else if (!attachment.data) {
failed.push('attachment has no data associated with it');
}
});
return {
isValid: failed.length === 0,
validationError: failed.join(', '),
};
}
return { isValid: true, validationError: undefined };
}
/**
* @public
* @deprecated does not conform to the `errback` style followed by the rest of the library, and will be removed in the next major version. use `checkValidity` instead.
* @param {function(isValid: boolean, invalidReason: (string | undefined)): void} callback .
* @returns {void}
*/
valid(callback) {
const { isValid, validationError } = this.checkValidity();
callback(isValid, validationError);
}
/**
* @public
* @returns {MessageStream} a stream of the current message
*/
stream() {
return new MessageStream(this);
}
/**
* @public
* @param {function(Error, string): void} callback the function to call with the error and buffer
* @returns {void}
*/
read(callback) {
let buffer = '';
const str = this.stream();
str.on('data', (data) => (buffer += data));
str.on('end', (err) => callback(err, buffer));
str.on('error', (err) => callback(err, buffer));
}
readAsync() {
return new Promise((resolve, reject) => {
this.read((err, buffer) => {
if (err != null) {
reject(err);
}
else {
resolve(buffer);
}
});
});
}
}
class MessageStream extends Stream {
/**
* @param {Message} message the message to stream
*/
constructor(message) {
super();
this.message = message;
this.readable = true;
this.paused = false;
this.buffer = Buffer.alloc(MIMECHUNK * 24 * 7);
this.bufferIndex = 0;
/**
* @param {string} [data] the data to output
* @param {Function} [callback] the function
* @param {any[]} [args] array of arguments to pass to the callback
* @returns {void}
*/
const output = (data) => {
// can we buffer the data?
if (this.buffer != null) {
const bytes = Buffer.byteLength(data);
if (bytes + this.bufferIndex < this.buffer.length) {
this.buffer.write(data, this.bufferIndex);
this.bufferIndex += bytes;
}
// we can't buffer the data, so ship it out!
else if (bytes > this.buffer.length) {
if (this.bufferIndex) {
this.emit('data', this.buffer.toString('utf-8', 0, this.bufferIndex));
this.bufferIndex = 0;
}
const loops = Math.ceil(data.length / this.buffer.length);
let loop = 0;
while (loop < loops) {
this.emit('data', data.substring(this.buffer.length * loop, this.buffer.length * (loop + 1)));
loop++;
}
} // we need to clean out the buffer, it is getting full
else {
if (!this.paused) {
this.emit('data', this.buffer.toString('utf-8', 0, this.bufferIndex));
this.buffer.write(data, 0);
this.bufferIndex = bytes;
}
else {
// we can't empty out the buffer, so let's wait till we resume before adding to it
this.once('resume', () => output(data));
}
}
}
};
/**
* @param {MessageAttachment} [attachment] the attachment whose headers you would like to output
* @returns {void}
*/
const outputAttachmentHeaders = (attachment) => {
let data = [];
const headers = {
'content-type': attachment.type +
(attachment.charset ? `; charset=${attachment.charset}` : '') +
(attachment.method ? `; method=${attachment.method}` : ''),
'content-transfer-encoding': 'base64',
'content-disposition': attachment.inline
? 'inline'
: `attachment; filename="${mimeWordEncode(attachment.name)}"`,
};
// allow sender to override default headers
if (attachment.headers != null) {
for (const header in attachment.headers) {
headers[header.toLowerCase()] = attachment.headers[header];
}
}
for (const header in headers) {
data = data.concat([
convertDashDelimitedTextToSnakeCase(header),
': ',
headers[header],
CRLF$1,
]);
}
output(data.concat([CRLF$1]).join(''));
};
/**
* @param {string} data the data to output as base64
* @param {function(): void} [callback] the function to call after output is finished
* @returns {void}
*/
const outputBase64 = (data, callback) => {
const loops = Math.ceil(data.length / MIMECHUNK);
let loop = 0;
while (loop < loops) {
output(data.substring(MIMECHUNK * loop, MIMECHUNK * (loop + 1)) + CRLF$1);
loop++;
}
if (callback) {
callback();
}
};
const outputFile = (attachment, next) => {
var _a;
const chunk = MIME64CHUNK * 16;
const buffer = Buffer.alloc(chunk);
const inputEncoding = ((_a = attachment === null || attachment === void 0 ? void 0 : attachment.headers) === null || _a === void 0 ? void 0 : _a['content-transfer-encoding']) || 'base64';
const encoding = inputEncoding === '7bit'
? 'ascii'
: inputEncoding === '8bit'
? 'binary'
: inputEncoding;
/**
* @param {Error} err the error to emit
* @param {number} fd the file descriptor
* @returns {void}
*/
const opened = (err, fd) => {
if (err) {
this.emit('error', err);
return;
}
const readBytes = (err, bytes) => {
if (err || this.readable === false) {
this.emit('error', err || new Error('message stream was interrupted somehow!'));
return;
}
// guaranteed to be encoded without padding unless it is our last read
outputBase64(buffer.toString(encoding, 0, bytes), () => {
if (bytes == chunk) {
// we read a full chunk, there might be more
read(fd, buffer, 0, chunk, null, readBytes);
} // that was the last chunk, we are done reading the file
else {
this.removeListener('error', closeSync);
close(fd, next);
}
});
};
read(fd, buffer, 0, chunk, null, readBytes);
this.once('error', closeSync);
};
open(attachment.path, 'r', opened);
};
/**
* @param {MessageAttachment} attachment the metadata to use as headers
* @param {function(): void} callback the function to call after output is finished
* @returns {void}
*/
const outputStream = (attachment, callback) => {
const { stream } = attachment;
if (stream === null || stream === void 0 ? void 0 : stream.readable) {
let previous = Buffer.alloc(0);
stream.resume();
stream.on('end', () => {
outputBase64(previous.toString('base64'), callback);
this.removeListener('pause', stream.pause);
this.removeListener('resume', stream.resume);
this.removeListener('error', stream.resume);
});
stream.on('data', (buff) => {
// do we have bytes from a previous stream data event?
let buffer = Buffer.isBuffer(buff) ? buff : Buffer.from(buff);
if (previous.byteLength > 0) {
buffer = Buffer.concat([previous, buffer]);
}
const padded = buffer.length % MIME64CHUNK;
previous = Buffer.alloc(padded);
// encode as much of the buffer to base64 without empty bytes
if (padded > 0) {
// copy dangling bytes into previous buffer
buffer.copy(previous, 0, buffer.length - padded);
}
outputBase64(buffer.toString('base64', 0, buffer.length - padded));
});
this.on('pause', stream.pause);
this.on('resume', stream.resume);
this.on('error', stream.resume);
}
else {
this.emit('error', { message: 'stream not readable' });
}
};
const outputAttachment = (attachment, callback) => {
const build = attachment.path
? outputFile
: attachment.stream
? outputStream
: outputData;
outputAttachmentHeaders(attachment);
build(attachment, callback);
};
/**
* @param {string} boundary the boundary text between outputs
* @param {MessageAttachment[]} list the list of potential messages to output
* @param {number} index the index of the list item to output
* @param {function(): void} callback the function to call if index is greater than upper bound
* @returns {void}
*/
const outputMessage = (boundary, list, index, callback) => {
if (index < list.length) {
output(`--${boundary}${CRLF$1}`);
if (list[index].related) {
outputRelated(list[index], () => outputMessage(boundary, list, index + 1, callback));
}
else {
outputAttachment(list[index], () => outputMessage(boundary, list, index + 1, callback));
}
}
else {
output(`${CRLF$1}--${boundary}--${CRLF$1}${CRLF$1}`);
callback();
}
};
const outputMixed = () => {
const boundary = generateBoundary();
output(`Content-Type: multipart/mixed; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
if (this.message.alternative == null) {
outputText(this.message);
outputMessage(boundary, this.message.attachments, 0, close$1);
}
else {
outputAlternative(
// typescript bug; should narrow to { alternative: MessageAttachment }
this.message, () => outputMessage(boundary, this.message.attachments, 0, close$1));
}
};
/**
* @param {MessageAttachment} attachment the metadata to use as headers
* @param {function(): void} callback the function to call after output is finished
* @returns {void}
*/
const outputData = (attachment, callback) => {
var _a, _b;
outputBase64(attachment.encoded
? (_a = attachment.data) !== null && _a !== void 0 ? _a : ''
: Buffer.from((_b = attachment.data) !== null && _b !== void 0 ? _b : '').toString('base64'), callback);
};
/**
* @param {Message} message the message to output
* @returns {void}
*/
const outputText = (message) => {
let data = [];
data = data.concat([
'Content-Type:',
message.content,
CRLF$1,
'Content-Transfer-Encoding: 7bit',
CRLF$1,
]);
data = data.concat(['Content-Disposition: inline', CRLF$1, CRLF$1]);
data = data.concat([message.text || '', CRLF$1, CRLF$1]);
output(data.join(''));
};
/**
* @param {MessageAttachment} message the message to output
* @param {function(): void} callback the function to call after output is finished
* @returns {void}
*/
const outputRelated = (message, callback) => {
const boundary = generateBoundary();
output(`Content-Type: multipart/related; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
outputAttachment(message, () => {
var _a;
outputMessage(boundary, (_a = message.related) !== null && _a !== void 0 ? _a : [], 0, () => {
output(`${CRLF$1}--${boundary}--${CRLF$1}${CRLF$1}`);
callback();
});
});
};
/**
* @param {Message} message the message to output
* @param {function(): void} callback the function to call after output is finished
* @returns {void}
*/
const outputAlternative = (message, callback) => {
const boundary = generateBoundary();
output(`Content-Type: multipart/alternative; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
outputText(message);
output(`--${boundary}${CRLF$1}`);
/**
* @returns {void}
*/
const finish = () => {
output([CRLF$1, '--', boundary, '--', CRLF$1, CRLF$1].join(''));
callback();
};
if (message.alternative.related) {
outputRelated(message.alternative, finish);
}
else {
outputAttachment(message.alternative, finish);
}
};
const close$1 = (err) => {
var _a, _b;
if (err) {
this.emit('error', err);
}
else {
this.emit('data', (_b = (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.toString('utf-8', 0, this.bufferIndex)) !== null && _b !== void 0 ? _b : '');
this.emit('end');
}
this.buffer = null;
this.bufferIndex = 0;
this.readable = false;
this.removeAllListeners('resume');
this.removeAllListeners('pause');
this.removeAllListeners('error');
this.removeAllListeners('data');
this.removeAllListeners('end');
};
/**
* @returns {void}
*/
const outputHeaderData = () => {
if (this.message.attachments.length || this.message.alternative) {
output(`MIME-Version: 1.0${CRLF$1}`);
outputMixed();
} // you only have a text message!
else {
outputText(this.message);
close$1();
}
};
/**
* @returns {void}
*/
const outputHeader = () => {
let data = [];
for (const header in this.message.header) {
// do not output BCC in the headers (regex) nor custom Object.prototype functions...
if (!/bcc/i.test(header) &&
Object.prototype.hasOwnProperty.call(this.message.header, header)) {
data = data.concat([
convertDashDelimitedTextToSnakeCase(header),
': ',
this.message.header[header],
CRLF$1,
]);
}
}
output(data.join(''));
outputHeaderData();
};
this.once('destroy', close$1);
process.nextTick(outputHeader);
}
/**