emailjs 3.8.0 → 4.0.1

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,2142 +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], // >?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}
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 : ''
891
- : Buffer.from((_b = attachment.data) !== null && _b !== void 0 ? _b : '').toString('base64'), callback);
892
- };
893
- /**
894
- * @param {Message} message the message to output
895
- * @returns {void}
896
- */
897
- const outputText = (message) => {
898
- let data = [];
899
- data = data.concat([
900
- 'Content-Type:',
901
- message.content,
902
- CRLF$1,
903
- 'Content-Transfer-Encoding: 7bit',
904
- CRLF$1,
905
- ]);
906
- data = data.concat(['Content-Disposition: inline', CRLF$1, CRLF$1]);
907
- data = data.concat([message.text || '', CRLF$1, CRLF$1]);
908
- output(data.join(''));
909
- };
910
- /**
911
- * @param {MessageAttachment} message the message to output
912
- * @param {function(): void} callback the function to call after output is finished
913
- * @returns {void}
914
- */
915
- const outputRelated = (message, callback) => {
916
- const boundary = generateBoundary();
917
- output(`Content-Type: multipart/related; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
918
- outputAttachment(message, () => {
919
- var _a;
920
- outputMessage(boundary, (_a = message.related) !== null && _a !== void 0 ? _a : [], 0, () => {
921
- output(`${CRLF$1}--${boundary}--${CRLF$1}${CRLF$1}`);
922
- callback();
923
- });
924
- });
925
- };
926
- /**
927
- * @param {Message} message the message to output
928
- * @param {function(): void} callback the function to call after output is finished
929
- * @returns {void}
930
- */
931
- const outputAlternative = (message, callback) => {
932
- const boundary = generateBoundary();
933
- output(`Content-Type: multipart/alternative; boundary="${boundary}"${CRLF$1}${CRLF$1}--${boundary}${CRLF$1}`);
934
- outputText(message);
935
- output(`--${boundary}${CRLF$1}`);
936
- /**
937
- * @returns {void}
938
- */
939
- const finish = () => {
940
- output([CRLF$1, '--', boundary, '--', CRLF$1, CRLF$1].join(''));
941
- callback();
942
- };
943
- if (message.alternative.related) {
944
- outputRelated(message.alternative, finish);
945
- }
946
- else {
947
- outputAttachment(message.alternative, finish);
948
- }
949
- };
950
- const close = (err) => {
951
- var _a, _b;
952
- if (err) {
953
- this.emit('error', err);
954
- }
955
- else {
956
- 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 : '');
957
- this.emit('end');
958
- }
959
- this.buffer = null;
960
- this.bufferIndex = 0;
961
- this.readable = false;
962
- this.removeAllListeners('resume');
963
- this.removeAllListeners('pause');
964
- this.removeAllListeners('error');
965
- this.removeAllListeners('data');
966
- this.removeAllListeners('end');
967
- };
968
- /**
969
- * @returns {void}
970
- */
971
- const outputHeaderData = () => {
972
- if (this.message.attachments.length || this.message.alternative) {
973
- output(`MIME-Version: 1.0${CRLF$1}`);
974
- outputMixed();
975
- } // you only have a text message!
976
- else {
977
- outputText(this.message);
978
- close();
979
- }
980
- };
981
- /**
982
- * @returns {void}
983
- */
984
- const outputHeader = () => {
985
- let data = [];
986
- for (const header in this.message.header) {
987
- // do not output BCC in the headers (regex) nor custom Object.prototype functions...
988
- if (!/bcc/i.test(header) &&
989
- Object.prototype.hasOwnProperty.call(this.message.header, header)) {
990
- data = data.concat([
991
- convertDashDelimitedTextToSnakeCase(header),
992
- ': ',
993
- this.message.header[header],
994
- CRLF$1,
995
- ]);
996
- }
997
- }
998
- output(data.join(''));
999
- outputHeaderData();
1000
- };
1001
- this.once('destroy', close);
1002
- process.nextTick(outputHeader);
1003
- }
1004
- /**
1005
- * @public
1006
- * pause the stream
1007
- * @returns {void}
1008
- */
1009
- pause() {
1010
- this.paused = true;
1011
- this.emit('pause');
1012
- }
1013
- /**
1014
- * @public
1015
- * resume the stream
1016
- * @returns {void}
1017
- */
1018
- resume() {
1019
- this.paused = false;
1020
- this.emit('resume');
1021
- }
1022
- /**
1023
- * @public
1024
- * destroy the stream
1025
- * @returns {void}
1026
- */
1027
- destroy() {
1028
- this.emit('destroy', this.bufferIndex > 0 ? { message: 'message stream destroyed' } : null);
1029
- }
1030
- /**
1031
- * @public
1032
- * destroy the stream at first opportunity
1033
- * @returns {void}
1034
- */
1035
- destroySoon() {
1036
- this.emit('destroy');
1037
- }
1038
- }
1039
-
1040
- /**
1041
- * @readonly
1042
- * @enum
1043
- */
1044
- const SMTPErrorStates = {
1045
- COULDNOTCONNECT: 1,
1046
- BADRESPONSE: 2,
1047
- AUTHFAILED: 3,
1048
- TIMEDOUT: 4,
1049
- ERROR: 5,
1050
- NOCONNECTION: 6,
1051
- AUTHNOTSUPPORTED: 7,
1052
- CONNECTIONCLOSED: 8,
1053
- CONNECTIONENDED: 9,
1054
- CONNECTIONAUTH: 10,
1055
- };
1056
- class SMTPError extends Error {
1057
- /**
1058
- * @protected
1059
- * @param {string} message error message
1060
- */
1061
- constructor(message) {
1062
- super(message);
1063
- this.code = null;
1064
- this.smtp = null;
1065
- this.previous = null;
1066
- }
1067
- /**
1068
- *
1069
- * @param {string} message error message
1070
- * @param {number} code smtp error state
1071
- * @param {Error | null} error previous error
1072
- * @param {unknown} smtp arbitrary data
1073
- * @returns {SMTPError} error
1074
- */
1075
- static create(message, code, error, smtp) {
1076
- const msg = (error === null || error === void 0 ? void 0 : error.message) ? `${message} (${error.message})` : message;
1077
- const err = new SMTPError(msg);
1078
- err.code = code;
1079
- err.smtp = smtp;
1080
- if (error) {
1081
- err.previous = error;
1082
- }
1083
- return err;
1084
- }
1085
- }
1086
-
1087
- class SMTPResponseMonitor {
1088
- constructor(stream, timeout, onerror) {
1089
- let buffer = '';
1090
- const notify = () => {
1091
- var _a, _b;
1092
- if (buffer.length) {
1093
- // parse buffer for response codes
1094
- const line = buffer.replace('\r', '');
1095
- if (!((_b = (_a = line
1096
- .trim()
1097
- .split(/\n/)
1098
- .pop()) === null || _a === void 0 ? void 0 : _a.match(/^(\d{3})\s/)) !== null && _b !== void 0 ? _b : false)) {
1099
- return;
1100
- }
1101
- const match = line ? line.match(/(\d+)\s?(.*)/) : null;
1102
- const data = match !== null
1103
- ? { code: match[1], message: match[2], data: line }
1104
- : { code: -1, data: line };
1105
- stream.emit('response', null, data);
1106
- buffer = '';
1107
- }
1108
- };
1109
- const error = (err) => {
1110
- stream.emit('response', SMTPError.create('connection encountered an error', SMTPErrorStates.ERROR, err));
1111
- };
1112
- const timedout = (err) => {
1113
- stream.end();
1114
- stream.emit('response', SMTPError.create('timedout while connecting to smtp server', SMTPErrorStates.TIMEDOUT, err));
1115
- };
1116
- const watch = (data) => {
1117
- if (data !== null) {
1118
- buffer += data.toString();
1119
- notify();
1120
- }
1121
- };
1122
- const close = (err) => {
1123
- stream.emit('response', SMTPError.create('connection has closed', SMTPErrorStates.CONNECTIONCLOSED, err));
1124
- };
1125
- const end = (err) => {
1126
- stream.emit('response', SMTPError.create('connection has ended', SMTPErrorStates.CONNECTIONENDED, err));
1127
- };
1128
- this.stop = (err) => {
1129
- stream.removeAllListeners('response');
1130
- stream.removeListener('data', watch);
1131
- stream.removeListener('end', end);
1132
- stream.removeListener('close', close);
1133
- stream.removeListener('error', error);
1134
- if (err != null && typeof onerror === 'function') {
1135
- onerror(err);
1136
- }
1137
- };
1138
- stream.on('data', watch);
1139
- stream.on('end', end);
1140
- stream.on('close', close);
1141
- stream.on('error', error);
1142
- stream.setTimeout(timeout, timedout);
1143
- }
1144
- }
1145
-
1146
- /**
1147
- * @readonly
1148
- * @enum
1149
- */
1150
- const AUTH_METHODS = {
1151
- PLAIN: 'PLAIN',
1152
- 'CRAM-MD5': 'CRAM-MD5',
1153
- LOGIN: 'LOGIN',
1154
- XOAUTH2: 'XOAUTH2',
1155
- };
1156
- /**
1157
- * @readonly
1158
- * @enum
1159
- */
1160
- const SMTPState = {
1161
- NOTCONNECTED: 0,
1162
- CONNECTING: 1,
1163
- CONNECTED: 2,
1164
- };
1165
- const DEFAULT_TIMEOUT = 5000;
1166
- const SMTP_PORT = 25;
1167
- const SMTP_SSL_PORT = 465;
1168
- const SMTP_TLS_PORT = 587;
1169
- const CRLF = '\r\n';
1170
- const GREYLIST_DELAY = 300;
1171
- let DEBUG = 0;
1172
- /**
1173
- * @param {...any[]} args the message(s) to log
1174
- * @returns {void}
1175
- */
1176
- const log = (...args) => {
1177
- if (DEBUG === 1) {
1178
- args.forEach((d) => console.log(typeof d === 'object'
1179
- ? d instanceof Error
1180
- ? d.message
1181
- : JSON.stringify(d)
1182
- : d));
1183
- }
1184
- };
1185
- /**
1186
- * @param {function(...any[]): void} callback the function to call
1187
- * @param {...any[]} args the arguments to apply to the function
1188
- * @returns {void}
1189
- */
1190
- const caller = (callback, ...args) => {
1191
- if (typeof callback === 'function') {
1192
- callback(...args);
1193
- }
1194
- };
1195
- class SMTPConnection extends events.EventEmitter {
1196
- /**
1197
- * SMTP class written using python's (2.7) smtplib.py as a base.
1198
- *
1199
- * To target a Message Transfer Agent (MTA), omit all options.
1200
- *
1201
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
1202
- */
1203
- constructor({ timeout, host, user, password, domain, port, ssl, tls, logger, authentication, } = {}) {
1204
- var _a;
1205
- super();
1206
- this.timeout = DEFAULT_TIMEOUT;
1207
- this.log = log;
1208
- this.authentication = [
1209
- AUTH_METHODS['CRAM-MD5'],
1210
- AUTH_METHODS.LOGIN,
1211
- AUTH_METHODS.PLAIN,
1212
- AUTH_METHODS.XOAUTH2,
1213
- ];
1214
- this._state = SMTPState.NOTCONNECTED;
1215
- this._secure = false;
1216
- this.loggedin = false;
1217
- this.sock = null;
1218
- this.features = null;
1219
- this.monitor = null;
1220
- this.domain = os.hostname();
1221
- this.host = 'localhost';
1222
- this.ssl = false;
1223
- this.tls = false;
1224
- this.greylistResponseTracker = new WeakSet();
1225
- if (Array.isArray(authentication)) {
1226
- this.authentication = authentication;
1227
- }
1228
- if (typeof timeout === 'number') {
1229
- this.timeout = timeout;
1230
- }
1231
- if (typeof domain === 'string') {
1232
- this.domain = domain;
1233
- }
1234
- if (typeof host === 'string') {
1235
- this.host = host;
1236
- }
1237
- if (ssl != null &&
1238
- (typeof ssl === 'boolean' ||
1239
- (typeof ssl === 'object' && Array.isArray(ssl) === false))) {
1240
- this.ssl = ssl;
1241
- }
1242
- if (tls != null &&
1243
- (typeof tls === 'boolean' ||
1244
- (typeof tls === 'object' && Array.isArray(tls) === false))) {
1245
- this.tls = tls;
1246
- }
1247
- this.port = port || (ssl ? SMTP_SSL_PORT : tls ? SMTP_TLS_PORT : SMTP_PORT);
1248
- this.loggedin = user && password ? false : true;
1249
- if (!user && ((_a = password === null || password === void 0 ? void 0 : password.length) !== null && _a !== void 0 ? _a : 0) > 0) {
1250
- throw new Error('`password` cannot be set without `user`');
1251
- }
1252
- // keep these strings hidden when quicky debugging/logging
1253
- this.user = () => user;
1254
- this.password = () => password;
1255
- if (typeof logger === 'function') {
1256
- this.log = log;
1257
- }
1258
- }
1259
- /**
1260
- * @public
1261
- * @param {0 | 1} level -
1262
- * @returns {void}
1263
- */
1264
- debug(level) {
1265
- DEBUG = level;
1266
- }
1267
- /**
1268
- * @public
1269
- * @returns {SMTPState} the current state
1270
- */
1271
- state() {
1272
- return this._state;
1273
- }
1274
- /**
1275
- * @public
1276
- * @returns {boolean} whether or not the instance is authorized
1277
- */
1278
- authorized() {
1279
- return this.loggedin;
1280
- }
1281
- /**
1282
- * Establish an SMTP connection.
1283
- *
1284
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
1285
- *
1286
- * @public
1287
- * @param {function(...any[]): void} callback function to call after response
1288
- * @param {number} [port] the port to use for the connection
1289
- * @param {string} [host] the hostname to use for the connection
1290
- * @param {ConnectOptions} [options={}] the options
1291
- * @returns {void}
1292
- */
1293
- connect(callback, port = this.port, host = this.host, options = {}) {
1294
- this.port = port;
1295
- this.host = host;
1296
- this.ssl = options.ssl || this.ssl;
1297
- if (this._state !== SMTPState.NOTCONNECTED) {
1298
- this.quit(() => this.connect(callback, port, host, options));
1299
- }
1300
- /**
1301
- * @returns {void}
1302
- */
1303
- const connected = () => {
1304
- this.log(`connected: ${this.host}:${this.port}`);
1305
- if (this.ssl && !this.tls) {
1306
- // if key/ca/cert was passed in, check if connection is authorized
1307
- if (typeof this.ssl !== 'boolean' &&
1308
- this.sock instanceof tls.TLSSocket &&
1309
- !this.sock.authorized) {
1310
- this.close(true);
1311
- caller(callback, SMTPError.create('could not establish an ssl connection', SMTPErrorStates.CONNECTIONAUTH));
1312
- }
1313
- else {
1314
- this._secure = true;
1315
- }
1316
- }
1317
- };
1318
- /**
1319
- * @param {Error} err err
1320
- * @returns {void}
1321
- */
1322
- const connectedErrBack = (err) => {
1323
- if (!err) {
1324
- connected();
1325
- }
1326
- else {
1327
- this.close(true);
1328
- this.log(err);
1329
- caller(callback, SMTPError.create('could not connect', SMTPErrorStates.COULDNOTCONNECT, err));
1330
- }
1331
- };
1332
- const response = (err, msg) => {
1333
- if (err) {
1334
- if (this._state === SMTPState.NOTCONNECTED && !this.sock) {
1335
- return;
1336
- }
1337
- this.close(true);
1338
- caller(callback, err);
1339
- }
1340
- else if (msg.code == '220') {
1341
- this.log(msg.data);
1342
- // might happen first, so no need to wait on connected()
1343
- this._state = SMTPState.CONNECTED;
1344
- caller(callback, null, msg.data);
1345
- }
1346
- else {
1347
- this.log(`response (data): ${msg.data}`);
1348
- this.quit(() => {
1349
- caller(callback, SMTPError.create('bad response on connection', SMTPErrorStates.BADRESPONSE, err, msg.data));
1350
- });
1351
- }
1352
- };
1353
- this._state = SMTPState.CONNECTING;
1354
- this.log(`connecting: ${this.host}:${this.port}`);
1355
- if (this.ssl) {
1356
- this.sock = tls.connect(this.port, this.host.trim(), typeof this.ssl === 'object' ? this.ssl : {}, connected);
1357
- }
1358
- else {
1359
- this.sock = new net.Socket();
1360
- this.sock.connect(this.port, this.host.trim(), connectedErrBack);
1361
- }
1362
- this.monitor = new SMTPResponseMonitor(this.sock, this.timeout, () => this.close(true));
1363
- this.sock.once('response', response);
1364
- this.sock.once('error', response); // the socket could reset or throw, so let's handle it and let the user know
1365
- }
1366
- /**
1367
- * @public
1368
- * @param {string} str the string to send
1369
- * @param {function(...any[]): void} callback function to call after response
1370
- * @returns {void}
1371
- */
1372
- send(str, callback) {
1373
- if (this.sock != null && this._state === SMTPState.CONNECTED) {
1374
- this.log(str);
1375
- this.sock.once('response', (err, msg) => {
1376
- if (err) {
1377
- caller(callback, err);
1378
- }
1379
- else {
1380
- this.log(msg.data);
1381
- caller(callback, null, msg);
1382
- }
1383
- });
1384
- if (this.sock.writable) {
1385
- this.sock.write(str);
1386
- }
1387
- }
1388
- else {
1389
- this.close(true);
1390
- caller(callback, SMTPError.create('no connection has been established', SMTPErrorStates.NOCONNECTION));
1391
- }
1392
- }
1393
- /**
1394
- * @public
1395
- * @param {string} cmd command to issue
1396
- * @param {function(...any[]): void} callback function to call after response
1397
- * @param {(number[] | number)} [codes=[250]] array codes
1398
- * @returns {void}
1399
- */
1400
- command(cmd, callback, codes = [250]) {
1401
- const codesArray = Array.isArray(codes)
1402
- ? codes
1403
- : typeof codes === 'number'
1404
- ? [codes]
1405
- : [250];
1406
- const response = (err, msg) => {
1407
- if (err) {
1408
- caller(callback, err);
1409
- }
1410
- else {
1411
- const code = Number(msg.code);
1412
- if (codesArray.indexOf(code) !== -1) {
1413
- caller(callback, err, msg.data, msg.message);
1414
- }
1415
- else if ((code === 450 || code === 451) &&
1416
- msg.message.toLowerCase().includes('greylist') &&
1417
- this.greylistResponseTracker.has(response) === false) {
1418
- this.greylistResponseTracker.add(response);
1419
- setTimeout(() => {
1420
- this.send(cmd + CRLF, response);
1421
- }, GREYLIST_DELAY);
1422
- }
1423
- else {
1424
- const suffix = msg.message ? `: ${msg.message}` : '';
1425
- const errorMessage = `bad response on command '${cmd.split(' ')[0]}'${suffix}`;
1426
- caller(callback, SMTPError.create(errorMessage, SMTPErrorStates.BADRESPONSE, null, msg.data));
1427
- }
1428
- }
1429
- };
1430
- this.greylistResponseTracker.delete(response);
1431
- this.send(cmd + CRLF, response);
1432
- }
1433
- /**
1434
- * @public
1435
- * @description SMTP 'helo' command.
1436
- *
1437
- * Hostname to send for self command defaults to the FQDN of the local
1438
- * host.
1439
- *
1440
- * As this command was deprecated by rfc2821, it should only be used for compatibility with non-compliant servers.
1441
- * @see https://tools.ietf.org/html/rfc2821#appendix-F.3
1442
- *
1443
- * @param {function(...any[]): void} callback function to call after response
1444
- * @param {string} domain the domain to associate with the 'helo' request
1445
- * @returns {void}
1446
- */
1447
- helo(callback, domain) {
1448
- this.command(`helo ${domain || this.domain}`, (err, data) => {
1449
- if (err) {
1450
- caller(callback, err);
1451
- }
1452
- else {
1453
- this.parse_smtp_features(data);
1454
- caller(callback, err, data);
1455
- }
1456
- });
1457
- }
1458
- /**
1459
- * @public
1460
- * @param {function(...any[]): void} callback function to call after response
1461
- * @returns {void}
1462
- */
1463
- starttls(callback) {
1464
- const response = (err, msg) => {
1465
- if (this.sock == null) {
1466
- throw new Error('null socket');
1467
- }
1468
- if (err) {
1469
- err.message += ' while establishing a starttls session';
1470
- caller(callback, err);
1471
- }
1472
- else {
1473
- const secureContext = tls.createSecureContext(typeof this.tls === 'object' ? this.tls : {});
1474
- const secureSocket = new tls.TLSSocket(this.sock, { secureContext });
1475
- secureSocket.on('error', (err) => {
1476
- this.close(true);
1477
- caller(callback, err);
1478
- });
1479
- this._secure = true;
1480
- this.sock = secureSocket;
1481
- new SMTPResponseMonitor(this.sock, this.timeout, () => this.close(true));
1482
- caller(callback, msg.data);
1483
- }
1484
- };
1485
- this.command('starttls', response, [220]);
1486
- }
1487
- /**
1488
- * @public
1489
- * @param {string} data the string to parse for features
1490
- * @returns {void}
1491
- */
1492
- parse_smtp_features(data) {
1493
- // According to RFC1869 some (badly written)
1494
- // MTA's will disconnect on an ehlo. Toss an exception if
1495
- // that happens -ddm
1496
- data.split('\n').forEach((ext) => {
1497
- const parse = ext.match(/^(?:\d+[-=]?)\s*?([^\s]+)(?:\s+(.*)\s*?)?$/);
1498
- // To be able to communicate with as many SMTP servers as possible,
1499
- // we have to take the old-style auth advertisement into account,
1500
- // because:
1501
- // 1) Else our SMTP feature parser gets confused.
1502
- // 2) There are some servers that only advertise the auth methods we
1503
- // support using the old style.
1504
- if (parse != null && this.features != null) {
1505
- // RFC 1869 requires a space between ehlo keyword and parameters.
1506
- // It's actually stricter, in that only spaces are allowed between
1507
- // parameters, but were not going to check for that here. Note
1508
- // that the space isn't present if there are no parameters.
1509
- this.features[parse[1].toLowerCase()] = parse[2] || true;
1510
- }
1511
- });
1512
- }
1513
- /**
1514
- * @public
1515
- * @param {function(...any[]): void} callback function to call after response
1516
- * @param {string} domain the domain to associate with the 'ehlo' request
1517
- * @returns {void}
1518
- */
1519
- ehlo(callback, domain) {
1520
- this.features = {};
1521
- this.command(`ehlo ${domain || this.domain}`, (err, data) => {
1522
- if (err) {
1523
- caller(callback, err);
1524
- }
1525
- else {
1526
- this.parse_smtp_features(data);
1527
- if (this.tls && !this._secure) {
1528
- this.starttls(() => this.ehlo(callback, domain));
1529
- }
1530
- else {
1531
- caller(callback, err, data);
1532
- }
1533
- }
1534
- });
1535
- }
1536
- /**
1537
- * @public
1538
- * @param {string} opt the features keyname to check
1539
- * @returns {boolean} whether the extension exists
1540
- */
1541
- has_extn(opt) {
1542
- var _a;
1543
- return ((_a = this.features) !== null && _a !== void 0 ? _a : {})[opt.toLowerCase()] === undefined;
1544
- }
1545
- /**
1546
- * @public
1547
- * @description SMTP 'help' command, returns text from the server
1548
- * @param {function(...any[]): void} callback function to call after response
1549
- * @param {string} domain the domain to associate with the 'help' request
1550
- * @returns {void}
1551
- */
1552
- help(callback, domain) {
1553
- this.command(domain ? `help ${domain}` : 'help', callback, [211, 214]);
1554
- }
1555
- /**
1556
- * @public
1557
- * @param {function(...any[]): void} callback function to call after response
1558
- * @returns {void}
1559
- */
1560
- rset(callback) {
1561
- this.command('rset', callback);
1562
- }
1563
- /**
1564
- * @public
1565
- * @param {function(...any[]): void} callback function to call after response
1566
- * @returns {void}
1567
- */
1568
- noop(callback) {
1569
- this.send('noop', callback);
1570
- }
1571
- /**
1572
- * @public
1573
- * @param {function(...any[]): void} callback function to call after response
1574
- * @param {string} from the sender
1575
- * @returns {void}
1576
- */
1577
- mail(callback, from) {
1578
- this.command(`mail FROM:${from}`, callback);
1579
- }
1580
- /**
1581
- * @public
1582
- * @param {function(...any[]): void} callback function to call after response
1583
- * @param {string} to the receiver
1584
- * @returns {void}
1585
- */
1586
- rcpt(callback, to) {
1587
- this.command(`RCPT TO:${to}`, callback, [250, 251]);
1588
- }
1589
- /**
1590
- * @public
1591
- * @param {function(...any[]): void} callback function to call after response
1592
- * @returns {void}
1593
- */
1594
- data(callback) {
1595
- this.command('data', callback, [354]);
1596
- }
1597
- /**
1598
- * @public
1599
- * @param {function(...any[]): void} callback function to call after response
1600
- * @returns {void}
1601
- */
1602
- data_end(callback) {
1603
- this.command(`${CRLF}.`, callback);
1604
- }
1605
- /**
1606
- * @public
1607
- * @param {string} data the message to send
1608
- * @returns {void}
1609
- */
1610
- message(data) {
1611
- var _a, _b;
1612
- this.log(data);
1613
- (_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');
1614
- }
1615
- /**
1616
- * @public
1617
- * @description SMTP 'verify' command -- checks for address validity.
1618
- * @param {string} address the address to validate
1619
- * @param {function(...any[]): void} callback function to call after response
1620
- * @returns {void}
1621
- */
1622
- verify(address, callback) {
1623
- this.command(`vrfy ${address}`, callback, [250, 251, 252]);
1624
- }
1625
- /**
1626
- * @public
1627
- * @description SMTP 'expn' command -- expands a mailing list.
1628
- * @param {string} address the mailing list to expand
1629
- * @param {function(...any[]): void} callback function to call after response
1630
- * @returns {void}
1631
- */
1632
- expn(address, callback) {
1633
- this.command(`expn ${address}`, callback);
1634
- }
1635
- /**
1636
- * @public
1637
- * @description Calls this.ehlo() and, if an error occurs, this.helo().
1638
- *
1639
- * If there has been no previous EHLO or HELO command self session, self
1640
- * method tries ESMTP EHLO first.
1641
- *
1642
- * @param {function(...any[]): void} callback function to call after response
1643
- * @param {string} [domain] the domain to associate with the command
1644
- * @returns {void}
1645
- */
1646
- ehlo_or_helo_if_needed(callback, domain) {
1647
- // is this code callable...?
1648
- if (!this.features) {
1649
- const response = (err, data) => caller(callback, err, data);
1650
- this.ehlo((err, data) => {
1651
- if (err) {
1652
- this.helo(response, domain);
1653
- }
1654
- else {
1655
- caller(callback, err, data);
1656
- }
1657
- }, domain);
1658
- }
1659
- }
1660
- /**
1661
- * @public
1662
- *
1663
- * Log in on an SMTP server that requires authentication.
1664
- *
1665
- * If there has been no previous EHLO or HELO command self session, self
1666
- * method tries ESMTP EHLO first.
1667
- *
1668
- * This method will return normally if the authentication was successful.
1669
- *
1670
- * @param {function(...any[]): void} callback function to call after response
1671
- * @param {string} [user] the username to authenticate with
1672
- * @param {string} [password] the password for the authentication
1673
- * @param {{ method: string, domain: string }} [options] login options
1674
- * @returns {void}
1675
- */
1676
- login(callback, user, password, options = {}) {
1677
- var _a, _b;
1678
- const login = {
1679
- user: user ? () => user : this.user,
1680
- password: password ? () => password : this.password,
1681
- 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 : '',
1682
- };
1683
- const domain = (options === null || options === void 0 ? void 0 : options.domain) || this.domain;
1684
- const initiate = (err, data) => {
1685
- var _a;
1686
- if (err) {
1687
- caller(callback, err);
1688
- return;
1689
- }
1690
- let method = null;
1691
- /**
1692
- * @param {string} challenge challenge
1693
- * @returns {string} base64 cram hash
1694
- */
1695
- const encodeCramMd5 = (challenge) => {
1696
- const hmac = crypto.createHmac('md5', login.password());
1697
- hmac.update(Buffer.from(challenge, 'base64').toString('ascii'));
1698
- return Buffer.from(`${login.user()} ${hmac.digest('hex')}`).toString('base64');
1699
- };
1700
- /**
1701
- * @returns {string} base64 login/password
1702
- */
1703
- const encodePlain = () => Buffer.from(`\u0000${login.user()}\u0000${login.password()}`).toString('base64');
1704
- /**
1705
- * @see https://developers.google.com/gmail/xoauth2_protocol
1706
- * @returns {string} base64 xoauth2 auth token
1707
- */
1708
- const encodeXoauth2 = () => Buffer.from(`user=${login.user()}\u0001auth=Bearer ${login.password()}\u0001\u0001`).toString('base64');
1709
- // List of authentication methods we support: from preferred to
1710
- // less preferred methods.
1711
- if (!method) {
1712
- const preferred = this.authentication;
1713
- let auth = '';
1714
- if (typeof ((_a = this.features) === null || _a === void 0 ? void 0 : _a['auth']) === 'string') {
1715
- auth = this.features['auth'];
1716
- }
1717
- for (let i = 0; i < preferred.length; i++) {
1718
- if (auth.includes(preferred[i])) {
1719
- method = preferred[i];
1720
- break;
1721
- }
1722
- }
1723
- }
1724
- /**
1725
- * handle bad responses from command differently
1726
- * @param {Error} err err
1727
- * @param {unknown} data data
1728
- * @returns {void}
1729
- */
1730
- const failed = (err, data) => {
1731
- this.loggedin = false;
1732
- this.close(); // if auth is bad, close the connection, it won't get better by itself
1733
- caller(callback, SMTPError.create('authorization.failed', SMTPErrorStates.AUTHFAILED, err, data));
1734
- };
1735
- /**
1736
- * @param {Error} err err
1737
- * @param {unknown} data data
1738
- * @returns {void}
1739
- */
1740
- const response = (err, data) => {
1741
- if (err) {
1742
- failed(err, data);
1743
- }
1744
- else {
1745
- this.loggedin = true;
1746
- caller(callback, err, data);
1747
- }
1748
- };
1749
- /**
1750
- * @param {Error} err err
1751
- * @param {unknown} data data
1752
- * @param {string} msg msg
1753
- * @returns {void}
1754
- */
1755
- const attempt = (err, data, msg) => {
1756
- if (err) {
1757
- failed(err, data);
1758
- }
1759
- else {
1760
- if (method === AUTH_METHODS['CRAM-MD5']) {
1761
- this.command(encodeCramMd5(msg), response, [235, 503]);
1762
- }
1763
- else if (method === AUTH_METHODS.LOGIN) {
1764
- this.command(Buffer.from(login.password()).toString('base64'), response, [235, 503]);
1765
- }
1766
- }
1767
- };
1768
- /**
1769
- * @param {Error} err err
1770
- * @param {unknown} data data
1771
- * @param {string} msg msg
1772
- * @returns {void}
1773
- */
1774
- const attemptUser = (err, data) => {
1775
- if (err) {
1776
- failed(err, data);
1777
- }
1778
- else {
1779
- if (method === AUTH_METHODS.LOGIN) {
1780
- this.command(Buffer.from(login.user()).toString('base64'), attempt, [334]);
1781
- }
1782
- }
1783
- };
1784
- switch (method) {
1785
- case AUTH_METHODS['CRAM-MD5']:
1786
- this.command(`AUTH ${AUTH_METHODS['CRAM-MD5']}`, attempt, [334]);
1787
- break;
1788
- case AUTH_METHODS.LOGIN:
1789
- this.command(`AUTH ${AUTH_METHODS.LOGIN}`, attemptUser, [334]);
1790
- break;
1791
- case AUTH_METHODS.PLAIN:
1792
- this.command(`AUTH ${AUTH_METHODS.PLAIN} ${encodePlain()}`, response, [235, 503]);
1793
- break;
1794
- case AUTH_METHODS.XOAUTH2:
1795
- this.command(`AUTH ${AUTH_METHODS.XOAUTH2} ${encodeXoauth2()}`, response, [235, 503]);
1796
- break;
1797
- default:
1798
- caller(callback, SMTPError.create('no form of authorization supported', SMTPErrorStates.AUTHNOTSUPPORTED, null, data));
1799
- break;
1800
- }
1801
- };
1802
- this.ehlo_or_helo_if_needed(initiate, domain);
1803
- }
1804
- /**
1805
- * @public
1806
- * @param {boolean} [force=false] whether or not to force destroy the connection
1807
- * @returns {void}
1808
- */
1809
- close(force = false) {
1810
- if (this.sock) {
1811
- if (force) {
1812
- this.log('smtp connection destroyed!');
1813
- this.sock.destroy();
1814
- }
1815
- else {
1816
- this.log('smtp connection closed.');
1817
- this.sock.end();
1818
- }
1819
- }
1820
- if (this.monitor) {
1821
- this.monitor.stop();
1822
- this.monitor = null;
1823
- }
1824
- this._state = SMTPState.NOTCONNECTED;
1825
- this._secure = false;
1826
- this.sock = null;
1827
- this.features = null;
1828
- this.loggedin = !(this.user() && this.password());
1829
- }
1830
- /**
1831
- * @public
1832
- * @param {function(...any[]): void} [callback] function to call after response
1833
- * @returns {void}
1834
- */
1835
- quit(callback) {
1836
- this.command('quit', (err, data) => {
1837
- caller(callback, err, data);
1838
- this.close();
1839
- }, [221, 250]);
1840
- }
1841
- }
1842
-
1843
- class SMTPClient {
1844
- /**
1845
- * Create a standard SMTP client backed by a self-managed SMTP connection.
1846
- *
1847
- * NOTE: `host` is trimmed before being used to establish a connection; however, the original untrimmed value will still be visible in configuration.
1848
- *
1849
- * @param {SMTPConnectionOptions} server smtp options
1850
- */
1851
- constructor(server) {
1852
- this.queue = [];
1853
- this.sending = false;
1854
- this.ready = false;
1855
- this.timer = null;
1856
- this.smtp = new SMTPConnection(server);
1857
- }
1858
- /**
1859
- * @public
1860
- * @param {Message} msg the message to send
1861
- * @param {function(err: Error, msg: Message): void} callback .
1862
- * @returns {void}
1863
- */
1864
- send(msg, callback) {
1865
- const message = msg instanceof Message
1866
- ? msg
1867
- : this._canMakeMessage(msg)
1868
- ? new Message(msg)
1869
- : null;
1870
- if (message == null) {
1871
- callback(new Error('message is not a valid Message instance'), msg);
1872
- return;
1873
- }
1874
- const { isValid, validationError } = message.checkValidity();
1875
- if (isValid) {
1876
- const stack = this.createMessageStack(message, callback);
1877
- if (stack.to.length === 0) {
1878
- return callback(new Error('No recipients found in message'), msg);
1879
- }
1880
- this.queue.push(stack);
1881
- this._poll();
1882
- }
1883
- else {
1884
- callback(new Error(validationError), msg);
1885
- }
1886
- }
1887
- /**
1888
- * @public
1889
- * @param {Message} msg the message to send
1890
- * @returns {Promise<Message>} a promise that resolves to the fully processed message
1891
- */
1892
- sendAsync(msg) {
1893
- return new Promise((resolve, reject) => {
1894
- this.send(msg, (err, msg) => {
1895
- if (err != null) {
1896
- reject(err);
1897
- }
1898
- else {
1899
- resolve(msg);
1900
- }
1901
- });
1902
- });
1903
- }
1904
- /**
1905
- * @public
1906
- * @description Converts a message to the raw object used by the internal stack.
1907
- * @param {Message} message message to convert
1908
- * @param {function(err: Error, msg: Message): void} callback errback
1909
- * @returns {MessageStack} raw message object
1910
- */
1911
- createMessageStack(message, callback = function () {
1912
- /* ø */
1913
- }) {
1914
- const [{ address: from }] = addressparser(message.header.from);
1915
- const stack = {
1916
- message,
1917
- to: [],
1918
- from,
1919
- callback: callback.bind(this),
1920
- };
1921
- const { header: { to, cc, bcc, 'return-path': returnPath }, } = message;
1922
- if ((typeof to === 'string' || Array.isArray(to)) && to.length > 0) {
1923
- stack.to = addressparser(to);
1924
- }
1925
- if ((typeof cc === 'string' || Array.isArray(cc)) && cc.length > 0) {
1926
- stack.to = stack.to.concat(addressparser(cc).filter((x) => stack.to.some((y) => y.address === x.address) === false));
1927
- }
1928
- if ((typeof bcc === 'string' || Array.isArray(bcc)) && bcc.length > 0) {
1929
- stack.to = stack.to.concat(addressparser(bcc).filter((x) => stack.to.some((y) => y.address === x.address) === false));
1930
- }
1931
- if (typeof returnPath === 'string' && returnPath.length > 0) {
1932
- const parsedReturnPath = addressparser(returnPath);
1933
- if (parsedReturnPath.length > 0) {
1934
- const [{ address: returnPathAddress }] = parsedReturnPath;
1935
- stack.returnPath = returnPathAddress;
1936
- }
1937
- }
1938
- return stack;
1939
- }
1940
- /**
1941
- * @protected
1942
- * @returns {void}
1943
- */
1944
- _poll() {
1945
- if (this.timer != null) {
1946
- clearTimeout(this.timer);
1947
- }
1948
- if (this.queue.length) {
1949
- if (this.smtp.state() == SMTPState.NOTCONNECTED) {
1950
- this._connect(this.queue[0]);
1951
- }
1952
- else if (this.smtp.state() == SMTPState.CONNECTED &&
1953
- !this.sending &&
1954
- this.ready) {
1955
- this._sendmail(this.queue.shift());
1956
- }
1957
- }
1958
- // wait around 1 seconds in case something does come in,
1959
- // otherwise close out SMTP connection if still open
1960
- else if (this.smtp.state() == SMTPState.CONNECTED) {
1961
- this.timer = setTimeout(() => this.smtp.quit(), 1000);
1962
- }
1963
- }
1964
- /**
1965
- * @protected
1966
- * @param {MessageStack} stack stack
1967
- * @returns {void}
1968
- */
1969
- _connect(stack) {
1970
- /**
1971
- * @param {Error} err callback error
1972
- * @returns {void}
1973
- */
1974
- const connect = (err) => {
1975
- if (!err) {
1976
- const begin = (err) => {
1977
- if (!err) {
1978
- this.ready = true;
1979
- this._poll();
1980
- }
1981
- else {
1982
- stack.callback(err, stack.message);
1983
- // clear out the queue so all callbacks can be called with the same error message
1984
- this.queue.shift();
1985
- this._poll();
1986
- }
1987
- };
1988
- if (!this.smtp.authorized()) {
1989
- this.smtp.login(begin);
1990
- }
1991
- else {
1992
- this.smtp.ehlo_or_helo_if_needed(begin);
1993
- }
1994
- }
1995
- else {
1996
- stack.callback(err, stack.message);
1997
- // clear out the queue so all callbacks can be called with the same error message
1998
- this.queue.shift();
1999
- this._poll();
2000
- }
2001
- };
2002
- this.ready = false;
2003
- this.smtp.connect(connect);
2004
- }
2005
- /**
2006
- * @protected
2007
- * @param {MessageStack} msg message stack
2008
- * @returns {boolean} can make message
2009
- */
2010
- _canMakeMessage(msg) {
2011
- return (msg.from &&
2012
- (msg.to || msg.cc || msg.bcc) &&
2013
- (msg.text !== undefined || this._containsInlinedHtml(msg.attachment)));
2014
- }
2015
- /**
2016
- * @protected
2017
- * @param {MessageAttachment | MessageAttachment[]} attachment attachment
2018
- * @returns {boolean} whether the attachment contains inlined html
2019
- */
2020
- _containsInlinedHtml(attachment) {
2021
- if (Array.isArray(attachment)) {
2022
- return attachment.some((att) => {
2023
- return this._isAttachmentInlinedHtml(att);
2024
- });
2025
- }
2026
- else {
2027
- return this._isAttachmentInlinedHtml(attachment);
2028
- }
2029
- }
2030
- /**
2031
- * @protected
2032
- * @param {MessageAttachment} attachment attachment
2033
- * @returns {boolean} whether the attachment is inlined html
2034
- */
2035
- _isAttachmentInlinedHtml(attachment) {
2036
- return (attachment &&
2037
- (attachment.data || attachment.path) &&
2038
- attachment.alternative === true);
2039
- }
2040
- /**
2041
- * @protected
2042
- * @param {MessageStack} stack stack
2043
- * @param {function(MessageStack): void} next next
2044
- * @returns {function(Error): void} callback
2045
- */
2046
- _sendsmtp(stack, next) {
2047
- /**
2048
- * @param {Error} [err] error
2049
- * @returns {void}
2050
- */
2051
- return (err) => {
2052
- if (!err && next) {
2053
- next.apply(this, [stack]);
2054
- }
2055
- else {
2056
- // if we snag on SMTP commands, call done, passing the error
2057
- // but first reset SMTP state so queue can continue polling
2058
- this.smtp.rset(() => this._senddone(err, stack));
2059
- }
2060
- };
2061
- }
2062
- /**
2063
- * @protected
2064
- * @param {MessageStack} stack stack
2065
- * @returns {void}
2066
- */
2067
- _sendmail(stack) {
2068
- const from = stack.returnPath || stack.from;
2069
- this.sending = true;
2070
- this.smtp.mail(this._sendsmtp(stack, this._sendrcpt), '<' + from + '>');
2071
- }
2072
- /**
2073
- * @protected
2074
- * @param {MessageStack} stack stack
2075
- * @returns {void}
2076
- */
2077
- _sendrcpt(stack) {
2078
- var _a;
2079
- if (stack.to == null || typeof stack.to === 'string') {
2080
- throw new TypeError('stack.to must be array');
2081
- }
2082
- const to = (_a = stack.to.shift()) === null || _a === void 0 ? void 0 : _a.address;
2083
- this.smtp.rcpt(this._sendsmtp(stack, stack.to.length ? this._sendrcpt : this._senddata), `<${to}>`);
2084
- }
2085
- /**
2086
- * @protected
2087
- * @param {MessageStack} stack stack
2088
- * @returns {void}
2089
- */
2090
- _senddata(stack) {
2091
- this.smtp.data(this._sendsmtp(stack, this._sendmessage));
2092
- }
2093
- /**
2094
- * @protected
2095
- * @param {MessageStack} stack stack
2096
- * @returns {void}
2097
- */
2098
- _sendmessage(stack) {
2099
- const stream = stack.message.stream();
2100
- stream.on('data', (data) => this.smtp.message(data));
2101
- stream.on('end', () => {
2102
- this.smtp.data_end(this._sendsmtp(stack, () => this._senddone(null, stack)));
2103
- });
2104
- // there is no way to cancel a message while in the DATA portion,
2105
- // so we have to close the socket to prevent a bad email from going out
2106
- stream.on('error', (err) => {
2107
- this.smtp.close();
2108
- this._senddone(err, stack);
2109
- });
2110
- }
2111
- /**
2112
- * @protected
2113
- * @param {Error} err err
2114
- * @param {MessageStack} stack stack
2115
- * @returns {void}
2116
- */
2117
- _senddone(err, stack) {
2118
- this.sending = false;
2119
- stack.callback(err, stack.message);
2120
- this._poll();
2121
- }
2122
- }
2123
-
2124
- exports.AUTH_METHODS = AUTH_METHODS;
2125
- exports.BUFFERSIZE = BUFFERSIZE;
2126
- exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
2127
- exports.MIME64CHUNK = MIME64CHUNK;
2128
- exports.MIMECHUNK = MIMECHUNK;
2129
- exports.Message = Message;
2130
- exports.SMTPClient = SMTPClient;
2131
- exports.SMTPConnection = SMTPConnection;
2132
- exports.SMTPError = SMTPError;
2133
- exports.SMTPErrorStates = SMTPErrorStates;
2134
- exports.SMTPResponseMonitor = SMTPResponseMonitor;
2135
- exports.SMTPState = SMTPState;
2136
- exports.addressparser = addressparser;
2137
- exports.getRFC2822Date = getRFC2822Date;
2138
- exports.getRFC2822DateUTC = getRFC2822DateUTC;
2139
- exports.isRFC2822Date = isRFC2822Date;
2140
- exports.mimeEncode = mimeEncode;
2141
- exports.mimeWordEncode = mimeWordEncode;
2142
- //# sourceMappingURL=email.cjs.map