emailengine-app 2.74.1 → 2.75.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 (60) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/data/google-crawlers.json +1 -1
  3. package/lib/account.js +117 -63
  4. package/lib/api-routes/changes-routes.js +51 -0
  5. package/lib/api-routes/index.js +160 -0
  6. package/lib/api-routes/message-routes.js +3 -1
  7. package/lib/consts.js +21 -0
  8. package/lib/db.js +4 -1
  9. package/lib/egress-filter.js +220 -0
  10. package/lib/email-client/base-client.js +5 -8
  11. package/lib/email-client/gmail/send-request.js +69 -0
  12. package/lib/email-client/gmail-client.js +6 -46
  13. package/lib/email-client/imap/detach-client.js +27 -0
  14. package/lib/email-client/imap/listing-diff.js +165 -0
  15. package/lib/email-client/imap/mailbox.js +35 -22
  16. package/lib/email-client/imap/subconnection.js +2 -4
  17. package/lib/email-client/imap/sync-operations.js +5 -3
  18. package/lib/email-client/imap-client.js +50 -84
  19. package/lib/email-client/notification-handler.js +11 -12
  20. package/lib/email-client/outlook/send-request.js +48 -0
  21. package/lib/email-client/outlook-client.js +7 -19
  22. package/lib/export.js +97 -21
  23. package/lib/imapproxy/imap-core/README.md +69 -0
  24. package/lib/imapproxy/imap-core/lib/imap-connection.js +1 -1
  25. package/lib/logger.js +14 -6
  26. package/lib/oauth/external-account-config.js +41 -1
  27. package/lib/oauth/external-account-signer.js +7 -2
  28. package/lib/oauth/verify-app.js +18 -3
  29. package/lib/queue-retention.js +56 -0
  30. package/lib/rate-limit.js +33 -11
  31. package/lib/respawn-backoff.js +95 -0
  32. package/lib/response-stream.js +138 -0
  33. package/lib/schemas.js +9 -2
  34. package/lib/sentry.js +8 -0
  35. package/lib/settings.js +4 -1
  36. package/lib/smtp-message-processor.js +131 -0
  37. package/lib/tools.js +48 -5
  38. package/lib/ui-routes/admin-config-routes.js +22 -18
  39. package/lib/ui-routes/internals-routes.js +32 -0
  40. package/lib/utils/network.js +122 -3
  41. package/lib/web-safe-html.js +401 -0
  42. package/lib/webhook-request.js +40 -2
  43. package/lib/webhooks.js +2 -3
  44. package/package.json +15 -13
  45. package/sbom.json +1 -1
  46. package/server.js +33 -8
  47. package/static/js/ee-client.js +55 -6
  48. package/static/js/ui.js +13 -0
  49. package/static/licenses.html +336 -286
  50. package/translations/messages.pot +12 -12
  51. package/views/config/webhooks.hbs +2 -2
  52. package/views/internals/index.hbs +8 -0
  53. package/views/partials/webhooks_editor_functions.hbs +1 -1
  54. package/workers/api.js +52 -233
  55. package/workers/documents.js +6 -0
  56. package/workers/export.js +37 -16
  57. package/workers/imap.js +64 -29
  58. package/workers/smtp.js +50 -91
  59. package/workers/submit.js +10 -0
  60. package/workers/webhooks.js +23 -2
@@ -1,7 +1,16 @@
1
1
  'use strict';
2
2
 
3
- const crypto = require('crypto');
4
- const { serialize, unserialize, compareExisting, normalizePath, download, filterEmptyObjectValues, validUidValidity } = require('../../tools');
3
+ const {
4
+ serialize,
5
+ unserialize,
6
+ compareExisting,
7
+ normalizePath,
8
+ download,
9
+ filterEmptyObjectValues,
10
+ validUidValidity,
11
+ mailboxPathHash,
12
+ getMailboxStatusKey
13
+ } = require('../../tools');
5
14
  const msgpack = require('msgpack5')();
6
15
  const he = require('he');
7
16
  const libmime = require('libmime');
@@ -9,7 +18,7 @@ const settings = require('../../settings');
9
18
  const { bounceDetect } = require('../../bounce-detect');
10
19
  const { arfDetect } = require('../../arf-detect');
11
20
  const appendList = require('../../append-list');
12
- const { mimeHtml } = require('@postalsys/email-text-tools');
21
+ const { messageWebSafeHtml } = require('../../web-safe-html');
13
22
  const simpleParser = require('mailparser').simpleParser;
14
23
  const ical = require('ical.js');
15
24
  const addressparser = require('nodemailer/lib/addressparser');
@@ -29,7 +38,6 @@ const {
29
38
  REDIS_PREFIX,
30
39
  MAX_INLINE_ATTACHMENT_SIZE,
31
40
  MAX_ALLOWED_DOWNLOAD_SIZE,
32
- MAILBOX_HASH,
33
41
  TRANSIENT_NETWORK_CODES,
34
42
  PHANTOM_SELECT_FAIL_THRESHOLD,
35
43
  PHANTOM_REPROBE_INTERVAL
@@ -88,7 +96,13 @@ class Mailbox {
88
96
  this.previouslyConnected = false;
89
97
 
90
98
  // Generate unique Redis key for this mailbox based on path hash
91
- this.redisKey = BigInt('0x' + crypto.createHash(MAILBOX_HASH).update(normalizePath(this.path)).digest('hex')).toString(36);
99
+ this.redisKey = mailboxPathHash(this.path);
100
+
101
+ // Built once, through the shared helper: Account.getMailboxListing() reads these counters
102
+ // back through the same helper and the two have to agree byte for byte, but the key is
103
+ // also read several times per folder on every sync pass and rebuilding it would re-run
104
+ // the SHA1 + BigInt + base36 derivation every time.
105
+ this.mailboxStatusKey = getMailboxStatusKey(this.connection.account, this.path);
92
106
 
93
107
  this.runPartialSyncTimer = false; // Timer for delayed partial sync after EXISTS
94
108
 
@@ -367,7 +381,7 @@ class Mailbox {
367
381
  * Gets Redis key for storing mailbox metadata (hash)
368
382
  */
369
383
  getMailboxKey() {
370
- return `${REDIS_PREFIX}iam:${this.connection.account}:h:${this.redisKey}`;
384
+ return this.mailboxStatusKey;
371
385
  }
372
386
 
373
387
  /**
@@ -1632,10 +1646,7 @@ class Mailbox {
1632
1646
  let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
1633
1647
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1634
1648
  // convert to web safe
1635
- messageInfo.text._generatedHtml = mimeHtml({
1636
- html: messageInfo.text.html,
1637
- text: messageInfo.text.plain
1638
- });
1649
+ messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
1639
1650
  messageInfo.text.webSafe = true;
1640
1651
 
1641
1652
  // Embed images referenced by Content-ID
@@ -2600,11 +2611,22 @@ class Mailbox {
2600
2611
 
2601
2612
  let messageData = await connectionClient.fetchOne(message.uid, fields, { uid: true });
2602
2613
 
2614
+ if (!messageData || !messageData.uid) {
2615
+ //TODO: support partial responses
2616
+ this.logger.debug({ msg: 'Partial FETCH response', code: 'partial_fetch', query: { range: message.uid, fields, opts: { uid: true } } });
2617
+ return false;
2618
+ }
2619
+
2603
2620
  // Mark as seen if requested
2604
- if (options.markAsSeen && (!messageData.flags || !messageData.flags.has('\\Seen'))) {
2621
+ if (options.markAsSeen && !messageData.flags?.has('\\Seen')) {
2605
2622
  try {
2606
2623
  let res = await connectionClient.messageFlagsAdd(message.uid, ['\\Seen'], { uid: true });
2607
- if (res) {
2624
+ // Mirror the flag locally so the returned message reflects it. A
2625
+ // caller-provided field list can leave FLAGS out and a server can
2626
+ // answer the FETCH without them - in that case there is nothing to
2627
+ // mirror into, and inventing a set here would report the message as
2628
+ // carrying \Seen and no other flag
2629
+ if (res && messageData.flags) {
2608
2630
  messageData.flags.add('\\Seen');
2609
2631
  }
2610
2632
  } catch (err) {
@@ -2612,12 +2634,6 @@ class Mailbox {
2612
2634
  }
2613
2635
  }
2614
2636
 
2615
- if (!messageData || !messageData.uid) {
2616
- //TODO: support partial responses
2617
- this.logger.debug({ msg: 'Partial FETCH response', code: 'partial_fetch', query: { range: message.uid, fields, opts: { uid: true } } });
2618
- return false;
2619
- }
2620
-
2621
2637
  messageInfo = await this.getMessageInfo(messageData, true);
2622
2638
  } finally {
2623
2639
  if (lock) {
@@ -2661,10 +2677,7 @@ class Mailbox {
2661
2677
 
2662
2678
  // Convert to web-safe HTML if requested
2663
2679
  if (options.preProcessHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
2664
- messageInfo.text.html = mimeHtml({
2665
- html: messageInfo.text.html,
2666
- text: messageInfo.text.plain
2667
- });
2680
+ messageInfo.text.html = await messageWebSafeHtml(messageInfo);
2668
2681
  messageInfo.text.webSafe = true;
2669
2682
  }
2670
2683
 
@@ -3,6 +3,7 @@
3
3
  const { ImapFlow } = require('imapflow');
4
4
  const { backOff } = require('exponential-backoff');
5
5
  const { ReconnectBackoff } = require('../reconnect-backoff');
6
+ const { detachImapClient } = require('./detach-client');
6
7
  const EventEmitter = require('events').EventEmitter;
7
8
 
8
9
  const MAX_WAIT_DELAY = 450; //ms
@@ -178,10 +179,7 @@ class Subconnection extends EventEmitter {
178
179
  let prevImapClient = this.imapClient;
179
180
  prevImapClient.disabled = true;
180
181
  try {
181
- prevImapClient.removeAllListeners();
182
- prevImapClient.once('error', err => {
183
- this.logger.warn({ msg: 'IMAP connection error', previous: true, account: this.account, err });
184
- });
182
+ detachImapClient(prevImapClient, this.logger, { type: 'subConnection', previous: true, account: this.account });
185
183
  prevImapClient.close();
186
184
  } catch (err) {
187
185
  this.logger.warn({ msg: 'IMAP close error', err });
@@ -275,7 +275,9 @@ class SyncOperations {
275
275
 
276
276
  // Record every message currently on the server as already-seen, without queuing notifications
277
277
  for await (let messageData of imapClient.fetch('1:*', fields, { uid: true })) {
278
- if (!messageData || !messageData.uid) {
278
+ // A server can answer a FETCH without the fields it was asked for, and
279
+ // everything below this point dereferences the flag set
280
+ if (!messageData || !messageData.uid || !messageData.flags) {
279
281
  continue;
280
282
  }
281
283
  // ignore Recent flag
@@ -378,7 +380,7 @@ class SyncOperations {
378
380
 
379
381
  // Fetch all messages in range
380
382
  for await (let messageData of imapClient.fetch(range, fields, opts)) {
381
- if (!messageData || !messageData.uid) {
383
+ if (!messageData || !messageData.uid || (fields.flags && !messageData.flags)) {
382
384
  //TODO: support partial responses
383
385
  this.logger.debug({ msg: 'Partial FETCH response', code: 'partial_fetch', query: { range, fields, opts } });
384
386
  continue;
@@ -539,7 +541,7 @@ class SyncOperations {
539
541
  try {
540
542
  // Fetch and process each message
541
543
  for await (let messageData of imapClient.fetch(range, fields, opts)) {
542
- if (!messageData || !messageData.uid) {
544
+ if (!messageData || !messageData.uid || (fields.flags && !messageData.flags)) {
543
545
  //TODO: support partial responses
544
546
  this.logger.debug({ msg: 'Partial FETCH response', code: 'partial_fetch', query: { range, fields, opts } });
545
547
  continue;
@@ -13,6 +13,8 @@ const { BaseClient } = require('./base-client');
13
13
  const { oauth2Apps } = require('../oauth2-apps');
14
14
 
15
15
  const { Subconnection } = require('./imap/subconnection');
16
+ const { decodeStoredListing, diffMailboxListing, buildStoredListingObject } = require('./imap/listing-diff');
17
+ const { detachImapClient } = require('./imap/detach-client');
16
18
  const { ReconnectBackoff } = require('./reconnect-backoff');
17
19
 
18
20
  const {
@@ -396,7 +398,7 @@ class IMAPClient extends BaseClient {
396
398
  }
397
399
 
398
400
  this.commandClient = null;
399
- commandClient.removeAllListeners();
401
+ detachImapClient(commandClient, this.logger, { type: 'commandClient', cid: commandCid, account: this.account });
400
402
  commandClient = null;
401
403
  });
402
404
 
@@ -637,15 +639,6 @@ class IMAPClient extends BaseClient {
637
639
 
638
640
  // Get mailbox listing from server
639
641
  let listing = await connectionClient.list(options);
640
- if (!listing.length) {
641
- // server bug, the list can never be empty
642
- if (this.imapClient) {
643
- this.imapClient.close();
644
- }
645
- let error = new Error('Server bug: empty mailbox listing');
646
- error.code = 'ServerBug';
647
- throw error;
648
- }
649
642
 
650
643
  // Extract delimiter from INBOX (most reliable source)
651
644
  let inboxData = (listing || []).find(entry => /^INBOX$/i.test(entry.path));
@@ -661,70 +654,60 @@ class IMAPClient extends BaseClient {
661
654
  return mailbox;
662
655
  });
663
656
 
664
- let hasChanges = false;
657
+ // Checked AFTER filtering, not just on the raw response: INBOX always exists and is
658
+ // always selectable, so a listing with nothing selectable left is the same server bug as
659
+ // an empty one. Treating it as real would clear every stored folder below - wiping each
660
+ // folder's message index and firing a mailboxDeleted webhook per folder - on a listing
661
+ // that only failed to report a single selectable folder for one pass.
662
+ if (!listing.length) {
663
+ // server bug, the list can never be empty
664
+ if (this.imapClient) {
665
+ this.imapClient.close();
666
+ }
667
+ let error = new Error('Server bug: empty mailbox listing');
668
+ error.code = 'ServerBug';
669
+ throw error;
670
+ }
665
671
 
666
- // compare listing for new / deleted / renamed folders
667
- let storedListing = await this.redis.hgetallBuffer(this.getMailboxListKey());
672
+ // compare listing for new / deleted / renamed folders (see lib/email-client/imap/listing-diff.js)
673
+ const { entries: storedListing, corruptPaths } = decodeStoredListing(await this.redis.hgetallBuffer(this.getMailboxListKey()));
668
674
 
669
- storedListing = Object.keys(storedListing || {})
670
- .map(path => {
671
- try {
672
- return msgpack.decode(storedListing[path]);
673
- } catch (err) {
674
- // should not happen
675
- }
676
- return false;
677
- })
678
- .filter(entry => entry);
679
-
680
- // Build lookup map from stored listing for O(1) access
681
- const storedListingMap = new Map();
682
- for (const entry of storedListing) {
683
- storedListingMap.set(normalizePath(entry.path), entry);
684
- }
685
-
686
- // compare listings to detect changes
687
- for (let mailbox of listing) {
688
- let existingMailbox = storedListingMap.get(normalizePath(mailbox.path));
689
- if (!existingMailbox) {
690
- // found new!
691
- mailbox.isNew = true;
692
- hasChanges = true;
693
- } else if (
694
- existingMailbox.delimiter !== mailbox.delimiter ||
695
- existingMailbox.specialUseSource !== mailbox.specialUseSource ||
696
- existingMailbox.noInferiors !== mailbox.noInferiors
697
- ) {
698
- hasChanges = true;
675
+ // Flags entries of `listing` as isNew as a side effect - that one-shot flag is what makes
676
+ // processListing() emit mailboxNew, so it has to ride along on the returned listing.
677
+ let { hasChanges, deletedEntries } = diffMailboxListing(listing, storedListing);
678
+
679
+ if (corruptPaths.length) {
680
+ // An unusable stored value is not part of the comparison at all, so it can not be
681
+ // reported as deleted either. Forcing the rewrite is the only thing that clears it.
682
+ //
683
+ // This is also where the corruption is escalated, rather than on the read path in
684
+ // Account.getMailboxListing(): here it is reported once per occurrence with every
685
+ // affected folder in hand, while the read path would report the same condition again
686
+ // on every /v1/account/{account}/mailboxes request until the next sync repairs it.
687
+ this.logger.error({ msg: 'Purging corrupt stored mailbox listing entries', account: this.account, paths: corruptPaths });
688
+ if (logger.notifyError) {
689
+ let corruptErr = new Error('Corrupt stored mailbox listing entries');
690
+ logger.notifyError(corruptErr, { user: this.account, meta: { paths: corruptPaths.join(', ') } });
699
691
  }
692
+ hasChanges = true;
700
693
  }
701
694
 
702
- // Check for deleted mailboxes
703
- const listingPathSet = new Set(listing.map(mailbox => normalizePath(mailbox.path)));
704
- for (let entry of storedListing) {
705
- if (!listingPathSet.has(normalizePath(entry.path))) {
706
- // found deleted!
707
- await this.clearMailboxEntry(entry);
708
- hasChanges = true;
709
- }
695
+ for (let entry of deletedEntries) {
696
+ // found deleted!
697
+ await this.clearMailboxEntry(entry);
710
698
  }
711
699
 
712
700
  // on changes store updated listing
713
701
  if (hasChanges) {
714
- // store
715
- const listingObject = {};
716
- listing.forEach(entry => {
717
- let mailbox = {};
718
- Object.keys(entry).forEach(key => {
719
- if (['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'].includes(key)) {
720
- mailbox[key] = entry[key];
721
- }
722
- });
723
- listingObject[normalizePath(entry.path)] = msgpack.encode(mailbox);
724
- });
725
-
726
- // Atomic update of the mailbox listing
727
- await this.redis.multi().del(this.getMailboxListKey()).hmset(this.getMailboxListKey(), listingObject).exec();
702
+ // Atomic update of the mailbox listing. HMSET refuses an empty hash, and that error
703
+ // aborts the entire MULTI including the DEL, so the write is only queued when there
704
+ // is something to write.
705
+ let listingObject = buildStoredListingObject(listing);
706
+ let updateListing = this.redis.multi().del(this.getMailboxListKey());
707
+ if (Object.keys(listingObject).length) {
708
+ updateListing = updateListing.hmset(this.getMailboxListKey(), listingObject);
709
+ }
710
+ await updateListing.exec();
728
711
  }
729
712
 
730
713
  return listing;
@@ -1501,15 +1484,8 @@ class IMAPClient extends BaseClient {
1501
1484
  let prevImapClient = this.imapClient;
1502
1485
  prevImapClient.disabled = true;
1503
1486
  try {
1504
- prevImapClient.removeAllListeners();
1505
-
1506
- const prevImapErrorHandler = err => {
1507
- this.logger.warn({ msg: 'IMAP connection error', type: 'imapClient', previous: true, account: this.account, err });
1508
- };
1509
-
1510
- prevImapClient.once('error', prevImapErrorHandler);
1487
+ detachImapClient(prevImapClient, this.logger, { type: 'imapClient', previous: true, account: this.account });
1511
1488
  prevImapClient.close();
1512
- prevImapClient.removeListener('error', prevImapErrorHandler);
1513
1489
 
1514
1490
  if (this.commandClient) {
1515
1491
  this.logger.debug({ msg: 'Clearing previous command connection' });
@@ -2585,17 +2561,7 @@ class IMAPClient extends BaseClient {
2585
2561
  */
2586
2562
  async getSpecialUseMailbox(specialUse) {
2587
2563
  let storedListing = await this.redis.hgetallBuffer(this.getMailboxListKey());
2588
- return Object.keys(storedListing || {})
2589
- .map(path => {
2590
- try {
2591
- return msgpack.decode(storedListing[path]);
2592
- } catch (err) {
2593
- // should not happen
2594
- }
2595
- return false;
2596
- })
2597
- .filter(entry => entry)
2598
- .find(entry => entry.specialUse === specialUse);
2564
+ return decodeStoredListing(storedListing).entries.find(entry => entry.specialUse === specialUse);
2599
2565
  }
2600
2566
 
2601
2567
  /**
@@ -6,6 +6,7 @@ const { webhooks: Webhooks } = require('../webhooks');
6
6
  const { getESClient, isDocumentStoreEnabled } = require('../document-store');
7
7
  const { getThread } = require('../threads');
8
8
  const settings = require('../settings');
9
+ const { buildRetentionPolicy } = require('../queue-retention');
9
10
 
10
11
  // Import notification-related constants
11
12
  const { MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, MESSAGE_UPDATED_NOTIFY, EMAIL_BOUNCE_NOTIFY, MAILBOX_DELETED_NOTIFY } = require('../consts');
@@ -227,9 +228,13 @@ class NotificationHandler {
227
228
  * Processes notification with document store sync only (no webhook)
228
229
  * @param {string} event - Event type
229
230
  * @param {Object} payload - Notification payload
231
+ * @param {boolean|number} queueKeep - Whether/how many jobs to keep
230
232
  */
231
- async processDocumentOnly(event, payload) {
232
- await this.documentsQueue.add(event, payload, DOCUMENT_JOB_OPTIONS);
233
+ async processDocumentOnly(event, payload, queueKeep) {
234
+ // Goes through buildJobOptions like every other enqueue. Passing DOCUMENT_JOB_OPTIONS
235
+ // straight through left this path on the hardcoded baseline: it ignored the queueKeep
236
+ // setting and, more importantly, never picked up the failed-entry floor.
237
+ await this.documentsQueue.add(event, payload, this.buildJobOptions(queueKeep).documents);
233
238
  }
234
239
 
235
240
  /**
@@ -238,17 +243,11 @@ class NotificationHandler {
238
243
  * @returns {Object} Job options for notify and documents queues
239
244
  */
240
245
  buildJobOptions(queueKeep) {
241
- const retention = typeof queueKeep === 'number' ? { age: 24 * 3600, count: queueKeep } : queueKeep;
246
+ const retention = buildRetentionPolicy(queueKeep);
242
247
 
243
- const notifyOptions = Object.assign({}, DEFAULT_JOB_OPTIONS, {
244
- removeOnComplete: retention,
245
- removeOnFail: retention
246
- });
248
+ const notifyOptions = Object.assign({}, DEFAULT_JOB_OPTIONS, retention);
247
249
 
248
- const documentOptions = Object.assign({}, DOCUMENT_JOB_OPTIONS, {
249
- removeOnComplete: retention,
250
- removeOnFail: retention
251
- });
250
+ const documentOptions = Object.assign({}, DOCUMENT_JOB_OPTIONS, retention);
252
251
 
253
252
  return {
254
253
  notify: notifyOptions,
@@ -300,7 +299,7 @@ class NotificationHandler {
300
299
  await this.processWebhookOnly(event, payload);
301
300
  } else if (addDocumentQueueJob) {
302
301
  // Document store only
303
- await this.processDocumentOnly(event, payload);
302
+ await this.processDocumentOnly(event, payload, queueKeep);
304
303
  }
305
304
  }
306
305
  }
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ // How a submitted message is put on the wire for Microsoft Graph /sendMail.
4
+ //
5
+ // Extracted from OutlookClient.submitMessage() because it is the part that has to be exactly
6
+ // right and can not be reached from a test otherwise (submitMessage needs a live account, an
7
+ // OAuth app and a Graph endpoint). The encoding is not obvious and Graph is unforgiving about
8
+ // it: the raw branch must post base64 as text/plain (a JSON body is rejected outright), while
9
+ // the structured branch must post a plain object so Graph honours an explicit from address.
10
+
11
+ /**
12
+ * Builds the raw-MIME /sendMail request.
13
+ *
14
+ * @param {Buffer} raw - Complete RFC822 message
15
+ * @param {String} oauth2UserPath - Graph user path ("me" or "users/<id>")
16
+ * @returns {Object} { path, body, options } for OutlookOauth.request()
17
+ */
18
+ function buildRawSendMailRequest(raw, oauth2UserPath) {
19
+ return {
20
+ path: `/${oauth2UserPath}/sendMail`,
21
+ // Graph expects the MIME message base64 encoded in the request body itself
22
+ body: Buffer.from(raw.toString('base64')),
23
+ options: {
24
+ // NOT application/json - Graph rejects a base64 MIME body sent as JSON
25
+ contentType: 'text/plain',
26
+ // sendMail answers 202 Accepted with an empty body
27
+ returnText: true
28
+ }
29
+ };
30
+ }
31
+
32
+ /**
33
+ * Builds the structured (JSON) /sendMail request used when the from address has to be honoured.
34
+ *
35
+ * @param {Object} messagePayload - Graph message object
36
+ * @param {String} oauth2UserPath - Graph user path ("me" or "users/<id>")
37
+ * @returns {Object} { path, body, options } for OutlookOauth.request()
38
+ */
39
+ function buildStructuredSendMailRequest(messagePayload, oauth2UserPath) {
40
+ return {
41
+ path: `/${oauth2UserPath}/sendMail`,
42
+ body: { message: messagePayload },
43
+ // No contentType: an object body is serialized as application/json
44
+ options: { returnText: true }
45
+ };
46
+ }
47
+
48
+ module.exports = { buildRawSendMailRequest, buildStructuredSendMailRequest };
@@ -9,13 +9,14 @@ const getSecret = require('../get-secret');
9
9
  const msgpack = require('msgpack5')();
10
10
  const he = require('he');
11
11
  const { emitChangeEvent, prepareUrl } = require('../tools');
12
- const { mimeHtml } = require('@postalsys/email-text-tools');
12
+ const { messageWebSafeHtml } = require('../web-safe-html');
13
13
  const crypto = require('crypto');
14
14
  const { Gateway } = require('../gateway');
15
15
  const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/mime-types');
16
16
 
17
17
  // Import Graph API module for MS Graph API handling
18
18
  const graphApi = require('./outlook/graph-api');
19
+ const { buildRawSendMailRequest, buildStructuredSendMailRequest } = require('./outlook/send-request');
19
20
 
20
21
  const {
21
22
  REDIS_PREFIX,
@@ -1759,10 +1760,7 @@ class OutlookClient extends BaseClient {
1759
1760
 
1760
1761
  // Generate web-safe HTML if requested
1761
1762
  if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
1762
- formattedMessage.text.html = mimeHtml({
1763
- html: formattedMessage.text.html,
1764
- text: formattedMessage.text.plain
1765
- });
1763
+ formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
1766
1764
 
1767
1765
  formattedMessage.text.webSafe = true;
1768
1766
  }
@@ -2457,16 +2455,8 @@ class OutlookClient extends BaseClient {
2457
2455
  // Send via Graph API using structured message format
2458
2456
  // This ensures the 'from' field is properly respected for shared mailboxes
2459
2457
  // Note: sendMail returns 202 Accepted with empty body
2460
- await this.request(
2461
- `/${this.oauth2UserPath}/sendMail`,
2462
- 'post',
2463
- {
2464
- message: messagePayload
2465
- },
2466
- {
2467
- returnText: true
2468
- }
2469
- );
2458
+ let sendRequest = buildStructuredSendMailRequest(messagePayload, this.oauth2UserPath);
2459
+ await this.request(sendRequest.path, 'post', sendRequest.body, sendRequest.options);
2470
2460
  } catch (err) {
2471
2461
  switch (err.oauthRequest?.status) {
2472
2462
  case 400: {
@@ -2492,10 +2482,8 @@ class OutlookClient extends BaseClient {
2492
2482
  // Use raw MIME format (default)
2493
2483
  // Preserves calendar invites and special MIME types, but ignores from field
2494
2484
  try {
2495
- await this.request(`/${this.oauth2UserPath}/sendMail`, 'post', Buffer.from(raw.toString('base64')), {
2496
- contentType: 'text/plain',
2497
- returnText: true
2498
- });
2485
+ let sendRequest = buildRawSendMailRequest(raw, this.oauth2UserPath);
2486
+ await this.request(sendRequest.path, 'post', sendRequest.body, sendRequest.options);
2499
2487
  } catch (err) {
2500
2488
  switch (err.oauthRequest?.status) {
2501
2489
  case 400: {