emailjs 3.8.1 → 4.0.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/rollup/email.cjs DELETED
@@ -1,2143 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var fs = require('fs');
6
- var os = require('os');
7
- var stream = require('stream');
8
- var util = require('util');
9
- var crypto = require('crypto');
10
- var events = require('events');
11
- var net = require('net');
12
- var tls = require('tls');
13
-
14
- /*
15
- * Operator tokens and which tokens are expected to end the sequence
16
- */
17
- const OPERATORS = new Map([
18
- ['"', '"'],
19
- ['(', ')'],
20
- ['<', '>'],
21
- [',', ''],
22
- // Groups are ended by semicolons
23
- [':', ';'],
24
- // Semicolons are not a legal delimiter per the RFC2822 grammar other
25
- // than for terminating a group, but they are also not valid for any
26
- // other use in this context. Given that some mail clients have
27
- // historically allowed the semicolon as a delimiter equivalent to the
28
- // comma in their UI, it makes sense to treat them the same as a comma
29
- // when used outside of a group.
30
- [';', ''],
31
- ]);
32
- /**
33
- * Tokenizes the original input string
34
- *
35
- * @param {string | string[] | undefined} address string(s) to tokenize
36
- * @return {AddressToken[]} An array of operator|text tokens
37
- */
38
- function tokenizeAddress(address = '') {
39
- var _a, _b;
40
- const tokens = [];
41
- let token = undefined;
42
- let operator = undefined;
43
- for (const character of address.toString()) {
44
- if (((_a = operator === null || operator === void 0 ? void 0 : operator.length) !== null && _a !== void 0 ? _a : 0) > 0 && character === operator) {
45
- tokens.push({ type: 'operator', value: character });
46
- token = undefined;
47
- operator = undefined;
48
- }
49
- else if (((_b = operator === null || operator === void 0 ? void 0 : operator.length) !== null && _b !== void 0 ? _b : 0) === 0 && OPERATORS.has(character)) {
50
- tokens.push({ type: 'operator', value: character });
51
- token = undefined;
52
- operator = OPERATORS.get(character);
53
- }
54
- else {
55
- if (token == null) {
56
- token = { type: 'text', value: character };
57
- tokens.push(token);
58
- }
59
- else {
60
- token.value += character;
61
- }
62
- }
63
- }
64
- return tokens
65
- .map((x) => {
66
- x.value = x.value.trim();
67
- return x;
68
- })
69
- .filter((x) => x.value.length > 0);
70
- }
71
- /**
72
- * Converts tokens for a single address into an address object
73
- *
74
- * @param {AddressToken[]} tokens Tokens object
75
- * @return {AddressObject[]} addresses object array
76
- */
77
- function convertAddressTokens(tokens) {
78
- const addressObjects = [];
79
- const groups = [];
80
- let addresses = [];
81
- let comments = [];
82
- let texts = [];
83
- let state = 'text';
84
- let isGroup = false;
85
- function handleToken(token) {
86
- if (token.type === 'operator') {
87
- switch (token.value) {
88
- case '<':
89
- state = 'address';
90
- break;
91
- case '(':
92
- state = 'comment';
93
- break;
94
- case ':':
95
- state = 'group';
96
- isGroup = true;
97
- break;
98
- default:
99
- state = 'text';
100
- break;
101
- }
102
- }
103
- else if (token.value.length > 0) {
104
- switch (state) {
105
- case 'address':
106
- addresses.push(token.value);
107
- break;
108
- case 'comment':
109
- comments.push(token.value);
110
- break;
111
- case 'group':
112
- groups.push(token.value);
113
- break;
114
- default:
115
- texts.push(token.value);
116
- break;
117
- }
118
- }
119
- }
120
- // Filter out <addresses>, (comments) and regular text
121
- for (const token of tokens) {
122
- handleToken(token);
123
- }
124
- // If there is no text but a comment, replace the two
125
- if (texts.length === 0 && comments.length > 0) {
126
- texts = [...comments];
127
- comments = [];
128
- }
129
- // http://tools.ietf.org/html/rfc2822#appendix-A.1.3
130
- if (isGroup) {
131
- addressObjects.push({
132
- name: texts.length === 0 ? undefined : texts.join(' '),
133
- group: groups.length > 0 ? addressparser(groups.join(',')) : [],
134
- });
135
- }
136
- else {
137
- // If no address was found, try to detect one from regular text
138
- if (addresses.length === 0 && texts.length > 0) {
139
- for (let i = texts.length - 1; i >= 0; i--) {
140
- if (texts[i].match(/^[^@\s]+@[^@\s]+$/)) {
141
- addresses = texts.splice(i, 1);
142
- break;
143
- }
144
- }
145
- // still no address
146
- if (addresses.length === 0) {
147
- for (let i = texts.length - 1; i >= 0; i--) {
148
- texts[i] = texts[i]
149
- .replace(/\s*\b[^@\s]+@[^@\s]+\b\s*/, (address) => {
150
- if (addresses.length === 0) {
151
- addresses = [address.trim()];
152
- return ' ';
153
- }
154
- else {
155
- return address;
156
- }
157
- })
158
- .trim();
159
- if (addresses.length > 0) {
160
- break;
161
- }
162
- }
163
- }
164
- }
165
- // If there's still is no text but a comment exixts, replace the two
166
- if (texts.length === 0 && comments.length > 0) {
167
- texts = [...comments];
168
- comments = [];
169
- }
170
- // Keep only the first address occurence, push others to regular text
171
- if (addresses.length > 1) {
172
- texts = [...texts, ...addresses.splice(1)];
173
- }
174
- if (addresses.length === 0 && isGroup) {
175
- return [];
176
- }
177
- else {
178
- // Join values with spaces
179
- let address = addresses.join(' ');
180
- let name = texts.length === 0 ? address : texts.join(' ');
181
- if (address === name) {
182
- if (address.match(/@/)) {
183
- name = '';
184
- }
185
- else {
186
- address = '';
187
- }
188
- }
189
- addressObjects.push({ address, name });
190
- }
191
- }
192
- return addressObjects;
193
- }
194
- /**
195
- * Parses structured e-mail addresses from an address field
196
- *
197
- * Example:
198
- *
199
- * "Name <address@domain>"
200
- *
201
- * will be converted to
202
- *
203
- * [{name: "Name", address: "address@domain"}]
204
- *
205
- * @param {string | string[] | undefined} address Address field
206
- * @return {AddressObject[]} An array of address objects
207
- */
208
- function addressparser(address) {
209
- const addresses = [];
210
- let tokens = [];
211
- for (const token of tokenizeAddress(address)) {
212
- if (token.type === 'operator' &&
213
- (token.value === ',' || token.value === ';')) {
214
- if (tokens.length > 0) {
215
- addresses.push(...convertAddressTokens(tokens));
216
- }
217
- tokens = [];
218
- }
219
- else {
220
- tokens.push(token);
221
- }
222
- }
223
- if (tokens.length > 0) {
224
- addresses.push(...convertAddressTokens(tokens));
225
- }
226
- return addresses;
227
- }
228
-
229
- /**
230
- * @param {Date} [date] an optional date to convert to RFC2822 format
231
- * @param {boolean} [useUtc] whether to parse the date as UTC (default: false)
232
- * @returns {string} the converted date
233
- */
234
- function getRFC2822Date(date = new Date(), useUtc = false) {
235
- if (useUtc) {
236
- return getRFC2822DateUTC(date);
237
- }
238
- const dates = date
239
- .toString()
240
- .replace('GMT', '')
241
- .replace(/\s\(.*\)$/, '')
242
- .split(' ');
243
- dates[0] = dates[0] + ',';
244
- const day = dates[1];
245
- dates[1] = dates[2];
246
- dates[2] = day;
247
- return dates.join(' ');
248
- }
249
- /**
250
- * @param {Date} [date] an optional date to convert to RFC2822 format (UTC)
251
- * @returns {string} the converted date
252
- */
253
- function getRFC2822DateUTC(date = new Date()) {
254
- const dates = date.toUTCString().split(' ');
255
- dates.pop(); // remove timezone
256
- dates.push('+0000');
257
- return dates.join(' ');
258
- }
259
- /**
260
- * RFC 2822 regex
261
- * @see https://tools.ietf.org/html/rfc2822#section-3.3
262
- * @see https://github.com/moment/moment/blob/a831fc7e2694281ce31e4f090bbcf90a690f0277/src/lib/create/from-string.js#L101
263
- */
264
- 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}))$/;
265
- /**
266
- * @param {string} [date] a string to check for conformance to the [rfc2822](https://tools.ietf.org/html/rfc2822#section-3.3) standard
267
- * @returns {boolean} the result of the conformance check
268
- */
269
- function isRFC2822Date(date) {
270
- return rfc2822re.test(date);
271
- }
272
-
273
- // adapted from https://github.com/emailjs/emailjs-mime-codec/blob/6909c706b9f09bc0e5c3faf48f723cca53e5b352/src/mimecodec.js
274
- const encoder = new util.TextEncoder();
275
- /**
276
- * @see https://tools.ietf.org/html/rfc2045#section-6.7
277
- */
278
- const RANGES = [
279
- [0x09],
280
- [0x0a],
281
- [0x0d],
282
- [0x20, 0x3c],
283
- [0x3e, 0x7e],
284
- ];
285
- const LOOKUP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
286
- const MAX_CHUNK_LENGTH = 16383; // must be multiple of 3
287
- const MAX_MIME_WORD_LENGTH = 52;
288
- const MAX_B64_MIME_WORD_BYTE_LENGTH = 39;
289
- function tripletToBase64(num) {
290
- return (LOOKUP[(num >> 18) & 0x3f] +
291
- LOOKUP[(num >> 12) & 0x3f] +
292
- LOOKUP[(num >> 6) & 0x3f] +
293
- LOOKUP[num & 0x3f]);
294
- }
295
- function encodeChunk(uint8, start, end) {
296
- let output = '';
297
- for (let i = start; i < end; i += 3) {
298
- output += tripletToBase64((uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]);
299
- }
300
- return output;
301
- }
302
- function encodeBase64(data) {
303
- const len = data.length;
304
- const extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
305
- let output = '';
306
- // go through the array every three bytes, we'll deal with trailing stuff later
307
- for (let i = 0, len2 = len - extraBytes; i < len2; i += MAX_CHUNK_LENGTH) {
308
- output += encodeChunk(data, i, i + MAX_CHUNK_LENGTH > len2 ? len2 : i + MAX_CHUNK_LENGTH);
309
- }
310
- // pad the end with zeros, but make sure to not forget the extra bytes
311
- if (extraBytes === 1) {
312
- const tmp = data[len - 1];
313
- output += LOOKUP[tmp >> 2];
314
- output += LOOKUP[(tmp << 4) & 0x3f];
315
- output += '==';
316
- }
317
- else if (extraBytes === 2) {
318
- const tmp = (data[len - 2] << 8) + data[len - 1];
319
- output += LOOKUP[tmp >> 10];
320
- output += LOOKUP[(tmp >> 4) & 0x3f];
321
- output += LOOKUP[(tmp << 2) & 0x3f];
322
- output += '=';
323
- }
324
- return output;
325
- }
326
- /**
327
- * Splits a mime encoded string. Needed for dividing mime words into smaller chunks
328
- *
329
- * @param {string} str Mime encoded string to be split up
330
- * @param {number} maxlen Maximum length of characters for one part (minimum 12)
331
- * @return {string[]} lines
332
- */
333
- function splitMimeEncodedString(str, maxlen = 12) {
334
- const minWordLength = 12; // require at least 12 symbols to fit possible 4 octet UTF-8 sequences
335
- const maxWordLength = Math.max(maxlen, minWordLength);
336
- const lines = [];
337
- while (str.length) {
338
- let curLine = str.substr(0, maxWordLength);
339
- const match = curLine.match(/=[0-9A-F]?$/i); // skip incomplete escaped char
340
- if (match) {
341
- curLine = curLine.substr(0, match.index);
342
- }
343
- let done = false;
344
- while (!done) {
345
- let chr;
346
- done = true;
347
- const match = str.substr(curLine.length).match(/^=([0-9A-F]{2})/i); // check if not middle of a unicode char sequence
348
- if (match) {
349
- chr = parseInt(match[1], 16);
350
- // invalid sequence, move one char back anc recheck
351
- if (chr < 0xc2 && chr > 0x7f) {
352
- curLine = curLine.substr(0, curLine.length - 3);
353
- done = false;
354
- }
355
- }
356
- }
357
- if (curLine.length) {
358
- lines.push(curLine);
359
- }
360
- str = str.substr(curLine.length);
361
- }
362
- return lines;
363
- }
364
- /**
365
- *
366
- * @param {number} nr number
367
- * @returns {boolean} if number is in range
368
- */
369
- function checkRanges(nr) {
370
- return RANGES.reduce((val, range) => val ||
371
- (range.length === 1 && nr === range[0]) ||
372
- (range.length === 2 && nr >= range[0] && nr <= range[1]), false);
373
- }
374
- /**
375
- * Encodes all non printable and non ascii bytes to =XX form, where XX is the
376
- * byte value in hex. This function does not convert linebreaks etc. it
377
- * only escapes character sequences
378
- *
379
- * NOTE: Encoding support depends on util.TextDecoder, which is severely limited
380
- * prior to Node.js 13.
381
- *
382
- * @see https://nodejs.org/api/util.html#util_whatwg_supported_encodings
383
- * @see https://github.com/nodejs/node/issues/19214
384
- *
385
- * @param {string|Uint8Array} data Either a string or an Uint8Array
386
- * @param {string} encoding WHATWG supported encoding
387
- * @return {string} Mime encoded string
388
- */
389
- function mimeEncode(data = '', encoding = 'utf-8') {
390
- const decoder = new util.TextDecoder(encoding);
391
- const buffer = typeof data === 'string'
392
- ? encoder.encode(data)
393
- : encoder.encode(decoder.decode(data));
394
- return buffer.reduce((aggregate, ord, index) => checkRanges(ord) &&
395
- !((ord === 0x20 || ord === 0x09) &&
396
- (index === buffer.length - 1 ||
397
- buffer[index + 1] === 0x0a ||
398
- buffer[index + 1] === 0x0d))
399
- ? // if the char is in allowed range, then keep as is, unless it is a ws in the end of a line
400
- aggregate + String.fromCharCode(ord)
401
- : `${aggregate}=${ord < 0x10 ? '0' : ''}${ord
402
- .toString(16)
403
- .toUpperCase()}`, '');
404
- }
405
- /**
406
- * Encodes a string or an Uint8Array to an UTF-8 MIME Word
407
- *
408
- * NOTE: Encoding support depends on util.TextDecoder, which is severely limited
409
- * prior to Node.js 13.
410
- *
411
- * @see https://tools.ietf.org/html/rfc2047
412
- * @see https://nodejs.org/api/util.html#util_whatwg_supported_encodings
413
- * @see https://github.com/nodejs/node/issues/19214
414
- *
415
- * @param {string|Uint8Array} data String to be encoded
416
- * @param {'Q' | 'B'} mimeWordEncoding='Q' Encoding for the mime word, either Q or B
417
- * @param {string} encoding WHATWG supported encoding
418
- * @return {string} Single or several mime words joined together
419
- */
420
- function mimeWordEncode(data, mimeWordEncoding = 'Q', encoding = 'utf-8') {
421
- let parts = [];
422
- const decoder = new util.TextDecoder(encoding);
423
- const str = typeof data === 'string' ? data : decoder.decode(data);
424
- if (mimeWordEncoding === 'Q') {
425
- const encodedStr = mimeEncode(str, encoding).replace(/[^a-z0-9!*+\-/=]/gi, (chr) => chr === ' '
426
- ? '_'
427
- : '=' +
428
- (chr.charCodeAt(0) < 0x10 ? '0' : '') +
429
- chr.charCodeAt(0).toString(16).toUpperCase());
430
- parts =
431
- encodedStr.length < MAX_MIME_WORD_LENGTH
432
- ? [encodedStr]
433
- : splitMimeEncodedString(encodedStr, MAX_MIME_WORD_LENGTH);
434
- }
435
- else {
436
- // Fits as much as possible into every line without breaking utf-8 multibyte characters' octets up across lines
437
- let j = 0;
438
- let i = 0;
439
- while (i < str.length) {
440
- if (encoder.encode(str.substring(j, i)).length >
441
- MAX_B64_MIME_WORD_BYTE_LENGTH) {
442
- // we went one character too far, substring at the char before
443
- parts.push(str.substring(j, i - 1));
444
- j = i - 1;
445
- }
446
- else {
447
- i++;
448
- }
449
- }
450
- // add the remainder of the string
451
- str.substring(j) && parts.push(str.substring(j));
452
- parts = parts.map((x) => encoder.encode(x)).map((x) => encodeBase64(x));
453
- }
454
- return parts
455
- .map((p) => `=?UTF-8?${mimeWordEncoding}?${p}?= `)
456
- .join('')
457
- .trim();
458
- }
459
-
460
- const CRLF$1 = '\r\n';
461
- /**
462
- * MIME standard wants 76 char chunks when sending out.
463
- */
464
- const MIMECHUNK = 76;
465
- /**
466
- * meets both base64 and mime divisibility
467
- */
468
- const MIME64CHUNK = (MIMECHUNK * 6);
469
- /**
470
- * size of the message stream buffer
471
- */
472
- const BUFFERSIZE = (MIMECHUNK * 24 * 7);
473
- let counter = 0;
474
- function generateBoundary() {
475
- let text = '';
476
- const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'()+_,-./:=?";
477
- for (let i = 0; i < 69; i++) {
478
- text += possible.charAt(Math.floor(Math.random() * possible.length));
479
- }
480
- return text;
481
- }
482
- function convertPersonToAddress(person) {
483
- return addressparser(person)
484
- .map(({ name, address }) => {
485
- return name
486
- ? `${mimeWordEncode(name).replace(/,/g, '=2C')} <${address}>`
487
- : address;
488
- })
489
- .join(', ');
490
- }
491
- function convertDashDelimitedTextToSnakeCase(text) {
492
- return text
493
- .toLowerCase()
494
- .replace(/^(.)|-(.)/g, (match) => match.toUpperCase());
495
- }
496
- class Message {
497
- /**
498
- * Construct an rfc2822-compliant message object.
499
- *
500
- * Special notes:
501
- * - The `from` field is required.
502
- * - At least one `to`, `cc`, or `bcc` header is also required.
503
- * - You can also add whatever other headers you want.
504
- *
505
- * @see https://tools.ietf.org/html/rfc2822
506
- * @param {Partial<MessageHeaders>} headers Message headers
507
- */
508
- constructor(headers) {
509
- this.attachments = [];
510
- this.header = {
511
- 'message-id': `<${new Date().getTime()}.${counter++}.${process.pid}@${os.hostname()}>`,
512
- date: getRFC2822Date(),
513
- };
514
- this.content = 'text/plain; charset=utf-8';
515
- this.alternative = null;
516
- for (const header in headers) {
517
- // allow user to override default content-type to override charset or send a single non-text message
518
- if (/^content-type$/i.test(header)) {
519
- this.content = headers[header];
520
- }
521
- else if (header === 'text') {
522
- this.text = headers[header];
523
- }
524
- else if (header === 'attachment' &&
525
- typeof headers[header] === 'object') {
526
- const attachment = headers[header];
527
- if (Array.isArray(attachment)) {
528
- for (let i = 0; i < attachment.length; i++) {
529
- this.attach(attachment[i]);
530
- }
531
- }
532
- else if (attachment != null) {
533
- this.attach(attachment);
534
- }
535
- }
536
- else if (header === 'subject') {
537
- this.header.subject = mimeWordEncode(headers.subject);
538
- }
539
- else if (/^(cc|bcc|to|from)/i.test(header)) {
540
- this.header[header.toLowerCase()] = convertPersonToAddress(headers[header]);
541
- }
542
- else {
543
- // allow any headers the user wants to set??
544
- this.header[header.toLowerCase()] = headers[header];
545
- }
546
- }
547
- }
548
- /**
549
- * Attach a file to the message.
550
- *
551
- * Can be called multiple times, each adding a new attachment.
552
- *
553
- * @public
554
- * @param {MessageAttachment} options attachment options
555
- * @returns {Message} the current instance for chaining
556
- */
557
- attach(options) {
558
- // sender can specify an attachment as an alternative
559
- if (options.alternative) {
560
- this.alternative = options;
561
- this.alternative.charset = options.charset || 'utf-8';
562
- this.alternative.type = options.type || 'text/html';
563
- this.alternative.inline = true;
564
- }
565
- else {
566
- this.attachments.push(options);
567
- }
568
- return this;
569
- }
570
- /**
571
- * @public
572
- * @returns {{ isValid: boolean, validationError: (string | undefined) }} an object specifying whether this message is validly formatted, and the first validation error if it is not.
573
- */
574
- checkValidity() {
575
- if (typeof this.header.from !== 'string' &&
576
- Array.isArray(this.header.from) === false) {
577
- return {
578
- isValid: false,
579
- validationError: 'Message must have a `from` header',
580
- };
581
- }
582
- if (typeof this.header.to !== 'string' &&
583
- Array.isArray(this.header.to) === false &&
584
- typeof this.header.cc !== 'string' &&
585
- Array.isArray(this.header.cc) === false &&
586
- typeof this.header.bcc !== 'string' &&
587
- Array.isArray(this.header.bcc) === false) {
588
- return {
589
- isValid: false,
590
- validationError: 'Message must have at least one `to`, `cc`, or `bcc` header',
591
- };
592
- }
593
- if (this.attachments.length > 0) {
594
- const failed = [];
595
- this.attachments.forEach((attachment) => {
596
- if (attachment.path) {
597
- if (fs.existsSync(attachment.path) === false) {
598
- failed.push(`${attachment.path} does not exist`);
599
- }
600
- }
601
- else if (attachment.stream) {
602
- if (!attachment.stream.readable) {
603
- failed.push('attachment stream is not readable');
604
- }
605
- }
606
- else if (!attachment.data) {
607
- failed.push('attachment has no data associated with it');
608
- }
609
- });
610
- return {
611
- isValid: failed.length === 0,
612
- validationError: failed.join(', '),
613
- };
614
- }
615
- return { isValid: true, validationError: undefined };
616
- }
617
- /**
618
- * @public
619
- * @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.
620
- * @param {function(isValid: boolean, invalidReason: (string | undefined)): void} callback .
621
- * @returns {void}
622
- */
623
- valid(callback) {
624
- const { isValid, validationError } = this.checkValidity();
625
- callback(isValid, validationError);
626
- }
627
- /**
628
- * @public
629
- * @returns {MessageStream} a stream of the current message
630
- */
631
- stream() {
632
- return new MessageStream(this);
633
- }
634
- /**
635
- * @public
636
- * @param {function(Error, string): void} callback the function to call with the error and buffer
637
- * @returns {void}
638
- */
639
- read(callback) {
640
- let buffer = '';
641
- const str = this.stream();
642
- str.on('data', (data) => (buffer += data));
643
- str.on('end', (err) => callback(err, buffer));
644
- str.on('error', (err) => callback(err, buffer));
645
- }
646
- readAsync() {
647
- return new Promise((resolve, reject) => {
648
- this.read((err, buffer) => {
649
- if (err != null) {
650
- reject(err);
651
- }
652
- else {
653
- resolve(buffer);
654
- }
655
- });
656
- });
657
- }
658
- }
659
- class MessageStream extends stream.Stream {
660
- /**
661
- * @param {Message} message the message to stream
662
- */
663
- constructor(message) {
664
- super();
665
- this.message = message;
666
- this.readable = true;
667
- this.paused = false;
668
- this.buffer = Buffer.alloc(MIMECHUNK * 24 * 7);
669
- this.bufferIndex = 0;
670
- /**
671
- * @param {string} [data] the data to output
672
- * @param {Function} [callback] the function
673
- * @param {any[]} [args] array of arguments to pass to the callback
674
- * @returns {void}
675
- */
676
- const output = (data) => {
677
- // can we buffer the data?
678
- if (this.buffer != null) {
679
- const bytes = Buffer.byteLength(data);
680
- if (bytes + this.bufferIndex < this.buffer.length) {
681
- this.buffer.write(data, this.bufferIndex);
682
- this.bufferIndex += bytes;
683
- }
684
- // we can't buffer the data, so ship it out!
685
- else if (bytes > this.buffer.length) {
686
- if (this.bufferIndex) {
687
- this.emit('data', this.buffer.toString('utf-8', 0, this.bufferIndex));
688
- this.bufferIndex = 0;
689
- }
690
- const loops = Math.ceil(data.length / this.buffer.length);
691
- let loop = 0;
692
- while (loop < loops) {
693
- this.emit('data', data.substring(this.buffer.length * loop, this.buffer.length * (loop + 1)));
694
- loop++;
695
- }
696
- } // we need to clean out the buffer, it is getting full
697
- else {
698
- if (!this.paused) {
699
- this.emit('data', this.buffer.toString('utf-8', 0, this.bufferIndex));
700
- this.buffer.write(data, 0);
701
- this.bufferIndex = bytes;
702
- }
703
- else {
704
- // we can't empty out the buffer, so let's wait till we resume before adding to it
705
- this.once('resume', () => output(data));
706
- }
707
- }
708
- }
709
- };
710
- /**
711
- * @param {MessageAttachment} [attachment] the attachment whose headers you would like to output
712
- * @returns {void}
713
- */
714
- const outputAttachmentHeaders = (attachment) => {
715
- let data = [];
716
- const headers = {
717
- 'content-type': attachment.type +
718
- (attachment.charset ? `; charset=${attachment.charset}` : '') +
719
- (attachment.method ? `; method=${attachment.method}` : ''),
720
- 'content-transfer-encoding': 'base64',
721
- 'content-disposition': attachment.inline
722
- ? 'inline'
723
- : `attachment; filename="${mimeWordEncode(attachment.name)}"`,
724
- };
725
- // allow sender to override default headers
726
- if (attachment.headers != null) {
727
- for (const header in attachment.headers) {
728
- headers[header.toLowerCase()] = attachment.headers[header];
729
- }
730
- }
731
- for (const header in headers) {
732
- data = data.concat([
733
- convertDashDelimitedTextToSnakeCase(header),
734
- ': ',
735
- headers[header],
736
- CRLF$1,
737
- ]);
738
- }
739
- output(data.concat([CRLF$1]).join(''));
740
- };
741
- /**
742
- * @param {string} data the data to output as base64
743
- * @param {function(): void} [callback] the function to call after output is finished
744
- * @returns {void}
745
- */
746
- const outputBase64 = (data, callback) => {
747
- const loops = Math.ceil(data.length / MIMECHUNK);
748
- let loop = 0;
749
- while (loop < loops) {
750
- output(data.substring(MIMECHUNK * loop, MIMECHUNK * (loop + 1)) + CRLF$1);
751
- loop++;
752
- }
753
- if (callback) {
754
- callback();
755
- }
756
- };
757
- const outputFile = (attachment, next) => {
758
- var _a;
759
- const chunk = MIME64CHUNK * 16;
760
- const buffer = Buffer.alloc(chunk);
761
- const inputEncoding = ((_a = attachment === null || attachment === void 0 ? void 0 : attachment.headers) === null || _a === void 0 ? void 0 : _a['content-transfer-encoding']) || 'base64';
762
- const encoding = inputEncoding === '7bit'
763
- ? 'ascii'
764
- : inputEncoding === '8bit'
765
- ? 'binary'
766
- : inputEncoding;
767
- /**
768
- * @param {Error} err the error to emit
769
- * @param {number} fd the file descriptor
770
- * @returns {void}
771
- */
772
- const opened = (err, fd) => {
773
- if (err) {
774
- this.emit('error', err);
775
- return;
776
- }
777
- const readBytes = (err, bytes) => {
778
- if (err || this.readable === false) {
779
- this.emit('error', err || new Error('message stream was interrupted somehow!'));
780
- return;
781
- }
782
- // guaranteed to be encoded without padding unless it is our last read
783
- outputBase64(buffer.toString(encoding, 0, bytes), () => {
784
- if (bytes == chunk) {
785
- // we read a full chunk, there might be more
786
- fs.read(fd, buffer, 0, chunk, null, readBytes);
787
- } // that was the last chunk, we are done reading the file
788
- else {
789
- this.removeListener('error', fs.closeSync);
790
- fs.close(fd, next);
791
- }
792
- });
793
- };
794
- fs.read(fd, buffer, 0, chunk, null, readBytes);
795
- this.once('error', fs.closeSync);
796
- };
797
- fs.open(attachment.path, 'r', opened);
798
- };
799
- /**
800
- * @param {MessageAttachment} attachment the metadata to use as headers
801
- * @param {function(): void} callback the function to call after output is finished
802
- * @returns {void}
803
- */
804
- const outputStream = (attachment, callback) => {
805
- const { stream } = attachment;
806
- if (stream === null || stream === void 0 ? void 0 : stream.readable) {
807
- let previous = Buffer.alloc(0);
808
- stream.resume();
809
- stream.on('end', () => {
810
- outputBase64(previous.toString('base64'), callback);
811
- this.removeListener('pause', stream.pause);
812
- this.removeListener('resume', stream.resume);
813
- this.removeListener('error', stream.resume);
814
- });
815
- stream.on('data', (buff) => {
816
- // do we have bytes from a previous stream data event?
817
- let buffer = Buffer.isBuffer(buff) ? buff : Buffer.from(buff);
818
- if (previous.byteLength > 0) {
819
- buffer = Buffer.concat([previous, buffer]);
820
- }
821
- const padded = buffer.length % MIME64CHUNK;
822
- previous = Buffer.alloc(padded);
823
- // encode as much of the buffer to base64 without empty bytes
824
- if (padded > 0) {
825
- // copy dangling bytes into previous buffer
826
- buffer.copy(previous, 0, buffer.length - padded);
827
- }
828
- outputBase64(buffer.toString('base64', 0, buffer.length - padded));
829
- });
830
- this.on('pause', stream.pause);
831
- this.on('resume', stream.resume);
832
- this.on('error', stream.resume);
833
- }
834
- else {
835
- this.emit('error', { message: 'stream not readable' });
836
- }
837
- };
838
- const outputAttachment = (attachment, callback) => {
839
- const build = attachment.path
840
- ? outputFile
841
- : attachment.stream
842
- ? outputStream
843
- : outputData;
844
- outputAttachmentHeaders(attachment);
845
- build(attachment, callback);
846
- };
847
- /**
848
- * @param {string} boundary the boundary text between outputs
849
- * @param {MessageAttachment[]} list the list of potential messages to output
850
- * @param {number} index the index of the list item to output
851
- * @param {function(): void} callback the function to call if index is greater than upper bound
852
- * @returns {void}
853
- */
854
- const outputMessage = (boundary, list, index, callback) => {
855
- if (index < list.length) {
856
- output(`--${boundary}${CRLF$1}`);
857
- if (list[index].related) {
858
- outputRelated(list[index], () => outputMessage(boundary, list, index + 1, callback));
859
- }
860
- else {
861
- outputAttachment(list[index], () => outputMessage(boundary, list, index + 1, callback));
862
- }
863
- }
864
- else {
865
- output(`${CRLF$1}--${boundary}--${CRLF$1}${CRLF$1}`);
866
- callback();
867
- }
868
- };
869
- const outputMixed = () => {
870
- const boundary = generateBoundary();
871
- output(`Content-Type: multipart/mixed; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
872
- if (this.message.alternative == null) {
873
- outputText(this.message);
874
- outputMessage(boundary, this.message.attachments, 0, close);
875
- }
876
- else {
877
- outputAlternative(
878
- // typescript bug; should narrow to { alternative: MessageAttachment }
879
- this.message, () => outputMessage(boundary, this.message.attachments, 0, close));
880
- }
881
- };
882
- /**
883
- * @param {MessageAttachment} attachment the metadata to use as headers
884
- * @param {function(): void} callback the function to call after output is finished
885
- * @returns {void}
886
- */
887
- const outputData = (attachment, callback) => {
888
- var _a, _b;
889
- outputBase64(attachment.encoded
890
- ? (_a = attachment.data) !== null && _a !== void 0 ? _a : '' : Buffer.from((_b = attachment.data) !== null && _b !== void 0 ? _b : '').toString('base64'), callback);
891
- };
892
- /**
893
- * @param {Message} message the message to output
894
- * @returns {void}
895
- */
896
- const outputText = (message) => {
897
- let data = [];
898
- data = data.concat([
899
- 'Content-Type:',
900
- message.content,
901
- CRLF$1,
902
- 'Content-Transfer-Encoding: 7bit',
903
- CRLF$1,
904
- ]);
905
- data = data.concat(['Content-Disposition: inline', CRLF$1, CRLF$1]);
906
- data = data.concat([message.text || '', CRLF$1, CRLF$1]);
907
- output(data.join(''));
908
- };
909
- /**
910
- * @param {MessageAttachment} message the message to output
911
- * @param {function(): void} callback the function to call after output is finished
912
- * @returns {void}
913
- */
914
- const outputRelated = (message, callback) => {
915
- const boundary = generateBoundary();
916
- output(`Content-Type: multipart/related; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
917
- outputAttachment(message, () => {
918
- var _a;
919
- outputMessage(boundary, (_a = message.related) !== null && _a !== void 0 ? _a : [], 0, () => {
920
- output(`${CRLF$1}--${boundary}--${CRLF$1}${CRLF$1}`);
921
- callback();
922
- });
923
- });
924
- };
925
- /**
926
- * @param {Message} message the message to output
927
- * @param {function(): void} callback the function to call after output is finished
928
- * @returns {void}
929
- */
930
- const outputAlternative = (message, callback) => {
931
- const boundary = generateBoundary();
932
- output(`Content-Type: multipart/alternative; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
933
- outputText(message);
934
- output(`--${boundary}${CRLF$1}`);
935
- /**
936
- * @returns {void}
937
- */
938
- const finish = () => {
939
- output([CRLF$1, '--', boundary, '--', CRLF$1, CRLF$1].join(''));
940
- callback();
941
- };
942
- if (message.alternative.related) {
943
- outputRelated(message.alternative, finish);
944
- }
945
- else {
946
- outputAttachment(message.alternative, finish);
947
- }
948
- };
949
- const close = (err) => {
950
- var _a, _b;
951
- if (err) {
952
- this.emit('error', err);
953
- }
954
- else {
955
- 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 : '');
956
- this.emit('end');
957
- }
958
- this.buffer = null;
959
- this.bufferIndex = 0;
960
- this.readable = false;
961
- this.removeAllListeners('resume');
962
- this.removeAllListeners('pause');
963
- this.removeAllListeners('error');
964
- this.removeAllListeners('data');
965
- this.removeAllListeners('end');
966
- };
967
- /**
968
- * @returns {void}
969
- */
970
- const outputHeaderData = () => {
971
- if (this.message.attachments.length || this.message.alternative) {
972
- output(`MIME-Version: 1.0${CRLF$1}`);
973
- outputMixed();
974
- } // you only have a text message!
975
- else {
976
- outputText(this.message);
977
- close();
978
- }
979
- };
980
- /**
981
- * @returns {void}
982
- */
983
- const outputHeader = () => {
984
- let data = [];
985
- for (const header in this.message.header) {
986
- // do not output BCC in the headers (regex) nor custom Object.prototype functions...
987
- if (!/bcc/i.test(header) &&
988
- Object.prototype.hasOwnProperty.call(this.message.header, header)) {
989
- data = data.concat([
990
- convertDashDelimitedTextToSnakeCase(header),
991
- ': ',
992
- this.message.header[header],
993
- CRLF$1,
994
- ]);
995
- }
996
- }
997
- output(data.join(''));
998
- outputHeaderData();
999
- };
1000
- this.once('destroy', close);
1001
- process.nextTick(outputHeader);
1002
- }
1003
- /**
1004
- * @public
1005
- * pause the stream
1006
- * @returns {void}
1007
- */
1008
- pause() {
1009
- this.paused = true;
1010
- this.emit('pause');
1011
- }
1012
- /**
1013
- * @public
1014
- * resume the stream
1015
- * @returns {void}
1016
- */
1017
- resume() {
1018
- this.paused = false;
1019
- this.emit('resume');
1020
- }
1021
- /**
1022
- * @public
1023
- * destroy the stream
1024
- * @returns {void}
1025
- */
1026
- destroy() {
1027
- this.emit('destroy', this.bufferIndex > 0 ? { message: 'message stream destroyed' } : null);
1028
- }
1029
- /**
1030
- * @public
1031
- * destroy the stream at first opportunity
1032
- * @returns {void}
1033
- */
1034
- destroySoon() {
1035
- this.emit('destroy');
1036
- }
1037
- }
1038
-
1039
- /**
1040
- * @readonly
1041
- * @enum
1042
- */
1043
- const SMTPErrorStates = {
1044
- COULDNOTCONNECT: 1,
1045
- BADRESPONSE: 2,
1046
- AUTHFAILED: 3,
1047
- TIMEDOUT: 4,
1048
- ERROR: 5,
1049
- NOCONNECTION: 6,
1050
- AUTHNOTSUPPORTED: 7,
1051
- CONNECTIONCLOSED: 8,
1052
- CONNECTIONENDED: 9,
1053
- CONNECTIONAUTH: 10,
1054
- };
1055
- class SMTPError extends Error {
1056
- /**
1057
- * @protected
1058
- * @param {string} message error message
1059
- */
1060
- constructor(message) {
1061
- super(message);
1062
- this.code = null;
1063
- this.smtp = null;
1064
- this.previous = null;
1065
- }
1066
- /**
1067
- *
1068
- * @param {string} message error message
1069
- * @param {number} code smtp error state
1070
- * @param {Error | null} error previous error
1071
- * @param {unknown} smtp arbitrary data
1072
- * @returns {SMTPError} error
1073
- */
1074
- static create(message, code, error, smtp) {
1075
- const msg = (error === null || error === void 0 ? void 0 : error.message) ? `${message} (${error.message})` : message;
1076
- const err = new SMTPError(msg);
1077
- err.code = code;
1078
- err.smtp = smtp;
1079
- if (error) {
1080
- err.previous = error;
1081
- }
1082
- return err;
1083
- }
1084
- }
1085
-
1086
- class SMTPResponseMonitor {
1087
- constructor(stream, timeout, onerror) {
1088
- let buffer = '';
1089
- const notify = () => {
1090
- var _a, _b;
1091
- if (buffer.length) {
1092
- // parse buffer for response codes
1093
- const line = buffer.replace('\r', '');
1094
- if (!((_b = (_a = line
1095
- .trim()
1096
- .split(/\n/)
1097
- .pop()) === null || _a === void 0 ? void 0 : _a.match(/^(\d{3})\s/)) !== null && _b !== void 0 ? _b : false)) {
1098
- return;
1099
- }
1100
- const match = line ? line.match(/(\d+)\s?(.*)/) : null;
1101
- const data = match !== null
1102
- ? { code: match[1], message: match[2], data: line }
1103
- : { code: -1, data: line };
1104
- stream.emit('response', null, data);
1105
- buffer = '';
1106
- }
1107
- };
1108
- const error = (err) => {
1109
- stream.emit('response', SMTPError.create('connection encountered an error', SMTPErrorStates.ERROR, err));
1110
- };
1111
- const timedout = (err) => {
1112
- stream.end();
1113
- stream.emit('response', SMTPError.create('timedout while connecting to smtp server', SMTPErrorStates.TIMEDOUT, err));
1114
- };
1115
- const watch = (data) => {
1116
- if (data !== null) {
1117
- buffer += data.toString();
1118
- notify();
1119
- }
1120
- };
1121
- const close = (err) => {
1122
- stream.emit('response', SMTPError.create('connection has closed', SMTPErrorStates.CONNECTIONCLOSED, err));
1123
- };
1124
- const end = (err) => {
1125
- stream.emit('response', SMTPError.create('connection has ended', SMTPErrorStates.CONNECTIONENDED, err));
1126
- };
1127
- this.stop = (err) => {
1128
- stream.removeAllListeners('response');
1129
- stream.removeListener('data', watch);
1130
- stream.removeListener('end', end);
1131
- stream.removeListener('close', close);
1132
- stream.removeListener('error', error);
1133
- if (err != null && typeof onerror === 'function') {
1134
- onerror(err);
1135
- }
1136
- };
1137
- stream.on('data', watch);
1138
- stream.on('end', end);
1139
- stream.on('close', close);
1140
- stream.on('error', error);
1141
- stream.setTimeout(timeout, timedout);
1142
- }
1143
- }
1144
-
1145
- /**
1146
- * @readonly
1147
- * @enum
1148
- */
1149
- const AUTH_METHODS = {
1150
- PLAIN: 'PLAIN',
1151
- 'CRAM-MD5': 'CRAM-MD5',
1152
- LOGIN: 'LOGIN',
1153
- XOAUTH2: 'XOAUTH2',
1154
- };
1155
- /**
1156
- * @readonly
1157
- * @enum
1158
- */
1159
- const SMTPState = {
1160
- NOTCONNECTED: 0,
1161
- CONNECTING: 1,
1162
- CONNECTED: 2,
1163
- };
1164
- const DEFAULT_TIMEOUT = 5000;
1165
- const SMTP_PORT = 25;
1166
- const SMTP_SSL_PORT = 465;
1167
- const SMTP_TLS_PORT = 587;
1168
- const CRLF = '\r\n';
1169
- const GREYLIST_DELAY = 300;
1170
- let DEBUG = 0;
1171
- /**
1172
- * @param {...any[]} args the message(s) to log
1173
- * @returns {void}
1174
- */
1175
- const log = (...args) => {
1176
- if (DEBUG === 1) {
1177
- args.forEach((d) => console.log(typeof d === 'object'
1178
- ? d instanceof Error
1179
- ? d.message
1180
- : JSON.stringify(d)
1181
- : d));
1182
- }
1183
- };
1184
- /**
1185
- * @param {function(...any[]): void} callback the function to call
1186
- * @param {...any[]} args the arguments to apply to the function
1187
- * @returns {void}
1188
- */
1189
- const caller = (callback, ...args) => {
1190
- if (typeof callback === 'function') {
1191
- callback(...args);
1192
- }
1193
- };
1194
- class SMTPConnection extends events.EventEmitter {
1195
- /**
1196
- * SMTP class written using python's (2.7) smtplib.py as a base.
1197
- *
1198
- * To target a Message Transfer Agent (MTA), omit all options.
1199
- *
1200
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
1201
- */
1202
- constructor({ timeout, host, user, password, domain, port, ssl, tls, logger, authentication, } = {}) {
1203
- var _a;
1204
- super();
1205
- this.timeout = DEFAULT_TIMEOUT;
1206
- this.log = log;
1207
- this.authentication = [
1208
- AUTH_METHODS['CRAM-MD5'],
1209
- AUTH_METHODS.LOGIN,
1210
- AUTH_METHODS.PLAIN,
1211
- AUTH_METHODS.XOAUTH2,
1212
- ];
1213
- this._state = SMTPState.NOTCONNECTED;
1214
- this._secure = false;
1215
- this.loggedin = false;
1216
- this.sock = null;
1217
- this.features = null;
1218
- this.monitor = null;
1219
- this.domain = os.hostname();
1220
- this.host = 'localhost';
1221
- this.ssl = false;
1222
- this.tls = false;
1223
- this.greylistResponseTracker = new WeakSet();
1224
- if (Array.isArray(authentication)) {
1225
- this.authentication = authentication;
1226
- }
1227
- if (typeof timeout === 'number') {
1228
- this.timeout = timeout;
1229
- }
1230
- if (typeof domain === 'string') {
1231
- this.domain = domain;
1232
- }
1233
- if (typeof host === 'string') {
1234
- this.host = host;
1235
- }
1236
- if (ssl != null &&
1237
- (typeof ssl === 'boolean' ||
1238
- (typeof ssl === 'object' && Array.isArray(ssl) === false))) {
1239
- this.ssl = ssl;
1240
- }
1241
- if (tls != null &&
1242
- (typeof tls === 'boolean' ||
1243
- (typeof tls === 'object' && Array.isArray(tls) === false))) {
1244
- this.tls = tls;
1245
- }
1246
- this.port = port || (ssl ? SMTP_SSL_PORT : tls ? SMTP_TLS_PORT : SMTP_PORT);
1247
- this.loggedin = user && password ? false : true;
1248
- if (!user && ((_a = password === null || password === void 0 ? void 0 : password.length) !== null && _a !== void 0 ? _a : 0) > 0) {
1249
- throw new Error('`password` cannot be set without `user`');
1250
- }
1251
- // keep these strings hidden when quicky debugging/logging
1252
- this.user = () => user;
1253
- this.password = () => password;
1254
- if (typeof logger === 'function') {
1255
- this.log = log;
1256
- }
1257
- }
1258
- /**
1259
- * @public
1260
- * @param {0 | 1} level -
1261
- * @returns {void}
1262
- */
1263
- debug(level) {
1264
- DEBUG = level;
1265
- }
1266
- /**
1267
- * @public
1268
- * @returns {SMTPState} the current state
1269
- */
1270
- state() {
1271
- return this._state;
1272
- }
1273
- /**
1274
- * @public
1275
- * @returns {boolean} whether or not the instance is authorized
1276
- */
1277
- authorized() {
1278
- return this.loggedin;
1279
- }
1280
- /**
1281
- * Establish an SMTP connection.
1282
- *
1283
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
1284
- *
1285
- * @public
1286
- * @param {function(...any[]): void} callback function to call after response
1287
- * @param {number} [port] the port to use for the connection
1288
- * @param {string} [host] the hostname to use for the connection
1289
- * @param {ConnectOptions} [options={}] the options
1290
- * @returns {void}
1291
- */
1292
- connect(callback, port = this.port, host = this.host, options = {}) {
1293
- this.port = port;
1294
- this.host = host;
1295
- this.ssl = options.ssl || this.ssl;
1296
- if (this._state !== SMTPState.NOTCONNECTED) {
1297
- this.quit(() => this.connect(callback, port, host, options));
1298
- }
1299
- /**
1300
- * @returns {void}
1301
- */
1302
- const connected = () => {
1303
- this.log(`connected: ${this.host}:${this.port}`);
1304
- if (this.ssl && !this.tls) {
1305
- // if key/ca/cert was passed in, check if connection is authorized
1306
- if (typeof this.ssl !== 'boolean' &&
1307
- this.sock instanceof tls.TLSSocket &&
1308
- !this.sock.authorized) {
1309
- this.close(true);
1310
- caller(callback, SMTPError.create('could not establish an ssl connection', SMTPErrorStates.CONNECTIONAUTH));
1311
- }
1312
- else {
1313
- this._secure = true;
1314
- }
1315
- }
1316
- };
1317
- /**
1318
- * @param {Error} err err
1319
- * @returns {void}
1320
- */
1321
- const connectedErrBack = (err) => {
1322
- if (!err) {
1323
- connected();
1324
- }
1325
- else {
1326
- this.close(true);
1327
- this.log(err);
1328
- caller(callback, SMTPError.create('could not connect', SMTPErrorStates.COULDNOTCONNECT, err));
1329
- }
1330
- };
1331
- const response = (err, msg) => {
1332
- if (err) {
1333
- if (this._state === SMTPState.NOTCONNECTED && !this.sock) {
1334
- return;
1335
- }
1336
- this.close(true);
1337
- caller(callback, err);
1338
- }
1339
- else if (msg.code == '220') {
1340
- this.log(msg.data);
1341
- // might happen first, so no need to wait on connected()
1342
- this._state = SMTPState.CONNECTED;
1343
- caller(callback, null, msg.data);
1344
- }
1345
- else {
1346
- this.log(`response (data): ${msg.data}`);
1347
- this.quit(() => {
1348
- caller(callback, SMTPError.create('bad response on connection', SMTPErrorStates.BADRESPONSE, err, msg.data));
1349
- });
1350
- }
1351
- };
1352
- this._state = SMTPState.CONNECTING;
1353
- this.log(`connecting: ${this.host}:${this.port}`);
1354
- if (this.ssl) {
1355
- this.sock = tls.connect(this.port, this.host.trim(), typeof this.ssl === 'object' ? this.ssl : {}, connected);
1356
- }
1357
- else {
1358
- this.sock = new net.Socket();
1359
- this.sock.connect(this.port, this.host.trim(), connectedErrBack);
1360
- }
1361
- this.monitor = new SMTPResponseMonitor(this.sock, this.timeout, () => this.close(true));
1362
- this.sock.once('response', response);
1363
- this.sock.once('error', response); // the socket could reset or throw, so let's handle it and let the user know
1364
- }
1365
- /**
1366
- * @public
1367
- * @param {string} str the string to send
1368
- * @param {function(...any[]): void} callback function to call after response
1369
- * @returns {void}
1370
- */
1371
- send(str, callback) {
1372
- if (this.sock != null && this._state === SMTPState.CONNECTED) {
1373
- this.log(str);
1374
- this.sock.once('response', (err, msg) => {
1375
- if (err) {
1376
- caller(callback, err);
1377
- }
1378
- else {
1379
- this.log(msg.data);
1380
- caller(callback, null, msg);
1381
- }
1382
- });
1383
- if (this.sock.writable) {
1384
- this.sock.write(str);
1385
- }
1386
- }
1387
- else {
1388
- this.close(true);
1389
- caller(callback, SMTPError.create('no connection has been established', SMTPErrorStates.NOCONNECTION));
1390
- }
1391
- }
1392
- /**
1393
- * @public
1394
- * @param {string} cmd command to issue
1395
- * @param {function(...any[]): void} callback function to call after response
1396
- * @param {(number[] | number)} [codes=[250]] array codes
1397
- * @returns {void}
1398
- */
1399
- command(cmd, callback, codes = [250]) {
1400
- const codesArray = Array.isArray(codes)
1401
- ? codes
1402
- : typeof codes === 'number'
1403
- ? [codes]
1404
- : [250];
1405
- const response = (err, msg) => {
1406
- if (err) {
1407
- caller(callback, err);
1408
- }
1409
- else {
1410
- const code = Number(msg.code);
1411
- if (codesArray.indexOf(code) !== -1) {
1412
- caller(callback, err, msg.data, msg.message);
1413
- }
1414
- else if ((code === 450 || code === 451) &&
1415
- msg.message.toLowerCase().includes('greylist') &&
1416
- this.greylistResponseTracker.has(response) === false) {
1417
- this.greylistResponseTracker.add(response);
1418
- setTimeout(() => {
1419
- this.send(cmd + CRLF, response);
1420
- }, GREYLIST_DELAY);
1421
- }
1422
- else {
1423
- const suffix = msg.message ? `: ${msg.message}` : '';
1424
- const errorMessage = `bad response on command '${cmd.split(' ')[0]}'${suffix}`;
1425
- caller(callback, SMTPError.create(errorMessage, SMTPErrorStates.BADRESPONSE, null, msg.data));
1426
- }
1427
- }
1428
- };
1429
- this.greylistResponseTracker.delete(response);
1430
- this.send(cmd + CRLF, response);
1431
- }
1432
- /**
1433
- * @public
1434
- * @description SMTP 'helo' command.
1435
- *
1436
- * Hostname to send for self command defaults to the FQDN of the local
1437
- * host.
1438
- *
1439
- * As this command was deprecated by rfc2821, it should only be used for compatibility with non-compliant servers.
1440
- * @see https://tools.ietf.org/html/rfc2821#appendix-F.3
1441
- *
1442
- * @param {function(...any[]): void} callback function to call after response
1443
- * @param {string} domain the domain to associate with the 'helo' request
1444
- * @returns {void}
1445
- */
1446
- helo(callback, domain) {
1447
- this.command(`helo ${domain || this.domain}`, (err, data) => {
1448
- if (err) {
1449
- caller(callback, err);
1450
- }
1451
- else {
1452
- this.parse_smtp_features(data);
1453
- caller(callback, err, data);
1454
- }
1455
- });
1456
- }
1457
- /**
1458
- * @public
1459
- * @param {function(...any[]): void} callback function to call after response
1460
- * @returns {void}
1461
- */
1462
- starttls(callback) {
1463
- const response = (err, msg) => {
1464
- if (this.sock == null) {
1465
- throw new Error('null socket');
1466
- }
1467
- if (err) {
1468
- err.message += ' while establishing a starttls session';
1469
- caller(callback, err);
1470
- }
1471
- else {
1472
- const secureContext = tls.createSecureContext(typeof this.tls === 'object' ? this.tls : {});
1473
- const secureSocket = new tls.TLSSocket(this.sock, { secureContext });
1474
- secureSocket.on('error', (err) => {
1475
- this.close(true);
1476
- caller(callback, err);
1477
- });
1478
- this._secure = true;
1479
- this.sock = secureSocket;
1480
- new SMTPResponseMonitor(this.sock, this.timeout, () => this.close(true));
1481
- caller(callback, msg.data);
1482
- }
1483
- };
1484
- this.command('starttls', response, [220]);
1485
- }
1486
- /**
1487
- * @public
1488
- * @param {string} data the string to parse for features
1489
- * @returns {void}
1490
- */
1491
- parse_smtp_features(data) {
1492
- // According to RFC1869 some (badly written)
1493
- // MTA's will disconnect on an ehlo. Toss an exception if
1494
- // that happens -ddm
1495
- data.split('\n').forEach((ext) => {
1496
- const parse = ext.match(/^(?:\d+[-=]?)\s*?([^\s]+)(?:\s+(.*)\s*?)?$/);
1497
- // To be able to communicate with as many SMTP servers as possible,
1498
- // we have to take the old-style auth advertisement into account,
1499
- // because:
1500
- // 1) Else our SMTP feature parser gets confused.
1501
- // 2) There are some servers that only advertise the auth methods we
1502
- // support using the old style.
1503
- if (parse != null && this.features != null) {
1504
- // RFC 1869 requires a space between ehlo keyword and parameters.
1505
- // It's actually stricter, in that only spaces are allowed between
1506
- // parameters, but were not going to check for that here. Note
1507
- // that the space isn't present if there are no parameters.
1508
- this.features[parse[1].toLowerCase()] = parse[2] || true;
1509
- }
1510
- });
1511
- }
1512
- /**
1513
- * @public
1514
- * @param {function(...any[]): void} callback function to call after response
1515
- * @param {string} domain the domain to associate with the 'ehlo' request
1516
- * @returns {void}
1517
- */
1518
- ehlo(callback, domain) {
1519
- this.features = {};
1520
- this.command(`ehlo ${domain || this.domain}`, (err, data) => {
1521
- if (err) {
1522
- caller(callback, err);
1523
- }
1524
- else {
1525
- this.parse_smtp_features(data);
1526
- if (this.tls && !this._secure) {
1527
- this.starttls(() => this.ehlo(callback, domain));
1528
- }
1529
- else {
1530
- caller(callback, err, data);
1531
- }
1532
- }
1533
- });
1534
- }
1535
- /**
1536
- * @public
1537
- * @param {string} opt the features keyname to check
1538
- * @returns {boolean} whether the extension exists
1539
- */
1540
- has_extn(opt) {
1541
- var _a;
1542
- return ((_a = this.features) !== null && _a !== void 0 ? _a : {})[opt.toLowerCase()] === undefined;
1543
- }
1544
- /**
1545
- * @public
1546
- * @description SMTP 'help' command, returns text from the server
1547
- * @param {function(...any[]): void} callback function to call after response
1548
- * @param {string} domain the domain to associate with the 'help' request
1549
- * @returns {void}
1550
- */
1551
- help(callback, domain) {
1552
- this.command(domain ? `help ${domain}` : 'help', callback, [211, 214]);
1553
- }
1554
- /**
1555
- * @public
1556
- * @param {function(...any[]): void} callback function to call after response
1557
- * @returns {void}
1558
- */
1559
- rset(callback) {
1560
- this.command('rset', callback);
1561
- }
1562
- /**
1563
- * @public
1564
- * @param {function(...any[]): void} callback function to call after response
1565
- * @returns {void}
1566
- */
1567
- noop(callback) {
1568
- this.send('noop', callback);
1569
- }
1570
- /**
1571
- * @public
1572
- * @param {function(...any[]): void} callback function to call after response
1573
- * @param {string} from the sender
1574
- * @returns {void}
1575
- */
1576
- mail(callback, from) {
1577
- this.command(`mail FROM:${from}`, callback);
1578
- }
1579
- /**
1580
- * @public
1581
- * @param {function(...any[]): void} callback function to call after response
1582
- * @param {string} to the receiver
1583
- * @returns {void}
1584
- */
1585
- rcpt(callback, to) {
1586
- this.command(`RCPT TO:${to}`, callback, [250, 251]);
1587
- }
1588
- /**
1589
- * @public
1590
- * @param {function(...any[]): void} callback function to call after response
1591
- * @returns {void}
1592
- */
1593
- data(callback) {
1594
- this.command('data', callback, [354]);
1595
- }
1596
- /**
1597
- * @public
1598
- * @param {function(...any[]): void} callback function to call after response
1599
- * @returns {void}
1600
- */
1601
- data_end(callback) {
1602
- this.command(`${CRLF}.`, callback);
1603
- }
1604
- /**
1605
- * @public
1606
- * @param {string} data the message to send
1607
- * @returns {void}
1608
- */
1609
- message(data) {
1610
- var _a, _b;
1611
- this.log(data);
1612
- (_b = (_a = this.sock) === null || _a === void 0 ? void 0 : _a.write(data)) !== null && _b !== void 0 ? _b : this.log('no socket to write to');
1613
- }
1614
- /**
1615
- * @public
1616
- * @description SMTP 'verify' command -- checks for address validity.
1617
- * @param {string} address the address to validate
1618
- * @param {function(...any[]): void} callback function to call after response
1619
- * @returns {void}
1620
- */
1621
- verify(address, callback) {
1622
- this.command(`vrfy ${address}`, callback, [250, 251, 252]);
1623
- }
1624
- /**
1625
- * @public
1626
- * @description SMTP 'expn' command -- expands a mailing list.
1627
- * @param {string} address the mailing list to expand
1628
- * @param {function(...any[]): void} callback function to call after response
1629
- * @returns {void}
1630
- */
1631
- expn(address, callback) {
1632
- this.command(`expn ${address}`, callback);
1633
- }
1634
- /**
1635
- * @public
1636
- * @description Calls this.ehlo() and, if an error occurs, this.helo().
1637
- *
1638
- * If there has been no previous EHLO or HELO command self session, self
1639
- * method tries ESMTP EHLO first.
1640
- *
1641
- * @param {function(...any[]): void} callback function to call after response
1642
- * @param {string} [domain] the domain to associate with the command
1643
- * @returns {void}
1644
- */
1645
- ehlo_or_helo_if_needed(callback, domain) {
1646
- // is this code callable...?
1647
- if (!this.features) {
1648
- const response = (err, data) => caller(callback, err, data);
1649
- this.ehlo((err, data) => {
1650
- if (err) {
1651
- this.helo(response, domain);
1652
- }
1653
- else {
1654
- caller(callback, err, data);
1655
- }
1656
- }, domain);
1657
- }
1658
- }
1659
- /**
1660
- * @public
1661
- *
1662
- * Log in on an SMTP server that requires authentication.
1663
- *
1664
- * If there has been no previous EHLO or HELO command self session, self
1665
- * method tries ESMTP EHLO first.
1666
- *
1667
- * This method will return normally if the authentication was successful.
1668
- *
1669
- * @param {function(...any[]): void} callback function to call after response
1670
- * @param {string} [user] the username to authenticate with
1671
- * @param {string} [password] the password for the authentication
1672
- * @param {{ method: string, domain: string }} [options] login options
1673
- * @returns {void}
1674
- */
1675
- login(callback, user, password, options = {}) {
1676
- var _a, _b;
1677
- const login = {
1678
- user: user ? () => user : this.user,
1679
- password: password ? () => password : this.password,
1680
- method: (_b = (_a = options === null || options === void 0 ? void 0 : options.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== null && _b !== void 0 ? _b : '',
1681
- };
1682
- const domain = (options === null || options === void 0 ? void 0 : options.domain) || this.domain;
1683
- const initiate = (err, data) => {
1684
- var _a;
1685
- if (err) {
1686
- caller(callback, err);
1687
- return;
1688
- }
1689
- let method = null;
1690
- /**
1691
- * @param {string} challenge challenge
1692
- * @returns {string} base64 cram hash
1693
- */
1694
- const encodeCramMd5 = (challenge) => {
1695
- const hmac = crypto.createHmac('md5', login.password());
1696
- hmac.update(Buffer.from(challenge, 'base64').toString('ascii'));
1697
- return Buffer.from(`${login.user()} ${hmac.digest('hex')}`).toString('base64');
1698
- };
1699
- /**
1700
- * @returns {string} base64 login/password
1701
- */
1702
- const encodePlain = () => Buffer.from(`\u0000${login.user()}\u0000${login.password()}`).toString('base64');
1703
- /**
1704
- * @see https://developers.google.com/gmail/xoauth2_protocol
1705
- * @returns {string} base64 xoauth2 auth token
1706
- */
1707
- const encodeXoauth2 = () => Buffer.from(`user=${login.user()}\u0001auth=Bearer ${login.password()}\u0001\u0001`).toString('base64');
1708
- // List of authentication methods we support: from preferred to
1709
- // less preferred methods.
1710
- if (!method) {
1711
- const preferred = this.authentication;
1712
- let auth = '';
1713
- if (typeof ((_a = this.features) === null || _a === void 0 ? void 0 : _a['auth']) === 'string') {
1714
- auth = this.features['auth'];
1715
- }
1716
- for (let i = 0; i < preferred.length; i++) {
1717
- if (auth.includes(preferred[i])) {
1718
- method = preferred[i];
1719
- break;
1720
- }
1721
- }
1722
- }
1723
- /**
1724
- * handle bad responses from command differently
1725
- * @param {Error} err err
1726
- * @param {unknown} data data
1727
- * @returns {void}
1728
- */
1729
- const failed = (err, data) => {
1730
- this.loggedin = false;
1731
- this.close(); // if auth is bad, close the connection, it won't get better by itself
1732
- caller(callback, SMTPError.create('authorization.failed', SMTPErrorStates.AUTHFAILED, err, data));
1733
- };
1734
- /**
1735
- * @param {Error} err err
1736
- * @param {unknown} data data
1737
- * @returns {void}
1738
- */
1739
- const response = (err, data) => {
1740
- if (err) {
1741
- failed(err, data);
1742
- }
1743
- else {
1744
- this.loggedin = true;
1745
- caller(callback, err, data);
1746
- }
1747
- };
1748
- /**
1749
- * @param {Error} err err
1750
- * @param {unknown} data data
1751
- * @param {string} msg msg
1752
- * @returns {void}
1753
- */
1754
- const attempt = (err, data, msg) => {
1755
- if (err) {
1756
- failed(err, data);
1757
- }
1758
- else {
1759
- if (method === AUTH_METHODS['CRAM-MD5']) {
1760
- this.command(encodeCramMd5(msg), response, [235, 503]);
1761
- }
1762
- else if (method === AUTH_METHODS.LOGIN) {
1763
- this.command(Buffer.from(login.password()).toString('base64'), response, [235, 503]);
1764
- }
1765
- }
1766
- };
1767
- /**
1768
- * @param {Error} err err
1769
- * @param {unknown} data data
1770
- * @param {string} msg msg
1771
- * @returns {void}
1772
- */
1773
- const attemptUser = (err, data) => {
1774
- if (err) {
1775
- failed(err, data);
1776
- }
1777
- else {
1778
- if (method === AUTH_METHODS.LOGIN) {
1779
- this.command(Buffer.from(login.user()).toString('base64'), attempt, [334]);
1780
- }
1781
- }
1782
- };
1783
- switch (method) {
1784
- case AUTH_METHODS['CRAM-MD5']:
1785
- this.command(`AUTH ${AUTH_METHODS['CRAM-MD5']}`, attempt, [334]);
1786
- break;
1787
- case AUTH_METHODS.LOGIN:
1788
- this.command(`AUTH ${AUTH_METHODS.LOGIN}`, attemptUser, [334]);
1789
- break;
1790
- case AUTH_METHODS.PLAIN:
1791
- this.command(`AUTH ${AUTH_METHODS.PLAIN} ${encodePlain()}`, response, [235, 503]);
1792
- break;
1793
- case AUTH_METHODS.XOAUTH2:
1794
- this.command(`AUTH ${AUTH_METHODS.XOAUTH2} ${encodeXoauth2()}`, response, [235, 503]);
1795
- break;
1796
- default:
1797
- caller(callback, SMTPError.create('no form of authorization supported', SMTPErrorStates.AUTHNOTSUPPORTED, null, data));
1798
- break;
1799
- }
1800
- };
1801
- this.ehlo_or_helo_if_needed(initiate, domain);
1802
- }
1803
- /**
1804
- * @public
1805
- * @param {boolean} [force=false] whether or not to force destroy the connection
1806
- * @returns {void}
1807
- */
1808
- close(force = false) {
1809
- if (this.sock) {
1810
- if (force) {
1811
- this.log('smtp connection destroyed!');
1812
- this.sock.destroy();
1813
- }
1814
- else {
1815
- this.log('smtp connection closed.');
1816
- this.sock.end();
1817
- }
1818
- }
1819
- if (this.monitor) {
1820
- this.monitor.stop();
1821
- this.monitor = null;
1822
- }
1823
- this._state = SMTPState.NOTCONNECTED;
1824
- this._secure = false;
1825
- this.sock = null;
1826
- this.features = null;
1827
- this.loggedin = !(this.user() && this.password());
1828
- }
1829
- /**
1830
- * @public
1831
- * @param {function(...any[]): void} [callback] function to call after response
1832
- * @returns {void}
1833
- */
1834
- quit(callback) {
1835
- this.command('quit', (err, data) => {
1836
- caller(callback, err, data);
1837
- this.close();
1838
- }, [221, 250]);
1839
- }
1840
- }
1841
-
1842
- class SMTPClient {
1843
- /**
1844
- * Create a standard SMTP client backed by a self-managed SMTP connection.
1845
- *
1846
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
1847
- *
1848
- * @param {SMTPConnectionOptions} server smtp options
1849
- */
1850
- constructor(server) {
1851
- this.queue = [];
1852
- this.sending = false;
1853
- this.ready = false;
1854
- this.timer = null;
1855
- this.smtp = new SMTPConnection(server);
1856
- }
1857
- /**
1858
- * @public
1859
- * @param {Message} msg the message to send
1860
- * @param {MessageCallback} callback .
1861
- * @returns {void}
1862
- */
1863
- send(msg, callback) {
1864
- const message = msg instanceof Message
1865
- ? msg
1866
- : this._canMakeMessage(msg)
1867
- ? new Message(msg)
1868
- : null;
1869
- if (message == null) {
1870
- callback(new Error('message is not a valid Message instance'), msg);
1871
- return;
1872
- }
1873
- const { isValid, validationError } = message.checkValidity();
1874
- if (isValid) {
1875
- const stack = this.createMessageStack(message, callback);
1876
- if (stack.to.length === 0) {
1877
- return callback(new Error('No recipients found in message'), msg);
1878
- }
1879
- this.queue.push(stack);
1880
- this._poll();
1881
- }
1882
- else {
1883
- callback(new Error(validationError), msg);
1884
- }
1885
- }
1886
- /**
1887
- * @public
1888
- * @param {Message} msg the message to send
1889
- * @returns {Promise<Message>} a promise that resolves to the fully processed message
1890
- */
1891
- sendAsync(msg) {
1892
- return new Promise((resolve, reject) => {
1893
- this.send(msg, (err, message) => {
1894
- if (err != null) {
1895
- reject(err);
1896
- }
1897
- else {
1898
- // unfortunately, the conditional type doesn't reach here
1899
- // fortunately, we only return a `Message` when err is null, so this is safe
1900
- resolve(message);
1901
- }
1902
- });
1903
- });
1904
- }
1905
- /**
1906
- * @public
1907
- * @description Converts a message to the raw object used by the internal stack.
1908
- * @param {Message} message message to convert
1909
- * @param {MessageCallback} callback errback
1910
- * @returns {MessageStack} raw message object
1911
- */
1912
- createMessageStack(message, callback = function () {
1913
- /* ø */
1914
- }) {
1915
- const [{ address: from }] = addressparser(message.header.from);
1916
- const stack = {
1917
- message,
1918
- to: [],
1919
- from,
1920
- callback: callback.bind(this),
1921
- };
1922
- const { header: { to, cc, bcc, 'return-path': returnPath }, } = message;
1923
- if ((typeof to === 'string' || Array.isArray(to)) && to.length > 0) {
1924
- stack.to = addressparser(to);
1925
- }
1926
- if ((typeof cc === 'string' || Array.isArray(cc)) && cc.length > 0) {
1927
- stack.to = stack.to.concat(addressparser(cc).filter((x) => stack.to.some((y) => y.address === x.address) === false));
1928
- }
1929
- if ((typeof bcc === 'string' || Array.isArray(bcc)) && bcc.length > 0) {
1930
- stack.to = stack.to.concat(addressparser(bcc).filter((x) => stack.to.some((y) => y.address === x.address) === false));
1931
- }
1932
- if (typeof returnPath === 'string' && returnPath.length > 0) {
1933
- const parsedReturnPath = addressparser(returnPath);
1934
- if (parsedReturnPath.length > 0) {
1935
- const [{ address: returnPathAddress }] = parsedReturnPath;
1936
- stack.returnPath = returnPathAddress;
1937
- }
1938
- }
1939
- return stack;
1940
- }
1941
- /**
1942
- * @protected
1943
- * @returns {void}
1944
- */
1945
- _poll() {
1946
- if (this.timer != null) {
1947
- clearTimeout(this.timer);
1948
- }
1949
- if (this.queue.length) {
1950
- if (this.smtp.state() == SMTPState.NOTCONNECTED) {
1951
- this._connect(this.queue[0]);
1952
- }
1953
- else if (this.smtp.state() == SMTPState.CONNECTED &&
1954
- !this.sending &&
1955
- this.ready) {
1956
- this._sendmail(this.queue.shift());
1957
- }
1958
- }
1959
- // wait around 1 seconds in case something does come in,
1960
- // otherwise close out SMTP connection if still open
1961
- else if (this.smtp.state() == SMTPState.CONNECTED) {
1962
- this.timer = setTimeout(() => this.smtp.quit(), 1000);
1963
- }
1964
- }
1965
- /**
1966
- * @protected
1967
- * @param {MessageStack} stack stack
1968
- * @returns {void}
1969
- */
1970
- _connect(stack) {
1971
- /**
1972
- * @param {Error} err callback error
1973
- * @returns {void}
1974
- */
1975
- const connect = (err) => {
1976
- if (!err) {
1977
- const begin = (err) => {
1978
- if (!err) {
1979
- this.ready = true;
1980
- this._poll();
1981
- }
1982
- else {
1983
- stack.callback(err, stack.message);
1984
- // clear out the queue so all callbacks can be called with the same error message
1985
- this.queue.shift();
1986
- this._poll();
1987
- }
1988
- };
1989
- if (!this.smtp.authorized()) {
1990
- this.smtp.login(begin);
1991
- }
1992
- else {
1993
- this.smtp.ehlo_or_helo_if_needed(begin);
1994
- }
1995
- }
1996
- else {
1997
- stack.callback(err, stack.message);
1998
- // clear out the queue so all callbacks can be called with the same error message
1999
- this.queue.shift();
2000
- this._poll();
2001
- }
2002
- };
2003
- this.ready = false;
2004
- this.smtp.connect(connect);
2005
- }
2006
- /**
2007
- * @protected
2008
- * @param {MessageStack} msg message stack
2009
- * @returns {boolean} can make message
2010
- */
2011
- _canMakeMessage(msg) {
2012
- return (msg.from &&
2013
- (msg.to || msg.cc || msg.bcc) &&
2014
- (msg.text !== undefined || this._containsInlinedHtml(msg.attachment)));
2015
- }
2016
- /**
2017
- * @protected
2018
- * @param {MessageAttachment | MessageAttachment[]} attachment attachment
2019
- * @returns {boolean} whether the attachment contains inlined html
2020
- */
2021
- _containsInlinedHtml(attachment) {
2022
- if (Array.isArray(attachment)) {
2023
- return attachment.some((att) => {
2024
- return this._isAttachmentInlinedHtml(att);
2025
- });
2026
- }
2027
- else {
2028
- return this._isAttachmentInlinedHtml(attachment);
2029
- }
2030
- }
2031
- /**
2032
- * @protected
2033
- * @param {MessageAttachment} attachment attachment
2034
- * @returns {boolean} whether the attachment is inlined html
2035
- */
2036
- _isAttachmentInlinedHtml(attachment) {
2037
- return (attachment &&
2038
- (attachment.data || attachment.path) &&
2039
- attachment.alternative === true);
2040
- }
2041
- /**
2042
- * @protected
2043
- * @param {MessageStack} stack stack
2044
- * @param {function(MessageStack): void} next next
2045
- * @returns {function(Error): void} callback
2046
- */
2047
- _sendsmtp(stack, next) {
2048
- /**
2049
- * @param {Error} [err] error
2050
- * @returns {void}
2051
- */
2052
- return (err) => {
2053
- if (!err && next) {
2054
- next.apply(this, [stack]);
2055
- }
2056
- else {
2057
- // if we snag on SMTP commands, call done, passing the error
2058
- // but first reset SMTP state so queue can continue polling
2059
- this.smtp.rset(() => this._senddone(err, stack));
2060
- }
2061
- };
2062
- }
2063
- /**
2064
- * @protected
2065
- * @param {MessageStack} stack stack
2066
- * @returns {void}
2067
- */
2068
- _sendmail(stack) {
2069
- const from = stack.returnPath || stack.from;
2070
- this.sending = true;
2071
- this.smtp.mail(this._sendsmtp(stack, this._sendrcpt), '<' + from + '>');
2072
- }
2073
- /**
2074
- * @protected
2075
- * @param {MessageStack} stack stack
2076
- * @returns {void}
2077
- */
2078
- _sendrcpt(stack) {
2079
- var _a;
2080
- if (stack.to == null || typeof stack.to === 'string') {
2081
- throw new TypeError('stack.to must be array');
2082
- }
2083
- const to = (_a = stack.to.shift()) === null || _a === void 0 ? void 0 : _a.address;
2084
- this.smtp.rcpt(this._sendsmtp(stack, stack.to.length ? this._sendrcpt : this._senddata), `<${to}>`);
2085
- }
2086
- /**
2087
- * @protected
2088
- * @param {MessageStack} stack stack
2089
- * @returns {void}
2090
- */
2091
- _senddata(stack) {
2092
- this.smtp.data(this._sendsmtp(stack, this._sendmessage));
2093
- }
2094
- /**
2095
- * @protected
2096
- * @param {MessageStack} stack stack
2097
- * @returns {void}
2098
- */
2099
- _sendmessage(stack) {
2100
- const stream = stack.message.stream();
2101
- stream.on('data', (data) => this.smtp.message(data));
2102
- stream.on('end', () => {
2103
- this.smtp.data_end(this._sendsmtp(stack, () => this._senddone(null, stack)));
2104
- });
2105
- // there is no way to cancel a message while in the DATA portion,
2106
- // so we have to close the socket to prevent a bad email from going out
2107
- stream.on('error', (err) => {
2108
- this.smtp.close();
2109
- this._senddone(err, stack);
2110
- });
2111
- }
2112
- /**
2113
- * @protected
2114
- * @param {Error} err err
2115
- * @param {MessageStack} stack stack
2116
- * @returns {void}
2117
- */
2118
- _senddone(err, stack) {
2119
- this.sending = false;
2120
- stack.callback(err, stack.message);
2121
- this._poll();
2122
- }
2123
- }
2124
-
2125
- exports.AUTH_METHODS = AUTH_METHODS;
2126
- exports.BUFFERSIZE = BUFFERSIZE;
2127
- exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
2128
- exports.MIME64CHUNK = MIME64CHUNK;
2129
- exports.MIMECHUNK = MIMECHUNK;
2130
- exports.Message = Message;
2131
- exports.SMTPClient = SMTPClient;
2132
- exports.SMTPConnection = SMTPConnection;
2133
- exports.SMTPError = SMTPError;
2134
- exports.SMTPErrorStates = SMTPErrorStates;
2135
- exports.SMTPResponseMonitor = SMTPResponseMonitor;
2136
- exports.SMTPState = SMTPState;
2137
- exports.addressparser = addressparser;
2138
- exports.getRFC2822Date = getRFC2822Date;
2139
- exports.getRFC2822DateUTC = getRFC2822DateUTC;
2140
- exports.isRFC2822Date = isRFC2822Date;
2141
- exports.mimeEncode = mimeEncode;
2142
- exports.mimeWordEncode = mimeWordEncode;
2143
- //# sourceMappingURL=email.cjs.map