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