emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -18,15 +18,15 @@ const { addTrackers } = require('../add-trackers');
18
18
  const { getRawEmail } = require('../get-raw-email');
19
19
  const { getTemplate } = require('@postalsys/templates');
20
20
  const { deepEqual } = require('assert');
21
- const { arfDetect, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
21
+ const { FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES } = require('../arf-detect');
22
22
  const {
23
23
  isFailedDelivery,
24
- classifyBounce,
25
- bounceNotification,
26
- complaintNotification,
27
24
  embedInlineImages,
28
25
  markWebSafe,
29
- notifyNewMessage
26
+ notifyNewMessage,
27
+ setHiddenContent,
28
+ runArrivalChecks,
29
+ runLlmSummary
30
30
  } = require('./new-message-steps');
31
31
  const { createTransaction } = require('../redis-operations');
32
32
  const { ACCOUNT_STATES } = require('../account/account-state');
@@ -39,7 +39,7 @@ const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS }
39
39
  const { collectCalendarEvents } = require('../calendar-event');
40
40
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../llm-pre-process');
41
41
  const { notificationHeaderFields, narrowHeaders } = require('../utils/header-map');
42
- const { notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../otp');
42
+ const { getMessageOtp, notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../otp');
43
43
  const { mapConcurrent } = require('../utils/map-concurrent');
44
44
  const { oauth2Apps } = require('../oauth2-apps');
45
45
  const { Account } = require('../account');
@@ -253,6 +253,187 @@ function findReferencedCidAttachments(html, attachments) {
253
253
  return cidAttachments;
254
254
  }
255
255
 
256
+ /**
257
+ * Sets the References header of a reply or forward, and In-Reply-To for a reply
258
+ * @param {Object} data - Message data, updated in place
259
+ * @param {Object} referencedMessage - The message being replied to or forwarded
260
+ */
261
+ function applyReferenceHeaders(data, referencedMessage) {
262
+ // Build references header chain
263
+ let references = buildReferences(referencedMessage);
264
+ if (references.length) {
265
+ if (!data.headers) {
266
+ data.headers = {};
267
+ }
268
+ data.headers.references = references.join(' ');
269
+ }
270
+
271
+ // Set In-Reply-To header for replies
272
+ if (['reply', 'reply-all'].includes(data.reference.action) && referencedMessage.messageId) {
273
+ data.headers['in-reply-to'] = referencedMessage.messageId;
274
+ }
275
+ }
276
+
277
+ /**
278
+ * The flag delivering a reply or forward sets on the referenced message: $Forwarded for a forward,
279
+ * \\Answered for a reply. A forward is not an answer, so it does not set \\Answered
280
+ * @param {string} action - reply, reply-all or forward
281
+ * @returns {string}
282
+ */
283
+ function referenceFlag(action) {
284
+ return action === 'forward' ? '$Forwarded' : '\\Answered';
285
+ }
286
+
287
+ /**
288
+ * Whether delivering a reply or forward has to flag the referenced message: only when it does not
289
+ * carry the flag of this action yet, so forwarding a message that was answered still marks it forwarded
290
+ * @param {string} action - reply, reply-all or forward
291
+ * @param {string[]} [flags] - Flags of the referenced message
292
+ * @returns {boolean}
293
+ */
294
+ function needsReferenceFlagUpdate(action, flags) {
295
+ return !(flags || []).includes(referenceFlag(action));
296
+ }
297
+
298
+ /**
299
+ * Subject of a reply or forward: the referenced subject, prefixed with Re: or Fwd: unless it already has one
300
+ * @param {string} [action] - reply, reply-all or forward
301
+ * @param {string} subject - Subject of the referenced message
302
+ * @returns {string}
303
+ */
304
+ function referenceSubject(action, subject) {
305
+ let prefix;
306
+ switch (action) {
307
+ case 'reply':
308
+ case 'reply-all':
309
+ if (!/^Re:/i.test(subject)) {
310
+ prefix = 'Re';
311
+ }
312
+ break;
313
+ case 'forward':
314
+ if (!/^Fwd:/i.test(subject)) {
315
+ prefix = 'Fwd';
316
+ }
317
+ break;
318
+ }
319
+ return `${prefix ? prefix + ': ' : ''}${subject}`;
320
+ }
321
+
322
+ /**
323
+ * Attachments of the referenced message to carry over: all of them for a forward that asks for
324
+ * it, otherwise the ones the quoted html shows inline
325
+ * @param {Object} reference - The reference of the message data
326
+ * @param {Object} referencedMessage - The message being replied to or forwarded
327
+ * @param {Object[]} cidAttachments - Attachments the quoted html links to
328
+ * @returns {Object[]|undefined} A non-empty list, or nothing when there is nothing to carry over
329
+ */
330
+ function selectReferenceAttachments(reference, referencedMessage, cidAttachments) {
331
+ if (reference.action === 'forward' && reference.forwardAttachments && referencedMessage.attachments && referencedMessage.attachments.length) {
332
+ // download all
333
+ return referencedMessage.attachments;
334
+ }
335
+ if (cidAttachments.length) {
336
+ // download referenced attachments
337
+ return cidAttachments;
338
+ }
339
+ }
340
+
341
+ /**
342
+ * The composer options a message to upload is built with, set again after the reference and
343
+ * attachment handling had their turn with `data`
344
+ * @param {Object} data - Message data, updated in place
345
+ */
346
+ function finalizeComposeOptions(data) {
347
+ data.disableUrlAccess = true;
348
+ data.disableFileAccess = true;
349
+ data.boundaryPrefix = MIME_BOUNDARY_PREFIX;
350
+ data.baseBoundary = genBaseBoundary();
351
+ data.newline = '\r\n';
352
+
353
+ if (data.internalDate && !data.date) {
354
+ // Update Date: header as well
355
+ data.date = new Date(data.internalDate);
356
+ }
357
+ }
358
+
359
+ /**
360
+ * The context the template fields of a queued message are rendered with
361
+ * @param {Object} data - Message data
362
+ * @param {Object} accountData - Account data
363
+ * @param {string|null} baseUrl - Service URL
364
+ * @returns {Object} Template context
365
+ */
366
+ function buildTemplateContext(data, accountData, baseUrl) {
367
+ return {
368
+ params: (data.render && data.render.params) || {},
369
+ account: {
370
+ name: accountData.name,
371
+ email: accountData.email
372
+ },
373
+ service: {
374
+ url: baseUrl
375
+ }
376
+ };
377
+ }
378
+
379
+ /**
380
+ * The domain a List-ID is built on: the host of the service URL, or the host name of the
381
+ * machine when the URL names none
382
+ * @param {string} baseUrl - Service URL
383
+ * @returns {string} Lowercase domain
384
+ */
385
+ function listBaseDomain(baseUrl) {
386
+ let baseDomain;
387
+ try {
388
+ baseDomain = (new URL(baseUrl).hostname || '').toLowerCase().trim();
389
+ } catch (err) {
390
+ // ignore error
391
+ }
392
+ return baseDomain || (os.hostname() || '').toLowerCase().trim() || 'localhost';
393
+ }
394
+
395
+ /**
396
+ * The domain of the sender address in its ASCII form, for a generated Message-ID
397
+ * @param {string} [address] - Sender address
398
+ * @param {string} fallback - Domain to use when there is no sender address
399
+ * @returns {string} Domain
400
+ */
401
+ function senderDomain(address, fallback) {
402
+ let fromDomain = (address || '').split('@').pop().trim().toLowerCase() || fallback;
403
+ try {
404
+ fromDomain = punycode.toASCII(fromDomain);
405
+ } catch (err) {
406
+ // ignore
407
+ }
408
+ return fromDomain;
409
+ }
410
+
411
+ /**
412
+ * The reference part of a queue or dry run response: whether the referenced message was found
413
+ * and the thread id the message was asked to join
414
+ * @param {Object} [reference] - The reference of the request
415
+ * @param {Object} [referencedMessage] - The referenced message, when it was found
416
+ * @returns {Object|undefined} Reference response, or nothing when the request referenced neither
417
+ */
418
+ function buildReferenceResponse(reference, referencedMessage) {
419
+ if (!reference || (!reference.message && !reference.threadId)) {
420
+ return undefined;
421
+ }
422
+
423
+ let response = {};
424
+ if (reference.message) {
425
+ response.message = reference.message;
426
+ response.success = referencedMessage ? true : false;
427
+ if (!referencedMessage) {
428
+ response.error = 'Referenced message was not found';
429
+ }
430
+ }
431
+ if (reference.threadId) {
432
+ response.threadId = reference.threadId;
433
+ }
434
+ return response;
435
+ }
436
+
256
437
  /**
257
438
  * A 401 that survives renewing the access token is the provider refusing the account's
258
439
  * credential. Left as it is it reaches the API caller as a 401, which reads as their own
@@ -1087,6 +1268,20 @@ class BaseClient {
1087
1268
  return;
1088
1269
  }
1089
1270
 
1271
+ await this.flagAuthenticationFailure(err, 'TokenGenerationError');
1272
+ }
1273
+
1274
+ /**
1275
+ * Puts an API-backed account into `authenticationError` for a refused credential, marks the
1276
+ * error so the worker does not retry it, and announces it once. Shared by the token refresh
1277
+ * (reportTokenRefreshFailure()) and the profile probe of init() (probeApiAuth()), which only
1278
+ * differ in what they report as the server response code.
1279
+ *
1280
+ * @param {Error} err - The refusal
1281
+ * @param {String} serverResponseCode - Reported in the authenticationError webhook
1282
+ * @returns {Promise<void>}
1283
+ */
1284
+ async flagAuthenticationFailure(err, serverResponseCode) {
1090
1285
  this.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
1091
1286
  await this.setStateVal();
1092
1287
 
@@ -1096,11 +1291,112 @@ class BaseClient {
1096
1291
  err.errorNotified = true;
1097
1292
  await this.notify(false, AUTH_ERROR_NOTIFY, {
1098
1293
  response: err.oauthRequest?.response?.error?.message || err.response,
1099
- serverResponseCode: 'TokenGenerationError'
1294
+ serverResponseCode
1100
1295
  });
1101
1296
  }
1102
1297
  }
1103
1298
 
1299
+ /**
1300
+ * First steps of an API client's init(), after the caller has set `connecting` and stopped its
1301
+ * own timers: stores the state, loads the account and stops when the auth-failure safety net
1302
+ * switched the account off. That check comes before any credential work, because the work that
1303
+ * keeps failing for a parked account is the token refresh.
1304
+ *
1305
+ * @returns {Promise<Boolean>} False when the account must not connect (it is left `unset`)
1306
+ */
1307
+ async beginApiInit() {
1308
+ await this.setStateVal();
1309
+
1310
+ await this.getAccount();
1311
+
1312
+ // The auth-failure safety net switches an account off by setting `imap.disabled`, and
1313
+ // an API-backed account reaches it the same way an IMAP one does - its failures run
1314
+ // through the same setErrorState()
1315
+ if (await this.isSyncDisabled()) {
1316
+ this.logger.info({ msg: 'Skipped connection setup', account: this.account, reason: 'disabled' });
1317
+ this.state = 'unset';
1318
+ await this.setStateVal();
1319
+ return false;
1320
+ }
1321
+
1322
+ return true;
1323
+ }
1324
+
1325
+ /**
1326
+ * Whether an API account holds the scope to send but not to read, logged for diagnostics. The
1327
+ * client maps the granted scopes to `{ hasSendScope, hasReadScope }` in its checkScopes()
1328
+ *
1329
+ * @param {Object} accountData - Loaded account data
1330
+ * @returns {Boolean} True for a send-only account
1331
+ */
1332
+ computeSendOnly(accountData) {
1333
+ const scopes = accountData.oauth2?.accessToken?.scope || accountData.oauth2?.scope || [];
1334
+ const { hasSendScope, hasReadScope } = this.checkScopes(scopes);
1335
+ const isSendOnly = hasSendScope && !hasReadScope;
1336
+
1337
+ this.logger.debug({
1338
+ msg: 'Account scopes loaded',
1339
+ account: this.account,
1340
+ scopes,
1341
+ hasSendScope,
1342
+ hasReadScope,
1343
+ isSendOnly
1344
+ });
1345
+
1346
+ return isSendOnly;
1347
+ }
1348
+
1349
+ /**
1350
+ * Runs the request init() verifies the credential with. A refusal is an authentication error;
1351
+ * a transient failure is rethrown unflagged, so the worker retries init() instead of reporting
1352
+ * an authentication error only re-authorization could clear.
1353
+ *
1354
+ * @param {Function} requestFn - Performs the profile request
1355
+ * @returns {Promise<*>} The response
1356
+ */
1357
+ async probeApiAuth(requestFn) {
1358
+ try {
1359
+ return await requestFn();
1360
+ } catch (err) {
1361
+ if (!isTransientCredentialError(err)) {
1362
+ await this.flagAuthenticationFailure(err, 'ApiRequestError');
1363
+ }
1364
+ throw err;
1365
+ }
1366
+ }
1367
+
1368
+ /**
1369
+ * The partial OAuth2 update that stores a changed login. Merges into the loaded `auth` object
1370
+ * itself, as init() always did, so the account data in hand already carries the new user.
1371
+ *
1372
+ * @param {Object} auth - The loaded `oauth2.auth` object, if any
1373
+ * @param {String} user - The new username
1374
+ * @returns {Object} Value for `updates.oauth2`
1375
+ */
1376
+ oauthUserUpdate(auth, user) {
1377
+ return {
1378
+ partial: true,
1379
+ auth: Object.assign(auth || {}, { user })
1380
+ };
1381
+ }
1382
+
1383
+ /**
1384
+ * Last steps of an API client's init(): announces a first login or a recovery, then flips the
1385
+ * account to `connected`. The announcement has to come first, see notifyAuthenticationSuccess()
1386
+ * (the Graph client used to run it after the flip and never announced a first login at all).
1387
+ *
1388
+ * @param {String} user - Username the login used, for the webhook payload
1389
+ * @returns {Promise<void>}
1390
+ */
1391
+ async finishApiInit(user) {
1392
+ await this.notifyAuthenticationSuccess(user);
1393
+
1394
+ this.state = 'connected';
1395
+ await this.setStateVal();
1396
+
1397
+ await emitChangeEvent(this.logger, this.account, 'state', this.state);
1398
+ }
1399
+
1104
1400
  /**
1105
1401
  * Sets error state and manages error tracking/notifications
1106
1402
  * Implements logic to disable IMAP after repeated authentication failures
@@ -1911,55 +2207,42 @@ class BaseClient {
1911
2207
  }
1912
2208
 
1913
2209
  /**
1914
- * Prepares raw email message for sending/storing
1915
- * Handles references, inline content, and attachments
2210
+ * Refuses a reply or forward on a send-only account, which has no mailbox to read the
2211
+ * referenced message from
1916
2212
  * @param {Object} data - Message data
1917
- * @param {Object} options - Processing options
1918
- * @param {Object} connectionOptions - Connection options
1919
- * @returns {Object} Raw message and metadata
2213
+ * @param {Object} accountData - Account data
2214
+ * @throws {Error} ReferenceNotSupported (400)
1920
2215
  */
1921
- async prepareRawMessage(data, options, connectionOptions) {
1922
- options = options || {};
1923
-
1924
- // Configure message defaults
1925
- data.disableFileAccess = true;
1926
- data.disableUrlAccess = true;
1927
- data.boundaryPrefix = MIME_BOUNDARY_PREFIX;
1928
- data.baseBoundary = genBaseBoundary();
1929
-
1930
- // convert data uri images to attachments
1931
- convertDataUrisToAttachments(data);
1932
-
1933
- let accountData = await this.accountObject.loadAccountData();
1934
-
1935
- // Check if send-only account is trying to use reference.action
1936
- if (data.reference && data.reference.message && data.reference.action) {
1937
- let app;
1938
- if (accountData.oauth2 && accountData.oauth2.provider) {
1939
- try {
1940
- app = await this.accountObject.getOauth2App();
1941
- } catch (err) {
1942
- // ignore
1943
- }
1944
- }
2216
+ async assertReferenceAllowed(data, accountData) {
2217
+ if (!data.reference || !data.reference.message || !data.reference.action) {
2218
+ return;
2219
+ }
1945
2220
 
1946
- if (this.accountObject.isSendOnlyAccount(accountData, app)) {
1947
- let err = new Error('Reference actions (reply, forward) are not supported for send-only accounts');
1948
- err.code = 'ReferenceNotSupported';
1949
- err.statusCode = 400;
1950
- throw err;
2221
+ let app;
2222
+ if (accountData.oauth2 && accountData.oauth2.provider) {
2223
+ try {
2224
+ app = await this.accountObject.getOauth2App();
2225
+ } catch (err) {
2226
+ // ignore
1951
2227
  }
1952
2228
  }
1953
2229
 
1954
- // Set default from address for reference actions
1955
- if (!data.from && data.reference?.action) {
1956
- data.from = {
1957
- name: accountData.name,
1958
- address: accountData.email
1959
- };
2230
+ if (this.accountObject.isSendOnlyAccount(accountData, app)) {
2231
+ let err = new Error('Reference actions (reply, forward) are not supported for send-only accounts');
2232
+ err.code = 'ReferenceNotSupported';
2233
+ err.statusCode = 400;
2234
+ throw err;
1960
2235
  }
2236
+ }
1961
2237
 
1962
- // Configure locale and timezone for inline content
2238
+ /**
2239
+ * Locale and time zone for the quoted content of a reply or forward: the request's, then the
2240
+ * account's, then the instance setting. Both are removed from `data`, they are not message fields
2241
+ * @param {Object} data - Message data, updated in place
2242
+ * @param {Object} accountData - Account data
2243
+ * @returns {Object} { locale, tz }
2244
+ */
2245
+ async resolveInlineOptions(data, accountData) {
1963
2246
  let inlineOptions = {
1964
2247
  locale: data.locale || accountData.locale || (await settings.get('locale')),
1965
2248
  tz: data.tz || accountData.tz || (await settings.get('timezone'))
@@ -1968,254 +2251,339 @@ class BaseClient {
1968
2251
  delete data.locale;
1969
2252
  delete data.tz;
1970
2253
 
2254
+ return inlineOptions;
2255
+ }
2256
+
2257
+ /**
2258
+ * Fetches the message a reply or forward refers to, retrying transient failures
2259
+ * @param {Object} data - Message data with `reference.message` set
2260
+ * @param {Object} connectionOptions - Connection options
2261
+ * @returns {Object|null} The referenced message, or nothing when it is missing and `ignoreMissing` is set
2262
+ * @throws {Error} ReferenceNotFound (404) when it is missing otherwise, or the fetch error itself
2263
+ */
2264
+ async fetchReferencedMessage(data, connectionOptions) {
1971
2265
  let referencedMessage;
1972
2266
 
1973
- // Resolve reference and update reference/in-reply-to headers
1974
- if (data.reference && data.reference.message) {
1975
- // Fetch from IMAP/API with retry logic for transient errors
1976
- let extendedData = data.reference.inline || data.reference.forwardAttachments;
2267
+ // Fetch from IMAP/API with retry logic for transient errors
2268
+ let extendedData = data.reference.inline || data.reference.forwardAttachments;
1977
2269
 
1978
- try {
1979
- referencedMessage = await retryOnTransientError(
1980
- async () =>
1981
- await this.getMessage(
1982
- data.reference.message,
1983
- {
1984
- fields: !extendedData
1985
- ? {
1986
- uid: true,
1987
- flags: true,
1988
- envelope: true,
1989
- headers: ['references']
1990
- }
1991
- : false,
1992
- textType: extendedData ? '*' : false
1993
- },
1994
- connectionOptions
1995
- ),
1996
- {
1997
- maxAttempts: 3,
1998
- baseDelay: 1000,
1999
- logger: this.logger
2000
- }
2001
- );
2002
- } catch (err) {
2003
- // Check if this is a transient error that exhausted retries
2004
- const isTransient = isTransientError(err);
2005
-
2006
- if (isTransient && data.reference.ignoreMissing) {
2007
- // Transient error but ignoreMissing is true - log and continue without reference
2008
- this.logger.warn({
2009
- msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
2010
- messageId: data.reference.message,
2011
- err,
2012
- statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
2013
- });
2014
- referencedMessage = null;
2015
- } else if (!isTransient && err.statusCode === 404) {
2016
- // Permanent 404 error - respect ignoreMissing
2017
- if (!data.reference.ignoreMissing) {
2018
- let error = new Error('Referenced message was not found');
2019
- error.code = 'ReferenceNotFound';
2020
- error.statusCode = 404;
2021
- throw error;
2022
- }
2023
- referencedMessage = null;
2024
- } else {
2025
- // Either transient error with ignoreMissing=false, or other permanent error
2026
- throw err;
2270
+ try {
2271
+ referencedMessage = await retryOnTransientError(
2272
+ async () =>
2273
+ await this.getMessage(
2274
+ data.reference.message,
2275
+ {
2276
+ fields: !extendedData
2277
+ ? {
2278
+ uid: true,
2279
+ flags: true,
2280
+ envelope: true,
2281
+ headers: ['references']
2282
+ }
2283
+ : false,
2284
+ textType: extendedData ? '*' : false
2285
+ },
2286
+ connectionOptions
2287
+ ),
2288
+ {
2289
+ maxAttempts: 3,
2290
+ baseDelay: 1000,
2291
+ logger: this.logger
2027
2292
  }
2028
- }
2293
+ );
2294
+ } catch (err) {
2295
+ // Check if this is a transient error that exhausted retries
2296
+ const isTransient = isTransientError(err);
2029
2297
 
2030
- if (!referencedMessage && !data.reference.ignoreMissing) {
2031
- let err = new Error('Referenced message was not found');
2032
- err.code = 'ReferenceNotFound';
2033
- err.statusCode = 404;
2298
+ if (isTransient && data.reference.ignoreMissing) {
2299
+ // Transient error but ignoreMissing is true - log and continue without reference
2300
+ this.logger.warn({
2301
+ msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
2302
+ messageId: data.reference.message,
2303
+ err,
2304
+ statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
2305
+ });
2306
+ referencedMessage = null;
2307
+ } else if (!isTransient && err.statusCode === 404) {
2308
+ // Permanent 404 error - the check below respects ignoreMissing
2309
+ referencedMessage = null;
2310
+ } else {
2311
+ // Either transient error with ignoreMissing=false, or other permanent error
2034
2312
  throw err;
2035
2313
  }
2314
+ }
2036
2315
 
2037
- if (referencedMessage) {
2038
- // Verify Message-ID if specified
2039
- if (data.reference.messageId && data.reference.messageId !== referencedMessage.messageId) {
2040
- let err = new Error('The referenced message was found, but its Message-ID does not match the expected value');
2041
- err.code = 'MessageNotFound';
2042
- err.statusCode = 404;
2043
- throw err;
2044
- }
2316
+ if (!referencedMessage && !data.reference.ignoreMissing) {
2317
+ let error = new Error('Referenced message was not found');
2318
+ error.code = 'ReferenceNotFound';
2319
+ error.statusCode = 404;
2320
+ throw error;
2321
+ }
2045
2322
 
2046
- // Build references header chain
2047
- let references = buildReferences(referencedMessage);
2048
- if (references.length) {
2049
- if (!data.headers) {
2050
- data.headers = {};
2051
- }
2052
- data.headers.references = references.join(' ');
2053
- }
2323
+ return referencedMessage;
2324
+ }
2054
2325
 
2055
- // Set In-Reply-To header for replies
2056
- if (['reply', 'reply-all'].includes(data.reference.action) && referencedMessage.messageId) {
2057
- data.headers['in-reply-to'] = referencedMessage.messageId;
2058
- }
2326
+ /**
2327
+ * Resolves the message a reply or forward refers to and applies it to the new message: threading
2328
+ * headers, subject, quoted content, recipients and the attachments to carry over. Shared by
2329
+ * prepareRawMessage() (upload) and queueMessageEntry() (delivery), which differ only in the options.
2330
+ * @param {Object} data - Message data with `reference.message` set, updated in place
2331
+ * @param {Object} inlineOptions - { locale, tz } for the quoted content
2332
+ * @param {Object} connectionOptions - Connection options
2333
+ * @param {Object} [opts]
2334
+ * @param {boolean} [opts.checkConnection] - Check the IMAP connection before fetching
2335
+ * @param {boolean} [opts.trackUpdate] - Set `reference.update` when the referenced message lacks the flag the delivery sets
2336
+ * @param {boolean} [opts.copyThreadId] - Copy the referenced thread id to `reference.threadId` unless the caller set one
2337
+ * @returns {Object|null} The referenced message
2338
+ */
2339
+ async resolveReference(data, inlineOptions, connectionOptions, opts) {
2340
+ opts = opts || {};
2059
2341
 
2060
- // Generate subject with appropriate prefix
2061
- if (!data.subject && referencedMessage.subject) {
2062
- let subject = referencedMessage.subject;
2063
- let prefix;
2064
- switch (data.reference.action) {
2065
- case 'reply':
2066
- case 'reply-all':
2067
- if (!/^Re:/i.test(subject)) {
2068
- prefix = 'Re';
2069
- }
2070
- break;
2071
- case 'forward':
2072
- if (!/^Fwd:/i.test(subject)) {
2073
- prefix = 'Fwd';
2074
- }
2075
- break;
2076
- }
2077
- data.subject = `${prefix ? prefix + ': ' : ''}${subject}`;
2078
- }
2342
+ if (opts.checkConnection) {
2343
+ this.checkIMAPConnection(connectionOptions);
2344
+ }
2079
2345
 
2080
- let cidAttachments = [];
2346
+ let referencedMessage = await this.fetchReferencedMessage(data, connectionOptions);
2347
+ if (!referencedMessage) {
2348
+ return referencedMessage;
2349
+ }
2081
2350
 
2082
- // Process inline content for replies/forwards
2083
- if (data.reference.inline) {
2084
- let inlineMessageData = {
2085
- text: referencedMessage.text && referencedMessage.text.plain,
2086
- html: referencedMessage.text && referencedMessage.text.html
2087
- };
2351
+ // Verify Message-ID if specified
2352
+ if (data.reference.messageId && data.reference.messageId !== referencedMessage.messageId) {
2353
+ let err = new Error('The referenced message was found, but its Message-ID does not match the expected value');
2354
+ err.code = 'MessageNotFound';
2355
+ err.statusCode = 404;
2356
+ throw err;
2357
+ }
2088
2358
 
2089
- for (let key of ['from', 'to', 'cc', 'bcc', 'date', 'subject']) {
2090
- inlineMessageData[key] = referencedMessage[key];
2091
- }
2359
+ applyReferenceHeaders(data, referencedMessage);
2092
2360
 
2093
- if (inlineMessageData.html) {
2094
- // Find inline attachments referenced in HTML
2095
- cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
2361
+ // Check if we need to update flags on referenced message
2362
+ if (opts.trackUpdate && needsReferenceFlagUpdate(data.reference.action, referencedMessage.flags)) {
2363
+ data.reference.update = true;
2364
+ }
2096
2365
 
2097
- try {
2098
- let html = data.html;
2099
- if (!(html || '').toString().trim() && data.text) {
2100
- html = textToHtml(data.text); // convert text to html
2101
- }
2366
+ // Preserve thread ID, but let a caller-supplied threadId win
2367
+ if (opts.copyThreadId && !data.reference.threadId && referencedMessage.threadId) {
2368
+ data.reference.threadId = referencedMessage.threadId;
2369
+ }
2102
2370
 
2103
- data.html = inlineHtml(data.reference.action, html, inlineMessageData, inlineOptions);
2104
- } catch (err) {
2105
- this.logger.error({ msg: 'Failed to generate inline HTML content', err });
2106
- }
2107
- }
2371
+ // Generate subject with appropriate prefix
2372
+ if (!data.subject && referencedMessage.subject) {
2373
+ data.subject = referenceSubject(data.reference.action, referencedMessage.subject);
2374
+ }
2108
2375
 
2109
- if (data.text) {
2110
- try {
2111
- data.text = inlineText(data.reference.action, data.text, inlineMessageData, inlineOptions);
2112
- } catch (err) {
2113
- this.logger.error({ msg: 'Failed to generate inline text content', err });
2114
- }
2115
- }
2116
- }
2376
+ // Process inline content for replies/forwards
2377
+ let cidAttachments = data.reference.inline ? this.applyInlineReference(data, referencedMessage, inlineOptions) : [];
2117
2378
 
2118
- // Set the recipients of a reply or reply-all
2119
- applyReferenceRecipients(data, referencedMessage);
2120
-
2121
- // Determine which attachments to include
2122
- let attachmentsToDownload;
2123
-
2124
- if (
2125
- data.reference.action === 'forward' &&
2126
- data.reference.forwardAttachments &&
2127
- referencedMessage.attachments &&
2128
- referencedMessage.attachments.length
2129
- ) {
2130
- // download all
2131
- attachmentsToDownload = referencedMessage.attachments;
2132
- } else if (cidAttachments.length) {
2133
- // download referenced attachments
2134
- attachmentsToDownload = cidAttachments;
2135
- }
2379
+ // Set the recipients of a reply or reply-all
2380
+ applyReferenceRecipients(data, referencedMessage);
2136
2381
 
2137
- // Download and attach referenced attachments
2138
- if (attachmentsToDownload && attachmentsToDownload.length) {
2139
- this.checkIMAPConnection(connectionOptions);
2382
+ // Download and attach referenced attachments
2383
+ let attachmentsToDownload = selectReferenceAttachments(data.reference, referencedMessage, cidAttachments);
2384
+ if (attachmentsToDownload) {
2385
+ await this.attachReferencedAttachments(data, attachmentsToDownload, connectionOptions);
2386
+ }
2140
2387
 
2141
- this.logger.debug({
2142
- msg: 'Fetching attachments from the referenced email',
2143
- attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
2144
- });
2388
+ return referencedMessage;
2389
+ }
2145
2390
 
2146
- // fetch and add attachments to the message
2147
- if (!data.attachments) {
2148
- data.attachments = [];
2149
- }
2150
- for (let attachment of attachmentsToDownload) {
2151
- let content;
2152
- if (attachment.content) {
2153
- // use local cache
2154
- content = Buffer.from(attachment.content, 'base64');
2155
- this.logger.trace({ msg: 'Using cached email content', attachment: attachment.id, size: content.length });
2156
- } else {
2157
- // fetch from IMAP
2158
- content = await this.getAttachmentContent(
2159
- attachment.id,
2160
- {
2161
- chunkSize: Math.max(DOWNLOAD_CHUNK_SIZE, 2 * 1024 * 1024),
2162
- contentOnly: true
2163
- },
2164
- connectionOptions
2165
- );
2166
- }
2167
- if (!content) {
2168
- // skip missing?
2169
- continue;
2170
- }
2171
- data.attachments.push({
2172
- filename: attachment.filename,
2173
- content,
2174
- contentType: attachment.contentType,
2175
- contentDisposition: attachment.inline ? 'inline' : 'attachment',
2176
- cid: attachment.contentId || null
2177
- });
2178
- }
2179
- }
2180
- }
2391
+ /**
2392
+ * Quotes the referenced message in the html and text content of a reply or forward
2393
+ * @param {Object} data - Message data, updated in place
2394
+ * @param {Object} referencedMessage - The message being quoted, fetched with its text
2395
+ * @param {Object} inlineOptions - { locale, tz }
2396
+ * @returns {Object[]} Attachments of the referenced message that the quoted html shows inline
2397
+ */
2398
+ applyInlineReference(data, referencedMessage, inlineOptions) {
2399
+ let cidAttachments = [];
2400
+
2401
+ let inlineMessageData = {
2402
+ text: referencedMessage.text && referencedMessage.text.plain,
2403
+ html: referencedMessage.text && referencedMessage.text.html
2404
+ };
2405
+
2406
+ for (let key of ['from', 'to', 'cc', 'bcc', 'date', 'subject']) {
2407
+ inlineMessageData[key] = referencedMessage[key];
2181
2408
  }
2182
2409
 
2183
- // resolve referenced attachments
2184
- for (let attachment of data.attachments || []) {
2185
- if (attachment.reference && !attachment.content) {
2186
- this.checkIMAPConnection(connectionOptions);
2410
+ // The caller's own content, before the quote is added to either part
2411
+ let ownText = typeof data.text === 'string' ? data.text : '';
2412
+ let ownHtml = (data.html || '').toString();
2187
2413
 
2188
- let content = await this.getAttachmentContent(
2189
- attachment.reference,
2190
- {
2191
- chunkSize: Math.max(DOWNLOAD_CHUNK_SIZE, 2 * 1024 * 1024),
2192
- contentOnly: true
2193
- },
2194
- connectionOptions
2195
- );
2196
- if (!content) {
2197
- let error = new Error('Referenced attachment was not found');
2198
- error.code = 'ReferenceNotFound';
2199
- error.statusCode = 404;
2200
- throw error;
2414
+ // The original goes into the html part when it has html of its own, or when the caller writes
2415
+ // html: an original with a text part alone is quoted there from its text, as it is in the text
2416
+ // part. A message sent as text alone stays text alone.
2417
+ if (inlineMessageData.html || (inlineMessageData.text && ownHtml.trim())) {
2418
+ // Find inline attachments referenced in HTML
2419
+ if (inlineMessageData.html) {
2420
+ cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
2421
+ }
2422
+
2423
+ try {
2424
+ let html = data.html;
2425
+ if (!(html || '').toString().trim() && data.text) {
2426
+ html = textToHtml(data.text); // convert text to html
2201
2427
  }
2202
2428
 
2203
- attachment.content = content;
2429
+ data.html = inlineHtml(data.reference.action, html, inlineMessageData, inlineOptions);
2430
+ } catch (err) {
2431
+ this.logger.error({ msg: 'Failed to generate inline HTML content', err });
2204
2432
  }
2205
2433
  }
2206
2434
 
2207
- // Final message configuration
2208
- data.disableUrlAccess = true;
2435
+ // The quote goes into the text part whatever the caller wrote. Without text of its own the
2436
+ // part is built from the caller's html, or carries the quote alone (a forward is often sent
2437
+ // with no note): quoting only a non-empty text left such a message with no text part, or,
2438
+ // on the draft upload path, a text part missing the note its html carried.
2439
+ if (!ownText.trim() && ownHtml.trim()) {
2440
+ try {
2441
+ ownText = htmlToText(ownHtml);
2442
+ } catch (err) {
2443
+ this.logger.error({ msg: 'Failed to convert html content to text', err });
2444
+ }
2445
+ }
2446
+
2447
+ try {
2448
+ data.text = inlineText(data.reference.action, ownText, inlineMessageData, inlineOptions);
2449
+ } catch (err) {
2450
+ this.logger.error({ msg: 'Failed to generate inline text content', err });
2451
+ }
2452
+
2453
+ return cidAttachments;
2454
+ }
2455
+
2456
+ /**
2457
+ * Adds attachments of the referenced message to the new message, from the cached content when
2458
+ * the fetch carried it and downloaded otherwise. One that downloads empty is skipped
2459
+ * @param {Object} data - Message data, updated in place
2460
+ * @param {Object[]} attachments - Attachment entries of the referenced message
2461
+ * @param {Object} connectionOptions - Connection options
2462
+ */
2463
+ async attachReferencedAttachments(data, attachments, connectionOptions) {
2464
+ this.checkIMAPConnection(connectionOptions);
2465
+
2466
+ this.logger.debug({
2467
+ msg: 'Fetching attachments from the referenced email',
2468
+ attachments: attachments.map(a => ({ id: a.id, hasContent: !!a.content }))
2469
+ });
2470
+
2471
+ // fetch and add attachments to the message
2472
+ if (!data.attachments) {
2473
+ data.attachments = [];
2474
+ }
2475
+ for (let attachment of attachments) {
2476
+ let content;
2477
+ if (attachment.content) {
2478
+ // use local cache
2479
+ content = Buffer.from(attachment.content, 'base64');
2480
+ this.logger.trace({ msg: 'Using cached email content', attachment: attachment.id, size: content.length });
2481
+ } else {
2482
+ // fetch from IMAP
2483
+ content = await this.getAttachmentContent(
2484
+ attachment.id,
2485
+ {
2486
+ chunkSize: Math.max(DOWNLOAD_CHUNK_SIZE, 2 * 1024 * 1024),
2487
+ contentOnly: true
2488
+ },
2489
+ connectionOptions
2490
+ );
2491
+ }
2492
+ if (!content) {
2493
+ // skip missing?
2494
+ continue;
2495
+ }
2496
+ data.attachments.push({
2497
+ filename: attachment.filename,
2498
+ content,
2499
+ contentType: attachment.contentType,
2500
+ contentDisposition: attachment.inline ? 'inline' : 'attachment',
2501
+ cid: attachment.contentId || null
2502
+ });
2503
+ }
2504
+ }
2505
+
2506
+ /**
2507
+ * Downloads the content of every attachment the request refers to by attachment id
2508
+ * @param {Object} data - Message data, its attachments updated in place
2509
+ * @param {Object} connectionOptions - Connection options
2510
+ * @throws {Error} ReferenceNotFound (404) when a referenced attachment is gone
2511
+ */
2512
+ async resolveAttachmentReferences(data, connectionOptions) {
2513
+ for (let attachment of data.attachments || []) {
2514
+ if (attachment.reference && !attachment.content) {
2515
+ this.checkIMAPConnection(connectionOptions);
2516
+
2517
+ let content = await this.getAttachmentContent(
2518
+ attachment.reference,
2519
+ {
2520
+ chunkSize: Math.max(DOWNLOAD_CHUNK_SIZE, 2 * 1024 * 1024),
2521
+ contentOnly: true
2522
+ },
2523
+ connectionOptions
2524
+ );
2525
+
2526
+ if (!content) {
2527
+ let error = new Error('Referenced attachment was not found');
2528
+ error.code = 'ReferenceNotFound';
2529
+ error.statusCode = 404;
2530
+ throw error;
2531
+ }
2532
+
2533
+ attachment.content = content;
2534
+ }
2535
+ }
2536
+ }
2537
+
2538
+ /**
2539
+ * Prepares raw email message for sending/storing
2540
+ * Handles references, inline content, and attachments
2541
+ * @param {Object} data - Message data
2542
+ * @param {Object} options - Processing options
2543
+ * @param {Object} connectionOptions - Connection options
2544
+ * @returns {Object} Raw message and metadata
2545
+ */
2546
+ async prepareRawMessage(data, options, connectionOptions) {
2547
+ options = options || {};
2548
+
2549
+ // Configure message defaults
2209
2550
  data.disableFileAccess = true;
2551
+ data.disableUrlAccess = true;
2210
2552
  data.boundaryPrefix = MIME_BOUNDARY_PREFIX;
2211
2553
  data.baseBoundary = genBaseBoundary();
2212
- data.newline = '\r\n';
2213
2554
 
2214
- if (data.internalDate && !data.date) {
2215
- // Update Date: header as well
2216
- data.date = new Date(data.internalDate);
2555
+ // convert data uri images to attachments
2556
+ convertDataUrisToAttachments(data);
2557
+
2558
+ let accountData = await this.accountObject.loadAccountData();
2559
+
2560
+ // Check if send-only account is trying to use reference.action
2561
+ await this.assertReferenceAllowed(data, accountData);
2562
+
2563
+ // Set default from address for reference actions
2564
+ if (!data.from && data.reference?.action) {
2565
+ data.from = {
2566
+ name: accountData.name,
2567
+ address: accountData.email
2568
+ };
2217
2569
  }
2218
2570
 
2571
+ // Configure locale and timezone for inline content
2572
+ let inlineOptions = await this.resolveInlineOptions(data, accountData);
2573
+
2574
+ let referencedMessage;
2575
+
2576
+ // Resolve reference and update reference/in-reply-to headers
2577
+ if (data.reference && data.reference.message) {
2578
+ referencedMessage = await this.resolveReference(data, inlineOptions, connectionOptions);
2579
+ }
2580
+
2581
+ // resolve referenced attachments
2582
+ await this.resolveAttachmentReferences(data, connectionOptions);
2583
+
2584
+ // Final message configuration
2585
+ finalizeComposeOptions(data);
2586
+
2219
2587
  // Generate raw MIME message
2220
2588
  let { raw, emailObject, messageId } = await getRawEmail(data, null, options);
2221
2589
 
@@ -2242,17 +2610,7 @@ class BaseClient {
2242
2610
 
2243
2611
  let baseUrl = data.baseUrl || (await settings.get('serviceUrl')) || null;
2244
2612
 
2245
- // Build template context
2246
- let context = {
2247
- params: (data.render && data.render.params) || {},
2248
- account: {
2249
- name: accountData.name,
2250
- email: accountData.email
2251
- },
2252
- service: {
2253
- url: baseUrl
2254
- }
2255
- };
2613
+ let context = buildTemplateContext(data, accountData, baseUrl);
2256
2614
 
2257
2615
  // Set default from address
2258
2616
  if (!data.from) {
@@ -2263,93 +2621,18 @@ class BaseClient {
2263
2621
  };
2264
2622
  }
2265
2623
 
2266
- // Handle list unsubscribe headers
2267
- if (baseUrl && data.listId && data.to && data.to.length === 1 && data.to[0].address) {
2268
- // check if not already blocked
2269
-
2270
- let blockData;
2271
-
2272
- try {
2273
- blockData = await this.redis.hget(`${REDIS_PREFIX}lists:unsub:entries:${data.listId}`, data.to[0].address.toLowerCase().trim());
2274
- blockData = JSON.parse(blockData);
2275
- } catch (err) {
2276
- blockData = false;
2277
- }
2278
-
2279
- // Skip if recipient has unsubscribed
2280
- if (blockData) {
2281
- return {
2282
- responseValue: {
2283
- skipped: {
2284
- reason: blockData.reason,
2285
- listId: data.listId
2286
- }
2287
- }
2288
- };
2289
- }
2290
-
2291
- if (!data.headers) {
2292
- data.headers = {};
2293
- }
2294
-
2295
- // Generate List headers
2296
- let baseDomain;
2297
- try {
2298
- baseDomain = (new URL(baseUrl).hostname || '').toLowerCase().trim();
2299
- } catch (err) {
2300
- // ignore error
2301
- }
2302
- baseDomain = baseDomain || (os.hostname() || '').toLowerCase().trim() || 'localhost';
2303
-
2304
- if (baseDomain) {
2305
- const serviceSecret = await getServiceSecret();
2306
-
2307
- let fromDomain = ((data.from && data.from.address) || '').split('@').pop().trim().toLowerCase() || baseDomain;
2308
- try {
2309
- fromDomain = punycode.toASCII(fromDomain);
2310
- } catch (err) {
2311
- // ignore
2312
- }
2313
-
2314
- data.headers['List-ID'] = `<${data.listId}.${baseDomain}>`;
2315
-
2316
- if (!data.messageId) {
2317
- data.messageId = `<${uuid()}@${fromDomain}>`;
2318
- }
2319
-
2320
- // Create signed unsubscribe URL
2321
- let unsubscribeUrl = buildUnsubscribeUrl(serviceSecret, baseUrl, {
2322
- account: accountData.account,
2323
- list: data.listId,
2324
- recipient: data.to[0].address,
2325
- messageId: data.messageId
2326
- });
2327
-
2328
- context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl });
2329
-
2330
- // Add RFC 8058 compliant unsubscribe headers
2331
- data.headers['List-Unsubscribe'] = `<${context.rcpt.unsubscribeUrl}>`;
2332
- data.headers['List-Unsubscribe-Post'] = 'List-Unsubscribe=One-Click';
2333
- }
2334
- }
2335
-
2336
- // Render templates
2337
- for (let key of ['subject', 'html', 'text', 'previewText']) {
2338
- if (data.render || data.listId) {
2339
- data[key] = this.render(data[key], context, key, data.render && data.render.format);
2340
- }
2624
+ // The steps below update data in place, in this order: the list headers set the
2625
+ // Message-ID the unsubscribe URL signs and the recipient the templates render, and the
2626
+ // text part is derived from the rendered html
2627
+ let skipped = await this.applyListHeaders(data, accountData, baseUrl, context);
2628
+ if (skipped) {
2629
+ return skipped;
2341
2630
  }
2342
2631
 
2343
- delete data.render;
2632
+ this.renderTemplateFields(data, context);
2344
2633
 
2345
2634
  // Configure locale and timezone for inline content
2346
- let inlineOptions = {
2347
- locale: data.locale || accountData.locale || (await settings.get('locale')),
2348
- tz: data.tz || accountData.tz || (await settings.get('timezone'))
2349
- };
2350
-
2351
- delete data.locale;
2352
- delete data.tz;
2635
+ let inlineOptions = await this.resolveInlineOptions(data, accountData);
2353
2636
 
2354
2637
  // Generate plain text from HTML if needed
2355
2638
  if (data.html && !data.text) {
@@ -2364,251 +2647,15 @@ class BaseClient {
2364
2647
 
2365
2648
  // Resolve reference and update reference/in-reply-to headers
2366
2649
  if (data.reference && data.reference.message) {
2367
- // Fetch from IMAP/API with retry logic for transient errors
2368
- this.checkIMAPConnection(connectionOptions);
2369
-
2370
- let extendedData = data.reference.inline || data.reference.forwardAttachments;
2371
-
2372
- try {
2373
- referencedMessage = await retryOnTransientError(
2374
- async () =>
2375
- await this.getMessage(
2376
- data.reference.message,
2377
- {
2378
- fields: !extendedData
2379
- ? {
2380
- uid: true,
2381
- flags: true,
2382
- envelope: true,
2383
- headers: ['references']
2384
- }
2385
- : false,
2386
- textType: extendedData ? '*' : false
2387
- },
2388
- connectionOptions
2389
- ),
2390
- {
2391
- maxAttempts: 3,
2392
- baseDelay: 1000,
2393
- logger: this.logger
2394
- }
2395
- );
2396
- } catch (err) {
2397
- // Check if this is a transient error that exhausted retries
2398
- const isTransient = isTransientError(err);
2399
-
2400
- if (isTransient && data.reference.ignoreMissing) {
2401
- // Transient error but ignoreMissing is true - log and continue without reference
2402
- this.logger.warn({
2403
- msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
2404
- messageId: data.reference.message,
2405
- err,
2406
- statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
2407
- });
2408
- referencedMessage = null;
2409
- } else if (!isTransient && err.statusCode === 404) {
2410
- // Permanent 404 error - respect ignoreMissing
2411
- if (!data.reference.ignoreMissing) {
2412
- let error = new Error('Referenced message was not found');
2413
- error.code = 'ReferenceNotFound';
2414
- error.statusCode = 404;
2415
- throw error;
2416
- }
2417
- referencedMessage = null;
2418
- } else {
2419
- // Either transient error with ignoreMissing=false, or other permanent error
2420
- throw err;
2421
- }
2422
- }
2423
-
2424
- if (!referencedMessage && !data.reference.ignoreMissing) {
2425
- let error = new Error('Referenced message was not found');
2426
- error.code = 'ReferenceNotFound';
2427
- error.statusCode = 404;
2428
- throw error;
2429
- }
2430
-
2431
- if (referencedMessage) {
2432
- // Verify Message-ID if specified
2433
- if (data.reference.messageId && data.reference.messageId !== referencedMessage.messageId) {
2434
- let err = new Error('The referenced message was found, but its Message-ID does not match the expected value');
2435
- err.code = 'MessageNotFound';
2436
- err.statusCode = 404;
2437
- throw err;
2438
- }
2439
-
2440
- // Build references header chain
2441
- let references = buildReferences(referencedMessage);
2442
- if (references.length) {
2443
- if (!data.headers) {
2444
- data.headers = {};
2445
- }
2446
- data.headers.references = references.join(' ');
2447
- }
2448
-
2449
- // Set In-Reply-To header for replies
2450
- if (['reply', 'reply-all'].includes(data.reference.action) && referencedMessage.messageId) {
2451
- data.headers['in-reply-to'] = referencedMessage.messageId;
2452
- }
2453
-
2454
- // Check if we need to update flags on referenced message
2455
- let referenceFlags = ['\\Answered'].concat(data.reference.action === 'forward' ? '$Forwarded' : []);
2456
- if (!referencedMessage.flags || !referencedMessage.flags.length || !referenceFlags.some(flag => referencedMessage.flags.includes(flag))) {
2457
- data.reference.update = true;
2458
- }
2459
-
2460
- // Preserve thread ID, but let a caller-supplied threadId win
2461
- if (!data.reference.threadId && referencedMessage.threadId) {
2462
- data.reference.threadId = referencedMessage.threadId;
2463
- }
2464
-
2465
- // Generate subject with appropriate prefix
2466
- if (!data.subject && referencedMessage.subject) {
2467
- let subject = referencedMessage.subject;
2468
- let prefix;
2469
- switch (data.reference.action) {
2470
- case 'reply':
2471
- case 'reply-all':
2472
- if (!/^Re:/i.test(subject)) {
2473
- prefix = 'Re';
2474
- }
2475
- break;
2476
- case 'forward':
2477
- if (!/^Fwd:/i.test(subject)) {
2478
- prefix = 'Fwd';
2479
- }
2480
- break;
2481
- }
2482
- data.subject = `${prefix ? prefix + ': ' : ''}${subject}`;
2483
- }
2484
-
2485
- let cidAttachments = [];
2486
-
2487
- // Process inline content for replies/forwards
2488
- if (data.reference.inline) {
2489
- let inlineMessageData = {
2490
- text: referencedMessage.text && referencedMessage.text.plain,
2491
- html: referencedMessage.text && referencedMessage.text.html
2492
- };
2493
-
2494
- for (let key of ['from', 'to', 'cc', 'bcc', 'date', 'subject']) {
2495
- inlineMessageData[key] = referencedMessage[key];
2496
- }
2497
-
2498
- if (inlineMessageData.html) {
2499
- // Find inline attachments referenced in HTML
2500
- cidAttachments = findReferencedCidAttachments(inlineMessageData.html, referencedMessage.attachments);
2501
-
2502
- try {
2503
- let html = data.html;
2504
- if (!(html || '').toString().trim() && data.text) {
2505
- html = textToHtml(data.text); // convert text to html
2506
- }
2507
-
2508
- data.html = inlineHtml(data.reference.action, html, inlineMessageData, inlineOptions);
2509
- } catch (err) {
2510
- this.logger.error({ msg: 'Failed to generate inline HTML content', err });
2511
- }
2512
- }
2513
-
2514
- if (data.text) {
2515
- try {
2516
- data.text = inlineText(data.reference.action, data.text, inlineMessageData, inlineOptions);
2517
- } catch (err) {
2518
- this.logger.error({ msg: 'Failed to generate inline text content', err });
2519
- }
2520
- }
2521
- }
2522
-
2523
- // Set the recipients of a reply or reply-all
2524
- applyReferenceRecipients(data, referencedMessage);
2525
-
2526
- // Determine which attachments to include
2527
- let attachmentsToDownload;
2528
-
2529
- if (
2530
- data.reference.action === 'forward' &&
2531
- data.reference.forwardAttachments &&
2532
- referencedMessage.attachments &&
2533
- referencedMessage.attachments.length
2534
- ) {
2535
- // download all
2536
- attachmentsToDownload = referencedMessage.attachments;
2537
- } else if (cidAttachments.length) {
2538
- // download referenced attachments
2539
- attachmentsToDownload = cidAttachments;
2540
- }
2541
-
2542
- // Download and attach referenced attachments
2543
- if (attachmentsToDownload && attachmentsToDownload.length) {
2544
- this.checkIMAPConnection(connectionOptions);
2545
-
2546
- this.logger.debug({
2547
- msg: 'Fetching attachments from the referenced email',
2548
- attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
2549
- });
2550
-
2551
- // fetch and add attachments to the message
2552
- if (!data.attachments) {
2553
- data.attachments = [];
2554
- }
2555
- for (let attachment of attachmentsToDownload) {
2556
- let content;
2557
- if (attachment.content) {
2558
- // use local cache
2559
- content = Buffer.from(attachment.content, 'base64');
2560
- this.logger.trace({ msg: 'Using cached email content', attachment: attachment.id, size: content.length });
2561
- } else {
2562
- // fetch from IMAP
2563
- content = await this.getAttachmentContent(
2564
- attachment.id,
2565
- {
2566
- chunkSize: Math.max(DOWNLOAD_CHUNK_SIZE, 2 * 1024 * 1024),
2567
- contentOnly: true
2568
- },
2569
- connectionOptions
2570
- );
2571
- }
2572
- if (!content) {
2573
- // skip missing?
2574
- continue;
2575
- }
2576
- data.attachments.push({
2577
- filename: attachment.filename,
2578
- content,
2579
- contentType: attachment.contentType,
2580
- contentDisposition: attachment.inline ? 'inline' : 'attachment',
2581
- cid: attachment.contentId || null
2582
- });
2583
- }
2584
- }
2585
- }
2650
+ referencedMessage = await this.resolveReference(data, inlineOptions, connectionOptions, {
2651
+ checkConnection: true,
2652
+ trackUpdate: true,
2653
+ copyThreadId: true
2654
+ });
2586
2655
  }
2587
2656
 
2588
2657
  // resolve referenced attachments by ID
2589
- for (let attachment of data.attachments || []) {
2590
- if (attachment.reference && !attachment.content) {
2591
- this.checkIMAPConnection(connectionOptions);
2592
-
2593
- let content = await this.getAttachmentContent(
2594
- attachment.reference,
2595
- {
2596
- chunkSize: Math.max(DOWNLOAD_CHUNK_SIZE, 2 * 1024 * 1024),
2597
- contentOnly: true
2598
- },
2599
- connectionOptions
2600
- );
2601
-
2602
- if (!content) {
2603
- let error = new Error('Referenced attachment was not found');
2604
- error.code = 'ReferenceNotFound';
2605
- error.statusCode = 404;
2606
- throw error;
2607
- }
2608
-
2609
- attachment.content = content;
2610
- }
2611
- }
2658
+ await this.resolveAttachmentReferences(data, connectionOptions);
2612
2659
 
2613
2660
  // Generate raw MIME message
2614
2661
  let { raw, hasBcc, envelope, subject, messageId, sendAt, deliveryAttempts, trackClicks, trackOpens, trackingEnabled, gateway } = await getRawEmail(
@@ -2623,18 +2670,9 @@ class BaseClient {
2623
2670
  messageId
2624
2671
  };
2625
2672
 
2626
- if (data.reference && (data.reference.message || data.reference.threadId)) {
2627
- response.reference = {};
2628
- if (data.reference.message) {
2629
- response.reference.message = data.reference.message;
2630
- response.reference.success = referencedMessage ? true : false;
2631
- if (!referencedMessage) {
2632
- response.reference.error = 'Referenced message was not found';
2633
- }
2634
- }
2635
- if (data.reference.threadId) {
2636
- response.reference.threadId = data.reference.threadId;
2637
- }
2673
+ let referenceResponse = buildReferenceResponse(data.reference, referencedMessage);
2674
+ if (referenceResponse) {
2675
+ response.reference = referenceResponse;
2638
2676
  }
2639
2677
 
2640
2678
  response.preview = raw.toString('base64');
@@ -2660,41 +2698,131 @@ class BaseClient {
2660
2698
  throw err;
2661
2699
  }
2662
2700
 
2663
- // Configure tracking settings: what the message itself does not decide comes from one read
2664
- // of the instance settings
2665
- const messageTracking = { trackingEnabled, trackClicks, trackOpens };
2666
- ({ trackClicks, trackOpens } = resolveTracking(
2701
+ raw = await this.applyTracking(raw, accountData, messageId, baseUrl, { trackingEnabled, trackClicks, trackOpens });
2702
+
2703
+ // Store the message in the queue and schedule the submit job
2704
+ let response = await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData });
2705
+
2706
+ let referenceResponse = buildReferenceResponse(data.reference, referencedMessage);
2707
+ if (referenceResponse) {
2708
+ response.reference = referenceResponse;
2709
+ }
2710
+
2711
+ return response;
2712
+ }
2713
+
2714
+ /**
2715
+ * Adds the List-ID and one-click unsubscribe headers to a message sent to a single list
2716
+ * recipient, generating its Message-ID first because the unsubscribe URL signs it. Updates
2717
+ * `data.headers`, `data.messageId` and `context.rcpt` in place
2718
+ * @param {Object} data - Message data
2719
+ * @param {Object} accountData - Account data
2720
+ * @param {string|null} baseUrl - Service URL the unsubscribe link points at
2721
+ * @param {Object} context - Template context
2722
+ * @returns {Object|null} The skipped response when the recipient has unsubscribed from the list
2723
+ */
2724
+ async applyListHeaders(data, accountData, baseUrl, context) {
2725
+ if (!baseUrl || !data.listId || !data.to || data.to.length !== 1 || !data.to[0].address) {
2726
+ return null;
2727
+ }
2728
+
2729
+ // check if not already blocked
2730
+ let blockData;
2731
+
2732
+ try {
2733
+ blockData = await this.redis.hget(`${REDIS_PREFIX}lists:unsub:entries:${data.listId}`, data.to[0].address.toLowerCase().trim());
2734
+ blockData = JSON.parse(blockData);
2735
+ } catch (err) {
2736
+ blockData = false;
2737
+ }
2738
+
2739
+ // Skip if recipient has unsubscribed
2740
+ if (blockData) {
2741
+ return {
2742
+ responseValue: {
2743
+ skipped: {
2744
+ reason: blockData.reason,
2745
+ listId: data.listId
2746
+ }
2747
+ }
2748
+ };
2749
+ }
2750
+
2751
+ if (!data.headers) {
2752
+ data.headers = {};
2753
+ }
2754
+
2755
+ // Generate List headers
2756
+ let baseDomain = listBaseDomain(baseUrl);
2757
+
2758
+ const serviceSecret = await getServiceSecret();
2759
+
2760
+ let fromDomain = senderDomain(data.from && data.from.address, baseDomain);
2761
+
2762
+ data.headers['List-ID'] = `<${data.listId}.${baseDomain}>`;
2763
+
2764
+ if (!data.messageId) {
2765
+ data.messageId = `<${uuid()}@${fromDomain}>`;
2766
+ }
2767
+
2768
+ // Create signed unsubscribe URL
2769
+ let unsubscribeUrl = buildUnsubscribeUrl(serviceSecret, baseUrl, {
2770
+ account: accountData.account,
2771
+ list: data.listId,
2772
+ recipient: data.to[0].address,
2773
+ messageId: data.messageId
2774
+ });
2775
+
2776
+ context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl });
2777
+
2778
+ // Add RFC 8058 compliant unsubscribe headers
2779
+ data.headers['List-Unsubscribe'] = `<${context.rcpt.unsubscribeUrl}>`;
2780
+ data.headers['List-Unsubscribe-Post'] = 'List-Unsubscribe=One-Click';
2781
+
2782
+ return null;
2783
+ }
2784
+
2785
+ /**
2786
+ * Renders the template fields of a message that asked for rendering or is a list message,
2787
+ * then drops the render options
2788
+ * @param {Object} data - Message data, updated in place
2789
+ * @param {Object} context - Template context
2790
+ */
2791
+ renderTemplateFields(data, context) {
2792
+ if (data.render || data.listId) {
2793
+ for (let key of ['subject', 'html', 'text', 'previewText']) {
2794
+ data[key] = this.render(data[key], context, key, data.render && data.render.format);
2795
+ }
2796
+ }
2797
+
2798
+ delete data.render;
2799
+ }
2800
+
2801
+ /**
2802
+ * Adds open and click tracking to a queued message. What the message itself does not decide
2803
+ * comes from one read of the instance settings
2804
+ * @param {Buffer} raw - Raw RFC822 message
2805
+ * @param {Object} accountData - Account data
2806
+ * @param {string} messageId - Message-ID header value
2807
+ * @param {string|null} baseUrl - Service URL the trackers point at
2808
+ * @param {Object} messageTracking - trackingEnabled, trackClicks and trackOpens of the message
2809
+ * @returns {Buffer} The message, with trackers when any apply
2810
+ */
2811
+ async applyTracking(raw, accountData, messageId, baseUrl, messageTracking) {
2812
+ const { trackClicks, trackOpens } = resolveTracking(
2667
2813
  messageTracking,
2668
2814
  needsTrackingSettings(messageTracking) ? await settings.getMulti(...TRACKING_SETTINGS) : undefined
2669
- ));
2815
+ );
2670
2816
 
2671
2817
  // Add tracking pixels and link tracking
2672
2818
  if (raw && (trackClicks || trackOpens) && baseUrl) {
2673
- // add open and click tracking
2674
2819
  raw = await addTrackers(raw, accountData.account, messageId, baseUrl, {
2675
2820
  trackClicks,
2676
2821
  trackOpens
2677
2822
  });
2678
2823
  }
2679
2824
 
2680
- // Store the message in the queue and schedule the submit job
2681
- let response = await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData });
2682
-
2683
- if (data.reference && (data.reference.message || data.reference.threadId)) {
2684
- response.reference = {};
2685
- if (data.reference.message) {
2686
- response.reference.message = data.reference.message;
2687
- response.reference.success = referencedMessage ? true : false;
2688
- if (!referencedMessage) {
2689
- response.reference.error = 'Referenced message was not found';
2690
- }
2691
- }
2692
- if (data.reference.threadId) {
2693
- response.reference.threadId = data.reference.threadId;
2694
- }
2695
- }
2696
-
2697
- return response;
2825
+ return raw;
2698
2826
  }
2699
2827
 
2700
2828
  /**
@@ -2992,6 +3120,25 @@ class BaseClient {
2992
3120
  return false;
2993
3121
  }
2994
3122
 
3123
+ /**
3124
+ * The tail both API clients run on a formatted message: the auto-reply check, then the
3125
+ * OTP-Token. The providers differ in the first step and the difference is kept on purpose:
3126
+ * Gmail checks every message (the subject alone can mark an auto-reply), MS Graph only a
3127
+ * message fetched with its headers
3128
+ * @param {Object} message - Formatted message, updated in place
3129
+ * @param {boolean} autoReplyNeedsHeaders - Skip the auto-reply check for a message without headers
3130
+ */
3131
+ finalizeApiMessage(message, autoReplyNeedsHeaders) {
3132
+ if ((message.headers || !autoReplyNeedsHeaders) && this.isAutoreply(message)) {
3133
+ message.isAutoReply = true;
3134
+ }
3135
+
3136
+ const otp = getMessageOtp(message.headers, this.summaryProvider());
3137
+ if (otp) {
3138
+ message.otp = otp;
3139
+ }
3140
+ }
3141
+
2995
3142
  /**
2996
3143
  * Gets message fetch options based on settings
2997
3144
  * @returns {Object} Fetch options for IMAP message retrieval
@@ -3034,102 +3181,61 @@ class BaseClient {
3034
3181
  }
3035
3182
 
3036
3183
  /**
3037
- * Main processor for new messages
3038
- * Handles bounce detection, complaint processing, attachments,
3039
- * calendar events, and AI-powered features
3040
- * @param {Object} messageData - Message data
3041
- * @param {Object} options - Processing options
3184
+ * Renders the web-safe copy of a new message and embeds the images its HTML references by
3185
+ * Content-ID. An attachment notifyAttachments already loaded is embedded as is; anything
3186
+ * downloaded here is capped at the inline image size
3187
+ * @param {Object} messageData - The new message, changed in place
3042
3188
  */
3043
- async processNew(messageData, options) {
3044
- let requestedHeaders = options.headers;
3189
+ async buildWebSafeHtml(messageData) {
3190
+ messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
3045
3191
 
3046
- let bounceNotifyInfo;
3047
- let complaintNotifyInfo;
3048
- let content;
3192
+ if (messageData.text.html && messageData.attachments) {
3193
+ let attachmentList = new Map();
3194
+ let cidReferences = collectCidReferences(messageData.text.html);
3049
3195
 
3050
- // Check for abuse report format (ARF) complaints
3051
- if (this.mightBeAComplaint(messageData)) {
3052
- try {
3053
- // Download attachments needed for complaint detection
3054
- for (let attachment of messageData.attachments || []) {
3055
- if (!COMPLAINT_ATTACHMENT_TYPES.includes(attachment.contentType)) {
3056
- continue;
3057
- }
3058
-
3059
- Object.defineProperty(attachment, 'content', {
3060
- value: (await this.getAttachment(attachment.id))?.data?.toString(),
3061
- enumerable: false
3062
- });
3196
+ for (let attachment of messageData.attachments) {
3197
+ let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
3198
+ if (!contentId || !cidReferences.has(contentId)) {
3199
+ continue;
3063
3200
  }
3064
3201
 
3065
- // Parse ARF report
3066
- const report = await arfDetect(messageData);
3202
+ if (!attachment.content && !(attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
3203
+ try {
3204
+ attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3205
+ } catch (err) {
3206
+ this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3207
+ }
3208
+ }
3067
3209
 
3068
- complaintNotifyInfo = complaintNotification(report, messageData);
3069
- } catch (err) {
3070
- this.logger.error({
3071
- msg: 'Failed to process ARF',
3072
- id: messageData.id,
3073
- uid: messageData.uid,
3074
- messageId: messageData.messageId,
3075
- err
3210
+ attachmentList.set(contentId, {
3211
+ attachment,
3212
+ content: attachment.content || null
3076
3213
  });
3077
3214
  }
3078
- }
3079
-
3080
- // Check for delivery status notifications (DSN)
3081
- if (this.mightBeDSNResponse(messageData)) {
3082
- try {
3083
- let raw = await this.getRawMessage(messageData.id);
3084
3215
 
3085
- let parsed = await parseMessage(raw, DSN_PARSER_OPTIONS);
3086
- if (parsed) {
3087
- content = { parsed };
3088
- applyDeliveryReport(parsed, messageData, this.logger);
3089
- }
3090
- } catch (err) {
3091
- this.logger.error({
3092
- msg: 'Failed to process DSN',
3093
- id: messageData.id,
3094
- uid: messageData.uid,
3095
- messageId: messageData.messageId,
3096
- err
3097
- });
3098
- }
3216
+ embedInlineImages(messageData.text, attachmentList);
3099
3217
  }
3100
3218
 
3101
- // Check if this could be a bounce
3102
- if (this.mightBeABounce(messageData)) {
3103
- // parse for bounce
3104
- try {
3105
- if (!content) {
3106
- content = await this.getRawMessage(messageData.id);
3107
- }
3108
-
3109
- if (content) {
3110
- let bounce = await bounceDetect(content);
3219
+ markWebSafe(messageData.text);
3220
+ }
3111
3221
 
3112
- await classifyBounce(bounce, this.call, this.logger);
3113
- bounceNotifyInfo = bounceNotification(bounce, messageData);
3222
+ /**
3223
+ * Main processor for new messages
3224
+ * Handles bounce detection, complaint processing, attachments,
3225
+ * calendar events, and AI-powered features
3226
+ * @param {Object} messageData - Message data
3227
+ * @param {Object} options - Processing options
3228
+ */
3229
+ async processNew(messageData, options) {
3230
+ let requestedHeaders = options.headers;
3114
3231
 
3115
- this.logger.debug({
3116
- msg: 'Detected bounce message',
3117
- id: messageData.id,
3118
- uid: messageData.uid,
3119
- messageId: messageData.messageId,
3120
- bounce
3121
- });
3122
- }
3123
- } catch (err) {
3124
- this.logger.error({
3125
- msg: 'Failed to process potential bounce',
3126
- id: messageData.id,
3127
- uid: messageData.uid,
3128
- messageId: messageData.messageId,
3129
- err
3130
- });
3131
- }
3132
- }
3232
+ const { bounceNotifyInfo, complaintNotifyInfo } = await runArrivalChecks(messageData, {
3233
+ detector: this,
3234
+ loadComplaintPart: async attachment => setHiddenContent(attachment, (await this.getAttachment(attachment.id))?.data?.toString()),
3235
+ fetchSource: () => this.getRawMessage(messageData.id),
3236
+ call: this.call,
3237
+ logger: this.logger
3238
+ });
3133
3239
 
3134
3240
  // The settings the rest of this pass reads, in one round trip instead of one each
3135
3241
  const { notifyAttachments, notifyAttachmentSize, notifyCalendarEvents, notifyWebSafeHtml } = await settings.getMulti(...NEW_MESSAGE_SETTINGS);
@@ -3155,57 +3261,16 @@ class BaseClient {
3155
3261
  }
3156
3262
  }
3157
3263
 
3158
- // Process with AI features for inbox messages. A message with no text part has no text
3159
- // object at all, and nothing to summarize
3160
- if (messageData.messageSpecialUse === '\\Inbox' && (messageData.text?.plain || messageData.text?.html)) {
3161
- let llmMessageData = Object.assign({ account: this.account }, messageData);
3162
-
3163
- if (await llmPreProcess.run(llmMessageData)) {
3164
- await llmPreProcess.summarize(messageData, {
3165
- call: this.call,
3166
- redis: this.redis,
3167
- account: this.account,
3168
- provider: this.summaryProvider(),
3169
- logger: this.logger
3170
- });
3171
- }
3172
- }
3264
+ await runLlmSummary(messageData, this.account, () => ({
3265
+ call: this.call,
3266
+ redis: this.redis,
3267
+ account: this.account,
3268
+ provider: this.summaryProvider(),
3269
+ logger: this.logger
3270
+ }));
3173
3271
 
3174
- // Convert message HTML to web safe HTML
3175
3272
  if (notifyWebSafeHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
3176
- // convert to web safe
3177
- messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
3178
-
3179
- // embed inline images as data URIs
3180
- if (messageData.text.html && messageData.attachments) {
3181
- let attachmentList = new Map();
3182
- let cidReferences = collectCidReferences(messageData.text.html);
3183
-
3184
- // Find CID references in HTML
3185
- for (let attachment of messageData.attachments) {
3186
- let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
3187
- if (contentId && cidReferences.has(contentId)) {
3188
- // An attachment notifyAttachments already loaded is embedded as is; anything
3189
- // downloaded here is capped at the inline image size
3190
- if (!attachment.content && !(attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
3191
- try {
3192
- attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3193
- } catch (err) {
3194
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3195
- }
3196
- }
3197
-
3198
- attachmentList.set(contentId, {
3199
- attachment,
3200
- content: attachment.content || null
3201
- });
3202
- }
3203
- }
3204
-
3205
- embedInlineImages(messageData.text, attachmentList);
3206
- }
3207
-
3208
- markWebSafe(messageData.text);
3273
+ await this.buildWebSafeHtml(messageData);
3209
3274
  }
3210
3275
 
3211
3276
  // Narrow the headers to what the caller asked for. This runs last: the checks and the AI
@@ -3423,6 +3488,37 @@ class BaseClient {
3423
3488
  throw err;
3424
3489
  }
3425
3490
 
3491
+ const smtpContext = await this.buildSmtpContext(accountData, data);
3492
+
3493
+ const jobData = data.job;
3494
+
3495
+ // Verify job still exists
3496
+ const submitJobEntry = await this.submitQueue.getJob(jobData.id);
3497
+ if (!submitJobEntry) {
3498
+ this.logger.error({ msg: 'Submit job was not found', job: jobData.id });
3499
+ return false;
3500
+ }
3501
+
3502
+ const info = await this.sendOnce(submitJobEntry, data, smtpContext);
3503
+
3504
+ // The server has accepted the message, so nothing from here on may throw: a failure is a
3505
+ // bookkeeping failure, and rethrowing it would make the submit worker deliver it again.
3506
+ // Every step below catches its own errors
3507
+ await this.recordSubmitSuccess(info, submitJobEntry, data, smtpContext);
3508
+
3509
+ await this.runPostSendActions(data, accountData, smtpContext);
3510
+
3511
+ return { response: info.response, messageId: info.messageId };
3512
+ }
3513
+
3514
+ /**
3515
+ * Resolves the SMTP settings a submission is sent with: the gateway, the connection, the
3516
+ * authentication and the network route
3517
+ * @param {Object} accountData - Account data
3518
+ * @param {Object} data - Submission data
3519
+ * @returns {Object} smtpSettings, networkRouting, gatewayData and gatewayObject
3520
+ */
3521
+ async buildSmtpContext(accountData, data) {
3426
3522
  // Build SMTP configuration using SmtpConfigBuilder
3427
3523
  const smtpConfigBuilder = new SmtpConfigBuilder({
3428
3524
  redis: this.redis,
@@ -3456,20 +3552,22 @@ class BaseClient {
3456
3552
  // Build network routing info for notifications
3457
3553
  const networkRouting = NetworkRoutingBuilder.build(smtpSettings, data);
3458
3554
 
3459
- // Extract message data
3460
- let { raw, hasBcc, envelope, messageId, queueId, reference, job: jobData } = data;
3555
+ return { smtpSettings, networkRouting, gatewayData, gatewayObject };
3556
+ }
3461
3557
 
3462
- // Verify job still exists
3463
- const submitJobEntry = await this.submitQueue.getJob(jobData.id);
3464
- if (!submitJobEntry) {
3465
- this.logger.error({ msg: 'Submit job was not found', job: jobData.id });
3466
- return false;
3467
- }
3558
+ /**
3559
+ * Sends a submission once through the pooled transport, within the deadline. A failed send is
3560
+ * recorded (status, feedback key, delivery error webhook) and rethrown, and a send that ran
3561
+ * into the deadline penalises the account
3562
+ * @param {Object} submitJobEntry - The BullMQ job of the submission
3563
+ * @param {Object} data - Submission data
3564
+ * @param {Object} smtpContext - What buildSmtpContext() resolved
3565
+ * @returns {Object} sendMail() info
3566
+ */
3567
+ async sendOnce(submitJobEntry, data, smtpContext) {
3568
+ const { smtpSettings, networkRouting, gatewayData, gatewayObject } = smtpContext;
3569
+ const { raw, hasBcc, envelope, messageId, queueId, job: jobData } = data;
3468
3570
 
3469
- // Only the send itself is inside this try. Once the server has accepted the message a
3470
- // failure is a bookkeeping failure: rethrowing it made the submit worker retry (and so
3471
- // deliver) an already delivered message, and reported a messageDeliveryError for it
3472
- let info;
3473
3571
  try {
3474
3572
  // Update job progress
3475
3573
  try {
@@ -3479,7 +3577,7 @@ class BaseClient {
3479
3577
  }
3480
3578
 
3481
3579
  // Send the message, through the pooled transport for these settings, within the deadline
3482
- info = await sendWithDeadline(smtpSettings, {
3580
+ return await sendWithDeadline(smtpSettings, {
3483
3581
  envelope,
3484
3582
  messageId,
3485
3583
  raw: !hasBcc ? raw : await removeBcc(raw),
@@ -3502,6 +3600,20 @@ class BaseClient {
3502
3600
  });
3503
3601
  throw err;
3504
3602
  }
3603
+ }
3604
+
3605
+ /**
3606
+ * Records a send the server accepted: the EHLO response, the job progress, the messageSent
3607
+ * webhook and the account's SMTP status. Each step catches its own errors, because the
3608
+ * message is already delivered
3609
+ * @param {Object} info - sendMail() info, its messageId replaced by the provider's own when it reported one
3610
+ * @param {Object} submitJobEntry - The BullMQ job of the submission
3611
+ * @param {Object} data - Submission data
3612
+ * @param {Object} smtpContext - What buildSmtpContext() resolved
3613
+ */
3614
+ async recordSubmitSuccess(info, submitJobEntry, data, smtpContext) {
3615
+ const { networkRouting } = smtpContext;
3616
+ const { envelope, messageId, queueId } = data;
3505
3617
 
3506
3618
  // Store EHLO response for debugging
3507
3619
  if (info.ehlo) {
@@ -3544,6 +3656,19 @@ class BaseClient {
3544
3656
  } catch (err) {
3545
3657
  // ignore
3546
3658
  }
3659
+ }
3660
+
3661
+ /**
3662
+ * The actions after a delivered submission: the Sent Mail copy, the draft cleanup, the flags
3663
+ * of the referenced message, the feedback key and the gateway stats. Each one catches its own
3664
+ * errors, because the message is already delivered
3665
+ * @param {Object} data - Submission data
3666
+ * @param {Object} accountData - Account data
3667
+ * @param {Object} smtpContext - What buildSmtpContext() resolved
3668
+ */
3669
+ async runPostSendActions(data, accountData, smtpContext) {
3670
+ const { gatewayData, gatewayObject } = smtpContext;
3671
+ const { raw, messageId, queueId, reference } = data;
3547
3672
 
3548
3673
  // Handle sent mail copy to folder
3549
3674
  const copyDeciderInputs = {
@@ -3591,8 +3716,6 @@ class BaseClient {
3591
3716
  if (gatewayData) {
3592
3717
  await this.updateGatewayStats(gatewayObject, queueId, messageId, reference);
3593
3718
  }
3594
-
3595
- return { response: info.response, messageId: info.messageId };
3596
3719
  }
3597
3720
 
3598
3721
  /**
@@ -3693,7 +3816,7 @@ class BaseClient {
3693
3816
  reference.message,
3694
3817
  {
3695
3818
  flags: {
3696
- add: ['\\Answered'].concat(reference.action === 'forward' ? '$Forwarded' : [])
3819
+ add: [referenceFlag(reference.action)]
3697
3820
  }
3698
3821
  },
3699
3822
  connectionOptions
@@ -3847,6 +3970,10 @@ module.exports = {
3847
3970
  metricsMeta: postMetrics,
3848
3971
  applyReferenceRecipients,
3849
3972
  buildReferences,
3973
+ buildReferenceResponse,
3974
+ listBaseDomain,
3975
+ senderDomain,
3850
3976
  markRejectedAccessToken,
3977
+ needsReferenceFlagUpdate,
3851
3978
  renewRejectedAccessToken
3852
3979
  };