nodemailer 10.4.0 → 10.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +21 -0
  3. package/dist/cjs/addressparser/index.js +185 -2
  4. package/dist/cjs/dkim/sign.js +2 -2
  5. package/dist/cjs/errors.d.ts +2 -0
  6. package/dist/cjs/errors.js +11 -1
  7. package/dist/cjs/json-transport/index.js +2 -0
  8. package/dist/cjs/mailer/index.d.ts +5 -0
  9. package/dist/cjs/mailer/index.js +56 -4
  10. package/dist/cjs/mailer/mail-message.d.ts +10 -0
  11. package/dist/cjs/mime-funcs/index.d.ts +2 -1
  12. package/dist/cjs/mime-funcs/index.js +72 -2
  13. package/dist/cjs/mime-node/index.js +1 -73
  14. package/dist/cjs/package-info.d.ts +1 -1
  15. package/dist/cjs/package-info.js +1 -1
  16. package/dist/cjs/shared/index.d.ts +23 -0
  17. package/dist/cjs/shared/index.js +79 -0
  18. package/dist/cjs/smtp-connection/index.js +6 -0
  19. package/dist/cjs/smtp-pool/index.d.ts +1 -0
  20. package/dist/cjs/smtp-pool/index.js +57 -6
  21. package/dist/cjs/smtp-pool/pool-resource.js +26 -4
  22. package/dist/cjs/smtp-transport/index.d.ts +1 -0
  23. package/dist/cjs/smtp-transport/index.js +47 -35
  24. package/dist/cjs/well-known/services.js +7 -0
  25. package/dist/esm/addressparser/index.js +185 -2
  26. package/dist/esm/dkim/sign.js +2 -2
  27. package/dist/esm/errors.d.ts +2 -0
  28. package/dist/esm/errors.js +9 -0
  29. package/dist/esm/json-transport/index.js +2 -0
  30. package/dist/esm/mailer/index.d.ts +5 -0
  31. package/dist/esm/mailer/index.js +56 -4
  32. package/dist/esm/mailer/mail-message.d.ts +10 -0
  33. package/dist/esm/mime-funcs/index.d.ts +2 -1
  34. package/dist/esm/mime-funcs/index.js +72 -2
  35. package/dist/esm/mime-node/index.js +1 -73
  36. package/dist/esm/package-info.d.ts +1 -1
  37. package/dist/esm/package-info.js +1 -1
  38. package/dist/esm/shared/index.d.ts +23 -0
  39. package/dist/esm/shared/index.js +78 -0
  40. package/dist/esm/smtp-connection/index.js +6 -0
  41. package/dist/esm/smtp-pool/index.d.ts +1 -0
  42. package/dist/esm/smtp-pool/index.js +57 -6
  43. package/dist/esm/smtp-pool/pool-resource.js +26 -4
  44. package/dist/esm/smtp-transport/index.d.ts +1 -0
  45. package/dist/esm/smtp-transport/index.js +47 -35
  46. package/dist/esm/well-known/services.js +7 -0
  47. package/dist/well-known/services.json +8 -0
  48. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## [10.5.0](https://github.com/nodemailer/nodemailer/compare/v10.4.1...v10.5.0) (2026-11-10)
4
+
5
+
6
+ ### Features
7
+
8
+ * **smtp:** support AbortSignal for individual sends ([#1911](https://github.com/nodemailer/nodemailer/issues/1911)) ([66387ed](https://github.com/nodemailer/nodemailer/commit/66387ed6f4bd26208b944b74b7329201ad77377b)), closes [#1910](https://github.com/nodemailer/nodemailer/issues/1910)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **dkim:** encode the d= domain the same way as the address headers ([#1908](https://github.com/nodemailer/nodemailer/issues/1908)) ([4ebf03f](https://github.com/nodemailer/nodemailer/commit/4ebf03fba33a96118c10afa340ce895a00549148))
14
+ * **mime-funcs:** encode header text that would be decoded as an invalid encoded word ([#1912](https://github.com/nodemailer/nodemailer/issues/1912)) ([7a7b942](https://github.com/nodemailer/nodemailer/commit/7a7b9427b632d8785190747ae2c62e88e77bc837))
15
+
16
+ ## [10.4.1](https://github.com/nodemailer/nodemailer/compare/v10.4.0...v10.4.1) (2026-11-10)
17
+
18
+
19
+ ### Bug Fixes
20
+
21
+ * **addressparser:** read whitespace and comments around a dot of the domain as CFWS ([c2b9c41](https://github.com/nodemailer/nodemailer/commit/c2b9c41bb81b2294ebadd294ad15ff035a17d0a5))
22
+ * **mime-node:** hand a domain to the UTS-46 mapper without lowercasing it first ([093e4dd](https://github.com/nodemailer/nodemailer/commit/093e4dd60af8a21e7f06a49c7f889291728e966a))
23
+
3
24
  ## [10.4.0](https://github.com/nodemailer/nodemailer/compare/v10.3.1...v10.4.0) (2026-11-07)
4
25
 
5
26
 
package/README.md CHANGED
@@ -14,6 +14,27 @@ See [nodemailer.com](https://nodemailer.com/) for documentation and terms.
14
14
 
15
15
  Nodemailer targets Node.js 20 and later. The ES module build also runs on [Bun](https://bun.sh/) (tested against the latest release) and on [Cloudflare Workers](https://developers.cloudflare.com/workers/) with the `nodejs_compat` compatibility flag. On Workers only the SMTP based transports apply, `sendmail` needs a child process, and the runtime does not allow turning certificate validation off, so `tls.rejectUnauthorized: false` fails there with an error.
16
16
 
17
+ ## Cancelling an individual SMTP send
18
+
19
+ Pass an `AbortSignal` in the message options to cancel one `sendMail()` call:
20
+
21
+ ```js
22
+ await transporter.sendMail({
23
+ from: 'sender@example.com',
24
+ to: 'recipient@example.com',
25
+ text: 'Hello',
26
+ signal: AbortSignal.timeout(30_000)
27
+ });
28
+ ```
29
+
30
+ This is supported by SMTP and pooled SMTP transports. A pre-aborted signal prevents processing; aborting later stops subsequent plugin processing, removes a queued message, or closes the SMTP connection assigned to that message. Other deliveries in the pool can continue. Both promise and callback forms report an error named `AbortError`, with `code: 'EABORT'` and the signal's reason as `cause`. The signal listener is removed when the send finishes.
31
+
32
+ Cancellation stops local processing; it does not prove that the SMTP server has not already accepted the message. Do not retry a cancelled send automatically on that assumption.
33
+
34
+ Work already started by a plugin or a custom `getSocket` hook requires that code's cooperation to stop. Nodemailer ignores late plugin completion and destroys a socket handed back after cancellation. Plugins can read `mail.data.signal` to cancel their own work.
35
+
36
+ Other bundled transports (stream, JSON, sendmail and SES) ignore the signal once the message is handed to them, so the message is sent normally. A signal that is already aborted, or aborts while plugins run, still cancels the send with `EABORT` on every transport, as that happens before the transport is called. A `signal` value that is not an `AbortSignal` fails the send with `ECONFIG`. Custom transports can opt in with `supportsAbortSignal: true`; their `send()` must register its abort listener synchronously, check for a pre-aborted signal, stop the work it owns, invoke its callback once, and remove the listener on completion.
37
+
17
38
  ## Having an issue?
18
39
 
19
40
  #### First review the docs
@@ -48,6 +48,30 @@ class TokenList {
48
48
  this.slots[at + 2] = end;
49
49
  return this.length++;
50
50
  }
51
+ /**
52
+ * Offset of the first character of a token that is part of its value. A text run that is
53
+ * no plain slice of the field still spans the whitespace and control characters its value
54
+ * is trimmed of.
55
+ */
56
+ contentStart(index) {
57
+ let start = this.slots[index * 3 + 1];
58
+ const end = this.slots[index * 3 + 2];
59
+ while (start < end && _isDroppedCode(this.str.charCodeAt(start))) {
60
+ start++;
61
+ }
62
+ return start;
63
+ }
64
+ /**
65
+ * Offset just past the last character of a token that is part of its value
66
+ */
67
+ contentEnd(index) {
68
+ const start = this.slots[index * 3 + 1];
69
+ let end = this.slots[index * 3 + 2];
70
+ while (end > start && _isDroppedCode(this.str.charCodeAt(end - 1))) {
71
+ end--;
72
+ }
73
+ return end;
74
+ }
51
75
  /**
52
76
  * The character of an operator token, an empty string for a text run
53
77
  */
@@ -183,6 +207,44 @@ function _isSpaceCode(code) {
183
207
  code === 0x3000 ||
184
208
  code === 0xfeff);
185
209
  }
210
+ /**
211
+ * Checks for the whitespace RFC 5322 folding whitespace is made of: SP and HTAB, plus the
212
+ * line break a fold carries. The other characters _isSpaceCode accepts are atext under
213
+ * RFC 6532, and parsers disagree on them: mailauth keeps U+00A0 in a domain, so joining a
214
+ * domain across one names a domain that reader never sees
215
+ *
216
+ * @param code Character code
217
+ * @return true if the character is folding whitespace
218
+ */
219
+ function _isFoldingSpaceCode(code) {
220
+ return code === 0x20 || code === 0x09 || code === 0x0d || code === 0x0a;
221
+ }
222
+ /**
223
+ * Checks if every character in a stretch of the field is folding whitespace
224
+ *
225
+ * @param str The field
226
+ * @param from Offset of the first character
227
+ * @param to Offset just past the last one
228
+ * @return true if the stretch holds nothing but folding whitespace
229
+ */
230
+ function _isFoldingGap(str, from, to) {
231
+ for (let i = from; i < to; i++) {
232
+ if (!_isFoldingSpaceCode(str.charCodeAt(i))) {
233
+ return false;
234
+ }
235
+ }
236
+ return true;
237
+ }
238
+ /**
239
+ * Checks for a character the value of a text run is trimmed of, or leaves out: whitespace,
240
+ * C0 controls and DEL
241
+ *
242
+ * @param code Character code
243
+ * @return true if the character is not part of the value at the edge of a run
244
+ */
245
+ function _isDroppedCode(code) {
246
+ return code < 0x20 || code === 0x7f || _isSpaceCode(code);
247
+ }
186
248
  /**
187
249
  * The characters JS `\w` matches without the unicode flag, the set the `\b` in
188
250
  * LOOSE_TEXT_ADDR is read against. charCodeAt off either end of the string gives NaN,
@@ -233,6 +295,9 @@ const LEADING_QUOTED_STRING = /^"(?:[^"\\]|\\[\s\S])*"/;
233
295
  * The scan is by index, a pattern such as /\s+@/ backtracks over a long whitespace run that
234
296
  * no '@' follows.
235
297
  *
298
+ * The whitespace around the dots of the domain that follows is dropped as well, see
299
+ * _joinDomainDotSpacing.
300
+ *
236
301
  * @param value Value holding the '@'
237
302
  * @param at Offset of the '@', or -1
238
303
  * @return The value with the whitespace beside that '@' removed
@@ -249,7 +314,86 @@ function _joinAtSpacing(value, at) {
249
314
  while (end < value.length && _isSpaceCode(value.charCodeAt(end))) {
250
315
  end++;
251
316
  }
252
- return start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
317
+ const joined = start === at && end === at + 1 ? value : value.slice(0, start) + '@' + value.slice(end);
318
+ return _joinDomainDotSpacing(joined, start);
319
+ }
320
+ // The ASCII atext characters: printable, and none of the RFC 5322 specials
321
+ const ASCII_ATEXT = new Uint8Array(0x80);
322
+ for (let code = 0x21; code < 0x7f; code++) {
323
+ ASCII_ATEXT[code] = '()<>[]:;@\\,."'.indexOf(String.fromCharCode(code)) < 0 ? 1 : 0;
324
+ }
325
+ /**
326
+ * Checks if a character can be part of an atom: anything but the specials, whitespace and
327
+ * the control characters (RFC 5322 3.2.3, with non-ASCII allowed as RFC 6532 does)
328
+ *
329
+ * @param code Character code
330
+ * @return true if the character is atext
331
+ */
332
+ function _isAtextCode(code) {
333
+ return code < 0x80 ? ASCII_ATEXT[code] === 1 : !_isSpaceCode(code);
334
+ }
335
+ /**
336
+ * Drops the whitespace around the dots of the domain behind the '@' at an offset.
337
+ *
338
+ * obs-domain is atoms with CFWS around the dots (RFC 5322 4.4), so 'user@victim.example
339
+ * .allowed.example' names user@victim.example.allowed.example. Read as two runs, the domain
340
+ * ended at the whitespace and the envelope went to victim.example, a different domain than
341
+ * the one an RFC 5322 parser, and an application validating the address with one, reads
342
+ * (GHSA-3q53-mvfw-q9v8). A comment around a dot reaches here as whitespace.
343
+ *
344
+ * Only SP, HTAB and a fold count as the whitespace, see _isFoldingSpaceCode.
345
+ *
346
+ * Only a dot with an atom on both sides joins, as for a conformant parser: whitespace that
347
+ * is not beside a dot ends the domain, and so does a dot that no atom follows, which keeps
348
+ * 'user@example.com .' from becoming a domain with a trailing dot. A domain literal is left
349
+ * alone. Everything from where the domain ends is kept as it is.
350
+ *
351
+ * @param value Value holding the '@'
352
+ * @param at Offset of the '@'
353
+ * @return The value with the whitespace around the dots of that domain removed
354
+ */
355
+ function _joinDomainDotSpacing(value, at) {
356
+ const len = value.length;
357
+ // '[' is no atext, so a domain literal ends the walk before it starts
358
+ let pos = at + 1;
359
+ let spaced = false;
360
+ for (;;) {
361
+ const labelStart = pos;
362
+ while (pos < len && _isAtextCode(value.charCodeAt(pos))) {
363
+ pos++;
364
+ }
365
+ if (pos === labelStart) {
366
+ break;
367
+ }
368
+ // the dot, with the whitespace on either side of it, and the label behind it
369
+ let next = pos;
370
+ while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
371
+ next++;
372
+ }
373
+ if (value.charCodeAt(next) !== 0x2e) {
374
+ break;
375
+ }
376
+ next++;
377
+ while (next < len && _isFoldingSpaceCode(value.charCodeAt(next))) {
378
+ next++;
379
+ }
380
+ if (next >= len || !_isAtextCode(value.charCodeAt(next))) {
381
+ break;
382
+ }
383
+ spaced = spaced || next !== pos + 1;
384
+ pos = next;
385
+ }
386
+ if (!spaced) {
387
+ return value;
388
+ }
389
+ // every whitespace character the walk covered sits beside a dot
390
+ let domain = '';
391
+ for (let k = at + 1; k < pos; k++) {
392
+ if (!_isFoldingSpaceCode(value.charCodeAt(k))) {
393
+ domain += value.charAt(k);
394
+ }
395
+ }
396
+ return value.slice(0, at + 1) + domain + value.slice(pos);
253
397
  }
254
398
  /**
255
399
  * Drops the whitespace beside the '@' that splits the domain off a value. That is the '@'
@@ -553,6 +697,15 @@ function _collectAddressParts(tokens, from, to) {
553
697
  // whether the last text run holds nothing but quoted text so far, which is what a quoted
554
698
  // local part is until the '@' after it joins the run
555
699
  let lastTextPureQuoted = false;
700
+ // whether the last text run holds an unquoted '@', so that it runs on into a domain, and
701
+ // whether nothing but comments has come since it, see the join below
702
+ let lastTextHasAt = false;
703
+ let lastTextOpen = false;
704
+ // Where the last text run, or the last comment since it, ended in the field, and whether
705
+ // everything between it and the comments since was folding whitespace. The tokens are
706
+ // trimmed of any whitespace, so this is read off the field itself.
707
+ let gapFrom = 0;
708
+ let gapsFolding = true;
556
709
  // Last character of the run each state is currently accumulating. Reading it back off
557
710
  // the accumulator with slice(-1) makes the engine flatten the whole growing string on
558
711
  // every token, which is quadratic over an address built from many comment-joined atoms
@@ -570,18 +723,27 @@ function _collectAddressParts(tokens, from, to) {
570
723
  case '<':
571
724
  state = 'address';
572
725
  insideQuotes = false;
726
+ lastTextOpen = false;
573
727
  break;
574
728
  case '(':
575
729
  state = 'comment';
576
730
  insideQuotes = false;
731
+ gapsFolding = gapsFolding && _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
577
732
  break;
578
733
  case '"':
579
734
  insideQuotes = !insideQuotes;
580
735
  state = 'text';
736
+ lastTextOpen = false;
581
737
  break;
582
738
  default:
583
739
  state = 'text';
584
740
  insideQuotes = false;
741
+ if (value !== ')') {
742
+ lastTextOpen = false;
743
+ }
744
+ else {
745
+ gapFrom = tokens.contentEnd(i);
746
+ }
585
747
  break;
586
748
  }
587
749
  }
@@ -598,8 +760,23 @@ function _collectAddressParts(tokens, from, to) {
598
760
  // of the '@', but it cannot join two atoms into one: gluing across it would read
599
761
  // 'user@example.com(x)evil.com' as the single domain 'example.comevil.com' and
600
762
  // deliver to a domain the sender never named.
763
+ // A comment beside a dot of a domain is CFWS inside obs-domain, with or without
764
+ // folding whitespace around it, so 'user@victim.example(x).allowed.example' names
765
+ // one domain (GHSA-3q53-mvfw-q9v8). Any other whitespace in between keeps them apart.
766
+ // A ')' always leaves the walk in unquoted text, so neither needs checking here.
767
+ // Neither join across a comment takes in a second '@' once the run holds one: the
768
+ // address would then split at the last '@', and 'user@company(x).com@attacker.net',
769
+ // which an RFC 5322 parser reads as user@company.com, would go to attacker.net.
601
770
  const parts = data[state];
602
- const joins = prevNoBreak && parts.length && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@');
771
+ const secondAt = lastTextHasAt && prevOperator === ')' && value.indexOf('@') >= 0;
772
+ const joinsDomain = !secondAt &&
773
+ lastTextOpen &&
774
+ lastTextHasAt &&
775
+ prevOperator === ')' &&
776
+ (lastChars.text === '.' || value.charAt(0) === '.') &&
777
+ gapsFolding &&
778
+ _isFoldingGap(tokens.str, gapFrom, tokens.contentStart(i));
779
+ const joins = joinsDomain || (!secondAt && prevNoBreak && parts.length > 0 && (prevOperator !== ')' || lastChars[state] === '@' || value.charAt(0) === '@'));
603
780
  if (joins) {
604
781
  const last = data[state].length - 1;
605
782
  if (state === 'text' && !insideQuotes) {
@@ -624,6 +801,12 @@ function _collectAddressParts(tokens, from, to) {
624
801
  lastTextPureQuoted = insideQuotes;
625
802
  }
626
803
  }
804
+ if (state === 'text') {
805
+ lastTextHasAt = (joins && lastTextHasAt) || (!insideQuotes && value.indexOf('@') >= 0);
806
+ lastTextOpen = true;
807
+ gapFrom = tokens.contentEnd(i);
808
+ gapsFolding = true;
809
+ }
627
810
  }
628
811
  }
629
812
  // If there is no text but a comment, replace the two. A comment is never part of a
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- const punycode = __importStar(require("../punycode/index.js"));
39
+ const shared = __importStar(require("../shared/index.js"));
40
40
  const mimeFuncs = __importStar(require("../mime-funcs/index.js"));
41
41
  const node_crypto_1 = __importDefault(require("node:crypto"));
42
42
  const errors = __importStar(require("../errors.js"));
@@ -103,7 +103,7 @@ function generateDKIMHeader(domainName, keySelector, fieldNames, hashAlgo, bodyH
103
103
  'v=1',
104
104
  'a=rsa-' + hashAlgo,
105
105
  'c=relaxed/relaxed',
106
- 'd=' + punycode.toASCII(cleanTagValue(domainName)),
106
+ 'd=' + shared.normalizeDomain(cleanTagValue(domainName), false),
107
107
  'q=dns/txt',
108
108
  's=' + cleanTagValue(keySelector),
109
109
  'bh=' + bodyHash,
@@ -23,6 +23,7 @@ export declare const ERROR_CODES: {
23
23
  readonly EMESSAGE: "Message delivery error";
24
24
  readonly EOTP: "Invalid one-time passcode data (otp option)";
25
25
  readonly ESTREAM: "Stream processing error";
26
+ readonly EABORT: "Message sending aborted";
26
27
  readonly EAUTH: "Authentication failed";
27
28
  readonly ENOAUTH: "Authentication credentials not provided";
28
29
  readonly EOAUTH2: "OAuth2 token generation or refresh error";
@@ -51,6 +52,7 @@ export declare const EENVELOPE = "EENVELOPE";
51
52
  export declare const EMESSAGE = "EMESSAGE";
52
53
  export declare const EOTP = "EOTP";
53
54
  export declare const ESTREAM = "ESTREAM";
55
+ export declare const EABORT = "EABORT";
54
56
  export declare const EAUTH = "EAUTH";
55
57
  export declare const ENOAUTH = "ENOAUTH";
56
58
  export declare const EOAUTH2 = "EOAUTH2";
@@ -10,7 +10,7 @@
10
10
  * err.code = errors.ECONNECTION;
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.ERR_ACCESS_DENIED = exports.isPermanentResponseCode = exports.isTransientError = exports.EFETCH = exports.EURLACCESS = exports.EFILEACCESS = exports.EPROXY = exports.ECONFIG = exports.ESES = exports.ESENDMAIL = exports.EMAXRECIPIENTS = exports.EMAXLIMIT = exports.EOAUTH2 = exports.ENOAUTH = exports.EAUTH = exports.ESTREAM = exports.EOTP = exports.EMESSAGE = exports.EENVELOPE = exports.EPROTOCOL = exports.EREQUIRETLS = exports.ETLS = exports.EDNS = exports.ESOCKET = exports.ETIMEDOUT = exports.ECONNECTION = exports.ERROR_CODES = void 0;
13
+ exports.ERR_ACCESS_DENIED = exports.isPermanentResponseCode = exports.isTransientError = exports.createAbortError = exports.EFETCH = exports.EURLACCESS = exports.EFILEACCESS = exports.EPROXY = exports.ECONFIG = exports.ESES = exports.ESENDMAIL = exports.EMAXRECIPIENTS = exports.EMAXLIMIT = exports.EOAUTH2 = exports.ENOAUTH = exports.EAUTH = exports.EABORT = exports.ESTREAM = exports.EOTP = exports.EMESSAGE = exports.EENVELOPE = exports.EPROTOCOL = exports.EREQUIRETLS = exports.ETLS = exports.EDNS = exports.ESOCKET = exports.ETIMEDOUT = exports.ECONNECTION = exports.ERROR_CODES = void 0;
14
14
  /**
15
15
  * Error code descriptions for documentation and debugging
16
16
  */
@@ -29,6 +29,7 @@ exports.ERROR_CODES = {
29
29
  EMESSAGE: 'Message delivery error',
30
30
  EOTP: 'Invalid one-time passcode data (otp option)',
31
31
  ESTREAM: 'Stream processing error',
32
+ EABORT: 'Message sending aborted',
32
33
  // Authentication errors
33
34
  EAUTH: 'Authentication failed',
34
35
  ENOAUTH: 'Authentication credentials not provided',
@@ -58,6 +59,7 @@ exports.EENVELOPE = 'EENVELOPE';
58
59
  exports.EMESSAGE = 'EMESSAGE';
59
60
  exports.EOTP = 'EOTP';
60
61
  exports.ESTREAM = 'ESTREAM';
62
+ exports.EABORT = 'EABORT';
61
63
  exports.EAUTH = 'EAUTH';
62
64
  exports.ENOAUTH = 'ENOAUTH';
63
65
  exports.EOAUTH2 = 'EOAUTH2';
@@ -70,6 +72,14 @@ exports.EPROXY = 'EPROXY';
70
72
  exports.EFILEACCESS = 'EFILEACCESS';
71
73
  exports.EURLACCESS = 'EURLACCESS';
72
74
  exports.EFETCH = 'EFETCH';
75
+ /** Creates the error reported when a caller cancels an individual send. @internal */
76
+ const createAbortError = (signal) => {
77
+ const err = new Error('Message sending aborted', { cause: signal.reason });
78
+ err.name = 'AbortError';
79
+ err.code = exports.EABORT;
80
+ return err;
81
+ };
82
+ exports.createAbortError = createAbortError;
73
83
  /**
74
84
  * Tells whether the error ended the connection rather than rejected what was sent over it
75
85
  */
@@ -83,6 +83,8 @@ class JSONTransport {
83
83
  }
84
84
  delete data.envelope;
85
85
  delete data.normalizedHeaders;
86
+ // the per-message AbortSignal is not message data
87
+ delete data.signal;
86
88
  // the message field is the object itself with skipEncoding, the
87
89
  // createTransport overload for that option types the result accordingly
88
90
  return done(null, {
@@ -112,6 +112,11 @@ export interface MailMeta {
112
112
  * declared on Transport, Transporter and Mail
113
113
  */
114
114
  export interface Transport<T = SentMessageInfo, D extends TransportOptions = TransportOptions> {
115
+ /**
116
+ * Set only if send() cancels its own work on mail.data.signal and removes its signal listener
117
+ * when finished. Without it the signal is still honored up to dispatch, then ignored.
118
+ */
119
+ supportsAbortSignal?: boolean | undefined;
115
120
  /** Transport name, used for logging */
116
121
  name: string;
117
122
  /** Transport version, used for logging */
@@ -56,6 +56,16 @@ const node_crypto_1 = __importDefault(require("node:crypto"));
56
56
  * asks a server to accept 100, so a real send is bounded far below this.
57
57
  */
58
58
  const DEFAULT_MAX_RECIPIENTS = 100000;
59
+ /**
60
+ * Duck-typed so that signals from another realm or a polyfill are accepted as well
61
+ */
62
+ function isAbortSignal(value) {
63
+ return (typeof value === 'object' &&
64
+ value !== null &&
65
+ 'aborted' in value &&
66
+ typeof value.addEventListener === 'function' &&
67
+ typeof value.removeEventListener === 'function');
68
+ }
59
69
  /**
60
70
  * Creates an object for exposing the Mail API
61
71
  *
@@ -157,11 +167,43 @@ class Mail extends node_events_1.EventEmitter {
157
167
  this.getSocket = false;
158
168
  }
159
169
  const mail = new mail_message_js_1.default(this, data);
170
+ const signalOption = mail.data.signal;
171
+ const signal = isAbortSignal(signalOption) ? signalOption : undefined;
172
+ let settled = false;
173
+ const removeAbortListener = () => signal?.removeEventListener('abort', onAbort);
174
+ const finish = (err, info) => {
175
+ if (settled) {
176
+ return;
177
+ }
178
+ settled = true;
179
+ removeAbortListener();
180
+ if (err) {
181
+ mail.releaseStreams();
182
+ }
183
+ done(err, info);
184
+ };
160
185
  // a failed message is not going to be read anymore, release its content streams
161
186
  const fail = (err) => {
162
- mail.releaseStreams();
163
- done(err);
187
+ finish(err);
164
188
  };
189
+ function onAbort() {
190
+ fail(errors.createAbortError(signal));
191
+ }
192
+ if (signalOption !== undefined && signalOption !== null && !signal) {
193
+ const err = new Error('The signal option must be an AbortSignal');
194
+ err.code = errors.ECONFIG;
195
+ setImmediate(() => fail(err));
196
+ return promise;
197
+ }
198
+ // Mail handles a pre-aborted signal and cancellation during plugin processing for every
199
+ // transport; a transport without supportsAbortSignal ignores the signal once it is called
200
+ if (signal) {
201
+ signal.addEventListener('abort', onAbort, { once: true });
202
+ if (signal.aborted) {
203
+ setImmediate(onAbort);
204
+ return promise;
205
+ }
206
+ }
165
207
  this.logger.debug({
166
208
  tnx: 'transport',
167
209
  name: this.transporter.name,
@@ -169,6 +211,9 @@ class Mail extends node_events_1.EventEmitter {
169
211
  action: 'send'
170
212
  }, 'Sending mail using %s/%s', this.transporter.name, this.transporter.version);
171
213
  this._processPlugins('compile', mail, err => {
214
+ if (settled) {
215
+ return;
216
+ }
172
217
  if (err) {
173
218
  this.logger.error({
174
219
  err,
@@ -206,6 +251,9 @@ class Mail extends node_events_1.EventEmitter {
206
251
  return fail(err);
207
252
  }
208
253
  this._processPlugins('stream', mail, err => {
254
+ if (settled) {
255
+ return;
256
+ }
209
257
  if (err) {
210
258
  this.logger.error({
211
259
  err,
@@ -225,16 +273,17 @@ class Mail extends node_events_1.EventEmitter {
225
273
  return dkim.sign(input, mail.data._dkim);
226
274
  });
227
275
  }
276
+ // The transport takes ownership of cancellation from here, including queued work.
277
+ removeAbortListener();
228
278
  this.transporter.send(mail, (...args) => {
229
279
  if (args[0]) {
230
- mail.releaseStreams();
231
280
  this.logger.error({
232
281
  err: args[0],
233
282
  tnx: 'transport',
234
283
  action: 'send'
235
284
  }, 'Send Error: %s', args[0].message);
236
285
  }
237
- done(...args);
286
+ finish(...args);
238
287
  });
239
288
  });
240
289
  });
@@ -264,6 +313,9 @@ class Mail extends node_events_1.EventEmitter {
264
313
  let pos = 0;
265
314
  let block = 'default';
266
315
  const processPlugins = () => {
316
+ if (mail.data.signal?.aborted) {
317
+ return callback(errors.createAbortError(mail.data.signal));
318
+ }
267
319
  let curplugins = block === 'default' ? defaultPlugins : userPlugins;
268
320
  if (pos >= curplugins.length) {
269
321
  if (block === 'default' && userPlugins.length) {
@@ -13,6 +13,16 @@ import type { SentMessageInfo } from './index.js';
13
13
  * tree is built from, the fields below are the ones the mailer reads on top of those
14
14
  */
15
15
  export interface SendMailOptions extends MailComposerOptions {
16
+ /**
17
+ * Cancel this send, including waiting for plugins or in an SMTP pool queue.
18
+ * Plugins must cooperate with the signal to stop their own work already in progress.
19
+ * Supported by SMTP, pooled SMTP and transports declaring supportsAbortSignal. Other
20
+ * transports ignore the signal once the message is handed to them; a signal that is
21
+ * already aborted, or aborts during plugin processing, still cancels the send.
22
+ * Fails with AbortError/EABORT on cancellation, ECONFIG if the value is not an AbortSignal.
23
+ * Aborting does not prove that the server has not already accepted the message.
24
+ */
25
+ signal?: AbortSignal | undefined;
16
26
  /** DKIM signing options for this message, used instead of the ones of the transporter */
17
27
  dkim?: DKIMOptions | undefined;
18
28
  /** Extra DKIM options for this message, merged over the options of the signer. The SES transport sets skipFields here, the option is not meant for callers */
@@ -74,7 +74,8 @@ export declare function hasLongerLines(str: string, lineLength: number): boolean
74
74
  */
75
75
  export declare function encodeWord(data: string | Buffer, mimeWordEncoding?: string, maxLength?: number): string;
76
76
  /**
77
- * Finds word sequences with non ascii text and converts these to mime words
77
+ * Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
78
+ * and converts these to mime words. A valid encoded-word is passed through as it is.
78
79
  *
79
80
  * @param value String to be encoded
80
81
  * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
@@ -181,8 +181,75 @@ function encodeWord(data, mimeWordEncoding, maxLength) {
181
181
  }
182
182
  return '=?' + toCharset + '?' + mimeWordEncoding + '?' + encodedStr + (encodedStr.substr(-2) === '?=' ? '' : '?=');
183
183
  }
184
+ // An encoded-word as RFC 2047 section 2 spells it: a charset token (with an optional RFC 2231
185
+ // language), B or Q, and encoded text without '?' or whitespace. None of the parts can hold the
186
+ // '?' that separates them, so the pattern never backtracks
187
+ const VALID_ENCODED_WORD = /^=\?[^\s()<>@,;:"/[\]?.=]+\?[BbQq]\?[^?\s]+\?=$/;
188
+ // What a lenient decoder reads as an encoded-word: libmime and Python decode
189
+ // '=?utf-8?Q?a b?=' across the space as well. Applied sticky at a '=?', and every part stops
190
+ // at the next '?', so it does not backtrack either
191
+ const LENIENT_ENCODED_WORD = /[=]\?[^?]*\?[BbQq]\?[^?]*\?=/y;
184
192
  /**
185
- * Finds word sequences with non ascii text and converts these to mime words
193
+ * Marks the text a receiver would read as an encoded-word when it is not one valid encoded-word
194
+ * on its own. RFC 2047 section 7 requires that a word beginning with '=?' and ending with '?='
195
+ * is a valid encoded-word, and decoders also decode a look-alike that spans whitespace, so
196
+ * '=?utf-8?X?x?=' and 'see =?utf-8?Q?a b?= here' read differently on every receiver. A valid
197
+ * encoded-word is left alone, which is what lets a caller pass a value that is already encoded,
198
+ * as most other mail libraries do.
199
+ *
200
+ * The bounds of the word around each '=?' are found once per word and reused, walking back to
201
+ * the start of a long word from every '=?' it holds would be quadratic.
202
+ *
203
+ * @param value String to look in
204
+ * @param range The first and the last offset that needs encoding so far, -1 for none
205
+ * @return The range, widened to cover the words of every invalid look-alike
206
+ */
207
+ function _markInvalidEncodedWords(value, range) {
208
+ const len = value.length;
209
+ const isSpace = (pos) => /\s/.test(value.charAt(pos));
210
+ // the word last looked at, its start and the offset just past it
211
+ let wordStart = 0;
212
+ let wordEnd = -1;
213
+ const wordAt = (pos) => {
214
+ if (pos < wordEnd) {
215
+ return;
216
+ }
217
+ // the previous word ended at whitespace, so the walk back stops before reaching it
218
+ wordStart = pos;
219
+ while (wordStart > 0 && !isSpace(wordStart - 1)) {
220
+ wordStart--;
221
+ }
222
+ wordEnd = pos;
223
+ while (wordEnd < len && !isSpace(wordEnd)) {
224
+ wordEnd++;
225
+ }
226
+ };
227
+ let pos = value.indexOf('=?');
228
+ while (pos >= 0) {
229
+ wordAt(pos);
230
+ const start = wordStart;
231
+ LENIENT_ENCODED_WORD.lastIndex = pos;
232
+ const match = LENIENT_ENCODED_WORD.exec(value);
233
+ const end = match ? pos + match[0].length : wordEnd;
234
+ if (match && end > wordEnd) {
235
+ // the look-alike runs across whitespace, on to the word it ends in
236
+ wordAt(end - 1);
237
+ }
238
+ const word = value.substring(start, wordEnd);
239
+ // without a match, a word that begins with '=?' and ends with '?=' is still invalid
240
+ const looksLike = match ? true : start === pos && word.length >= 4 && word.endsWith('?=');
241
+ const valid = start === pos && wordEnd === end && word.length <= 75 && VALID_ENCODED_WORD.test(word);
242
+ if (looksLike && !valid) {
243
+ range[0] = range[0] < 0 ? start : Math.min(range[0], start);
244
+ range[1] = Math.max(range[1], wordEnd - 1);
245
+ }
246
+ pos = value.indexOf('=?', match ? end : pos + 2);
247
+ }
248
+ return range;
249
+ }
250
+ /**
251
+ * Finds word sequences with non ascii text, and words that look like an invalid encoded-word,
252
+ * and converts these to mime words. A valid encoded-word is passed through as it is.
186
253
  *
187
254
  * @param value String to be encoded
188
255
  * @param mimeWordEncoding='Q' Encoding for the mime word, either Q or B
@@ -206,11 +273,14 @@ function encodeWords(value, mimeWordEncoding, maxLength, encodeAll) {
206
273
  lastSpecial = i;
207
274
  }
208
275
  }
276
+ if (value.indexOf('=?') >= 0) {
277
+ [firstSpecial, lastSpecial] = _markInvalidEncodedWords(value, [firstSpecial, lastSpecial]);
278
+ }
209
279
  if (firstSpecial < 0) {
210
280
  return value;
211
281
  }
212
282
  if (encodeAll) {
213
- // if it is requested to encode everything or the string contains something that resebles encoded word, then encode everything
283
+ // the value needs encoding and it is requested to encode everything
214
284
  return encodeWord(value, mimeWordEncoding, maxLength);
215
285
  }
216
286
  // encode from the start of the word holding the first such character to the end of the