emailengine-app 2.75.0 → 2.76.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.
@@ -78,11 +78,6 @@ jobs:
78
78
  with:
79
79
  node-version: 24
80
80
  cache: npm
81
- - name: Setup Redis CLI
82
- uses: shogo82148/actions-setup-redis@v1
83
- with:
84
- redis-version: '7.x'
85
- auto-start: 'false'
86
81
  - run: npm install
87
82
  - name: Run unit tests
88
83
  run: |
@@ -157,11 +152,6 @@ jobs:
157
152
  with:
158
153
  node-version: 24
159
154
  cache: npm
160
- - name: Setup Redis CLI
161
- uses: shogo82148/actions-setup-redis@v1
162
- with:
163
- redis-version: '7.x'
164
- auto-start: 'false'
165
155
  - run: npm install
166
156
  - name: Run integration tests
167
157
  run: |
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.76.0](https://github.com/postalsys/emailengine/compare/v2.75.0...v2.76.0) (2026-07-29)
4
+
5
+
6
+ ### Features
7
+
8
+ * add an API endpoint for sending stored drafts ([16e759a](https://github.com/postalsys/emailengine/commit/16e759aab429160d312827618841222c7704057d))
9
+ * add EENGINE_UPDATE_CHECK_DISABLED to opt out of the GitHub update check ([e92bfe6](https://github.com/postalsys/emailengine/commit/e92bfe6e9b01ae9abe1cc782b51d39aac94b2341))
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * **deps:** update dependencies (imapflow 1.6.3) ([7dc423c](https://github.com/postalsys/emailengine/commit/7dc423cafe45206c36b8293f1a57f47f56594dfe))
15
+ * **deps:** update dependencies (imapflow 1.6.5) ([6a350e1](https://github.com/postalsys/emailengine/commit/6a350e1ab7e8b96ae089d0768c2a9300e0a405e0))
16
+ * **imap:** stop re-listing the folders on every connection setup ([6d79eb3](https://github.com/postalsys/emailengine/commit/6d79eb3f67a3d2bb826f43483c4e51d03ea98d8a))
17
+
3
18
  ## [2.75.0](https://github.com/postalsys/emailengine/compare/v2.74.2...v2.75.0) (2026-07-28)
4
19
 
5
20
 
package/config/e2e.toml CHANGED
@@ -27,7 +27,7 @@ imap = 1
27
27
  level = "warn"
28
28
 
29
29
  [dbs]
30
- # Isolated Redis DB for e2e; flushed before each run by test/e2e/flush-redis.js
30
+ # Isolated Redis DB for e2e; flushed before each run by test/helpers/flush-redis.js
31
31
  redis = "redis://127.0.0.1:6379/14"
32
32
 
33
33
  [api]
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-07-27T14:45:52.000000",
2
+ "creationTime": "2026-07-29T14:46:26.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -30,6 +30,9 @@ function handleError(request, err) {
30
30
  if (err.details) {
31
31
  error.output.payload.details = err.details;
32
32
  }
33
+ if (err.info) {
34
+ error.output.payload.info = err.info;
35
+ }
33
36
  throw error;
34
37
  }
35
38
 
@@ -1,11 +1,11 @@
1
1
  'use strict';
2
2
 
3
- const Boom = require('@hapi/boom');
4
3
  const Joi = require('joi');
5
4
  const { redis } = require('../db');
6
5
  const { Account } = require('../account');
7
6
  const getSecret = require('../get-secret');
8
7
  const { failAction } = require('../tools');
8
+ const { handleError } = require('./route-helpers');
9
9
  const {
10
10
  messageReferenceSchema,
11
11
  fromAddressSchema,
@@ -20,6 +20,50 @@ const {
20
20
  errorResponses
21
21
  } = require('../schemas');
22
22
 
23
+ // Schema fragments shared between the message submit and the draft submit routes. Joi schemas
24
+ // are immutable, so per-route variants are derived with .description()/.label() where needed.
25
+ const submitHeadersSchema = Joi.object({
26
+ 'x-ee-timeout': headerTimeoutSchema,
27
+ 'idempotency-key': idempotencyKeySchema
28
+ }).unknown();
29
+
30
+ const sendAtSchema = Joi.date().iso().example('2021-07-08T07:06:34.336Z').description('Send message at specified time');
31
+
32
+ const deliveryAttemptsSchema = Joi.number().integer().example(10).description('How many delivery attempts to make until message is considered as failed');
33
+
34
+ const gatewaySchema = Joi.string().max(256).example('example').description('Optional SMTP gateway ID for message routing').label('MessageGateway');
35
+
36
+ const dsnSchema = Joi.object({
37
+ id: Joi.string().trim().empty('').max(256).description('The envelope identifier that would be included in the response (ENVID)'),
38
+ return: Joi.string()
39
+ .trim()
40
+ .empty('')
41
+ .valid('headers', 'full')
42
+ .required()
43
+ .description('Specifies if only headers or the entire body of the message should be included in the response (RET)')
44
+ .label('DsnReturn'),
45
+ notify: Joi.array()
46
+ .single()
47
+ .items(Joi.string().valid('never', 'success', 'failure', 'delay').label('NotifyEntry'))
48
+ .description('Defines the conditions under which a DSN response should be sent')
49
+ .label('DsnNotify'),
50
+ recipient: Joi.string().trim().empty('').email().description('The email address the DSN should be sent (ORCPT)')
51
+ }).description('Request DSN notifications');
52
+
53
+ const proxySchema = settingsSchema.proxyUrl.description('Optional proxy URL to use when connecting to the SMTP server');
54
+
55
+ const localAddressSchema = ipSchema.description('Optional local IP address to bind to when connecting to the SMTP server');
56
+
57
+ const idempotencyResponseSchema = Joi.object({
58
+ key: idempotencyKeySchema.example('submit-12345').description('Idempotency key from the request').label('ResponseIdempotencyKey'),
59
+ status: Joi.string()
60
+ .valid('MISS', 'HIT')
61
+ .example('MISS')
62
+ .description('Whether the response was generated now (MISS) or returned from the idempotency cache (HIT)')
63
+ })
64
+ .description('Idempotency info, present when an Idempotency-Key header was used')
65
+ .label('ResponseIdempotency');
66
+
23
67
  async function init(args) {
24
68
  const { server, call, CORS_CONFIG, MAX_ATTACHMENT_SIZE, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT } = args;
25
69
 
@@ -43,18 +87,7 @@ async function init(args) {
43
87
  useStructuredFormat: request.query.useStructuredFormat
44
88
  });
45
89
  } catch (err) {
46
- request.logger.error({ msg: 'API request failed', err });
47
- if (Boom.isBoom(err)) {
48
- throw err;
49
- }
50
- let error = Boom.boomify(err, { statusCode: err.statusCode || 500 });
51
- if (err.code) {
52
- error.output.payload.code = err.code;
53
- }
54
- if (err.info) {
55
- error.output.payload.info = err.info;
56
- }
57
- throw error;
90
+ handleError(request, err);
58
91
  }
59
92
  },
60
93
  options: {
@@ -106,10 +139,7 @@ async function init(args) {
106
139
  )
107
140
  }).label('SubmitQuery'),
108
141
 
109
- headers: Joi.object({
110
- 'x-ee-timeout': headerTimeoutSchema,
111
- 'idempotency-key': idempotencyKeySchema
112
- }).unknown(),
142
+ headers: submitHeadersSchema,
113
143
 
114
144
  payload: Joi.object({
115
145
  reference: messageReferenceSchema,
@@ -285,12 +315,9 @@ async function init(args) {
285
315
  locale: Joi.string().empty('').max(100).example('fr').description('Optional locale').label('MessageLocale'),
286
316
  tz: Joi.string().empty('').max(100).example('Europe/Tallinn').description('Optional timezone'),
287
317
 
288
- sendAt: Joi.date().iso().example('2021-07-08T07:06:34.336Z').description('Send message at specified time'),
289
- deliveryAttempts: Joi.number()
290
- .integer()
291
- .example(10)
292
- .description('How many delivery attempts to make until message is considered as failed'),
293
- gateway: Joi.string().max(256).example('example').description('Optional SMTP gateway ID for message routing').label('MessageGateway'),
318
+ sendAt: sendAtSchema,
319
+ deliveryAttempts: deliveryAttemptsSchema,
320
+ gateway: gatewaySchema,
294
321
 
295
322
  listId: Joi.string()
296
323
  .hostname()
@@ -305,24 +332,7 @@ async function init(args) {
305
332
  otherwise: Joi.forbidden()
306
333
  }),
307
334
 
308
- dsn: Joi.object({
309
- id: Joi.string().trim().empty('').max(256).description('The envelope identifier that would be included in the response (ENVID)'),
310
- return: Joi.string()
311
- .trim()
312
- .empty('')
313
- .valid('headers', 'full')
314
- .required()
315
- .description('Specifies if only headers or the entire body of the message should be included in the response (RET)')
316
- .label('DsnReturn'),
317
- notify: Joi.array()
318
- .single()
319
- .items(Joi.string().valid('never', 'success', 'failure', 'delay').label('NotifyEntry'))
320
- .description('Defines the conditions under which a DSN response should be sent')
321
- .label('DsnNotify'),
322
- recipient: Joi.string().trim().empty('').email().description('The email address the DSN should be sent (ORCPT)')
323
- })
324
- .description('Request DSN notifications')
325
- .label('DSN'),
335
+ dsn: dsnSchema.label('DSN'),
326
336
 
327
337
  baseUrl: Joi.string()
328
338
  .trim()
@@ -334,8 +344,8 @@ async function init(args) {
334
344
  .example('https://customer123.myservice.com')
335
345
  .description('Optional base URL for trackers. This URL must point to your EmailEngine instance.'),
336
346
 
337
- proxy: settingsSchema.proxyUrl.description('Optional proxy URL to use when connecting to the SMTP server'),
338
- localAddress: ipSchema.description('Optional local IP address to bind to when connecting to the SMTP server'),
347
+ proxy: proxySchema,
348
+ localAddress: localAddressSchema,
339
349
 
340
350
  dryRun: Joi.boolean()
341
351
  .truthy('Y', 'true', '1')
@@ -404,15 +414,7 @@ async function init(args) {
404
414
  .description('Base64 encoded RFC822 email if a preview was requested. Not returned for mail-merge submissions.')
405
415
  .label('ResponsePreview'),
406
416
 
407
- idempotency: Joi.object({
408
- key: idempotencyKeySchema.example('submit-12345').description('Idempotency key from the request').label('ResponseIdempotencyKey'),
409
- status: Joi.string()
410
- .valid('MISS', 'HIT')
411
- .example('MISS')
412
- .description('Whether the response was generated now (MISS) or returned from the idempotency cache (HIT)')
413
- })
414
- .description('Idempotency info, present when an Idempotency-Key header was used')
415
- .label('ResponseIdempotency'),
417
+ idempotency: idempotencyResponseSchema,
416
418
 
417
419
  mailMerge: Joi.array()
418
420
  .items(
@@ -456,6 +458,111 @@ async function init(args) {
456
458
  }
457
459
  }
458
460
  });
461
+
462
+ server.route({
463
+ method: 'POST',
464
+ path: '/v1/account/{account}/message/{message}/submit',
465
+
466
+ async handler(request) {
467
+ let accountObject = new Account({
468
+ redis,
469
+ account: request.params.account,
470
+ call,
471
+ secret: await getSecret(),
472
+ timeout: request.headers['x-ee-timeout']
473
+ });
474
+
475
+ try {
476
+ return await accountObject.queueMessage(request.payload || {}, {
477
+ source: 'api',
478
+ idempotencyKey: request.headers['idempotency-key'],
479
+ draft: { message: request.params.message }
480
+ });
481
+ } catch (err) {
482
+ handleError(request, err);
483
+ }
484
+ },
485
+ options: {
486
+ description: 'Submit a stored draft for delivery',
487
+ notes: 'Sends an existing draft message. The message must be a draft: stored in the Drafts folder or flagged as a draft (IMAP), carrying the DRAFT label (Gmail), or a draft message (MS Graph). Gmail and MS Graph accounts use the native draft-send call of the provider, which also files the message into the Sent Mail folder and removes the draft. For IMAP accounts the draft is downloaded, sent over SMTP, copied to the Sent Mail folder (unless disabled), and then removed from the Drafts folder.',
488
+ tags: ['api', 'Submit'],
489
+
490
+ plugins: {
491
+ 'hapi-swagger': {
492
+ responses: errorResponses(400, 401, 403, 404, 429, 500, 503)
493
+ }
494
+ },
495
+
496
+ auth: {
497
+ strategy: 'api-token',
498
+ mode: 'required'
499
+ },
500
+ cors: CORS_CONFIG,
501
+
502
+ validate: {
503
+ options: {
504
+ stripUnknown: false,
505
+ abortEarly: false,
506
+ convert: true
507
+ },
508
+ failAction,
509
+
510
+ params: Joi.object({
511
+ account: accountIdSchema.required(),
512
+ message: Joi.string().max(256).required().example('AAAAAQAACnA').description('Message ID of the draft')
513
+ }),
514
+
515
+ headers: submitHeadersSchema,
516
+
517
+ payload: Joi.object({
518
+ envelope: Joi.object({
519
+ from: Joi.string().email().allow('').example('sender@example.com'),
520
+ to: Joi.array().items(Joi.string().email().required().example('recipient@example.com')).single().label('DraftSmtpEnvelopeTo')
521
+ })
522
+ .description(
523
+ "An optional object specifying the SMTP envelope used during email transmission. If not provided, the envelope is derived from the draft's message headers. Only used when the message is delivered over SMTP."
524
+ )
525
+ .label('DraftSMTPEnvelope'),
526
+
527
+ copy: Joi.boolean()
528
+ .allow(null)
529
+ .example(null)
530
+ .description(
531
+ "If set then either copies the message to the Sent Mail folder or not. If not set then uses the account's default setting. Only applies to SMTP deliveries - Gmail and MS Graph file sent drafts into the Sent Mail folder themselves."
532
+ ),
533
+
534
+ sentMailPath: Joi.string()
535
+ .empty('')
536
+ .max(1024)
537
+ .example('Sent Mail')
538
+ .description("Upload sent message to this folder. By default the account's Sent Mail folder is used. Only applies to SMTP deliveries."),
539
+
540
+ sendAt: sendAtSchema,
541
+ deliveryAttempts: deliveryAttemptsSchema,
542
+ gateway: gatewaySchema,
543
+
544
+ dsn: dsnSchema.description('Request DSN notifications. Only used when the message is delivered over SMTP.').label('DraftDSN'),
545
+
546
+ proxy: proxySchema,
547
+ localAddress: localAddressSchema
548
+ })
549
+ .allow(null)
550
+ .label('SubmitDraft')
551
+ },
552
+
553
+ response: {
554
+ schema: Joi.object({
555
+ response: Joi.string().example('Queued for delivery'),
556
+ messageId: Joi.string().example('<a2184d08-a470-fec6-a493-fa211a3756e9@example.com>').description('Message-ID header value'),
557
+ queueId: Joi.string().example('d41f0423195f271f').description('Queue identifier for scheduled email'),
558
+ sendAt: Joi.date().example('2021-07-08T07:06:34.336Z').description('Scheduled send time'),
559
+
560
+ idempotency: idempotencyResponseSchema
561
+ }).label('SubmitDraftResponse'),
562
+ failAction: 'log'
563
+ }
564
+ }
565
+ });
459
566
  }
460
567
 
461
568
  module.exports = init;
@@ -882,6 +882,13 @@ class BaseClient {
882
882
  async queueMessageHandler(data, meta, connectionOptions) {
883
883
  let accountData = await this.accountObject.loadAccountData();
884
884
 
885
+ // Submitting a stored draft skips content processing - the message body already exists.
886
+ // The draft path owns its own gateway load and SMTP-capability check (the effective
887
+ // gateway is only known after the draft's X-EE-* headers have been parsed)
888
+ if (meta && meta.draft) {
889
+ return this.queueDraftEntry(data, meta, accountData, connectionOptions);
890
+ }
891
+
885
892
  // Load gateway configuration if specified
886
893
  let gatewayData;
887
894
  let gatewayObject;
@@ -2004,6 +2011,44 @@ class BaseClient {
2004
2011
  });
2005
2012
  }
2006
2013
 
2014
+ // Store the message in the queue and schedule the submit job
2015
+ let response = await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData });
2016
+
2017
+ if (data.reference && (data.reference.message || data.reference.threadId)) {
2018
+ response.reference = {};
2019
+ if (data.reference.message) {
2020
+ response.reference.message = data.reference.message;
2021
+ response.reference.documentStore = documentStoreUsed;
2022
+ response.reference.success = referencedMessage ? true : false;
2023
+ if (!referencedMessage) {
2024
+ response.reference.error = 'Referenced message was not found';
2025
+ }
2026
+ }
2027
+ if (data.reference.threadId) {
2028
+ response.reference.threadId = data.reference.threadId;
2029
+ }
2030
+ }
2031
+
2032
+ return response;
2033
+ }
2034
+
2035
+ /**
2036
+ * Stores an outbound message in the delivery queue and schedules the submit job
2037
+ * @param {Object} params
2038
+ * @param {Object} params.data - Message data (copy, sentMailPath, feedbackKey, dsn, proxy, localAddress, reference)
2039
+ * @param {Object} params.meta - Metadata for the queue job
2040
+ * @param {Buffer} params.raw - Raw RFC822 message
2041
+ * @param {boolean} params.hasBcc - Whether the raw message carries a Bcc header
2042
+ * @param {Object} params.envelope - SMTP envelope
2043
+ * @param {string} params.messageId - Message-ID header value
2044
+ * @param {string} params.subject - Message subject for queue listings
2045
+ * @param {Date} [params.sendAt] - Scheduled send time
2046
+ * @param {number} [params.deliveryAttempts] - Delivery attempt count override
2047
+ * @param {Object} [params.gatewayData] - Loaded gateway data
2048
+ * @param {Object} [params.draft] - Draft reference if the queued message is a stored draft
2049
+ * @returns {Object} Base queue response
2050
+ */
2051
+ async pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData, draft }) {
2007
2052
  let now = new Date();
2008
2053
 
2009
2054
  //queue for later
@@ -2025,6 +2070,7 @@ class BaseClient {
2025
2070
  envelope,
2026
2071
  messageId,
2027
2072
  reference: data.reference || {},
2073
+ draft: draft || null,
2028
2074
  sendAt: (sendAt && sendAt.getTime()) || false,
2029
2075
  created: now.getTime(),
2030
2076
  copy: data.copy,
@@ -2092,30 +2138,93 @@ class BaseClient {
2092
2138
 
2093
2139
  this.logger.info({ msg: 'Message queued for delivery', envelope, messageId, sendAt: (sendAt || now).toISOString(), queueId, job: job.id });
2094
2140
 
2095
- // Build response
2096
- let response = {
2141
+ return {
2097
2142
  response: 'Queued for delivery',
2098
2143
  messageId,
2099
2144
  sendAt: (sendAt || now).toISOString(),
2100
2145
  queueId
2101
2146
  };
2147
+ }
2102
2148
 
2103
- if (data.reference && (data.reference.message || data.reference.threadId)) {
2104
- response.reference = {};
2105
- if (data.reference.message) {
2106
- response.reference.message = data.reference.message;
2107
- response.reference.documentStore = documentStoreUsed;
2108
- response.reference.success = referencedMessage ? true : false;
2109
- if (!referencedMessage) {
2110
- response.reference.error = 'Referenced message was not found';
2111
- }
2112
- }
2113
- if (data.reference.threadId) {
2114
- response.reference.threadId = data.reference.threadId;
2149
+ /**
2150
+ * Queues an existing draft message for delivery. The draft is resolved through the
2151
+ * backend-specific resolveDraftForSubmit(), its raw content is stored in the queue entry
2152
+ * (used by the SMTP and gateway delivery paths), and a draft reference travels along so
2153
+ * the delivery step can use the provider's native draft-send call and clean up the draft.
2154
+ * @param {Object} data - Submit options ({ envelope, sendAt, ... })
2155
+ * @param {Object} meta - Metadata carrying the draft marker ({ draft: { message } })
2156
+ * @param {Object} accountData - Already loaded account data
2157
+ * @param {Object} connectionOptions - Connection options
2158
+ * @returns {Object} Queue response
2159
+ */
2160
+ async queueDraftEntry(data, meta, accountData, connectionOptions) {
2161
+ let licenseInfo = await this.call({ cmd: 'license' });
2162
+
2163
+ let { raw: draftRaw, draft, threadId } = await this.resolveDraftForSubmit(meta.draft.message, connectionOptions);
2164
+
2165
+ if (threadId) {
2166
+ // Keep the sent copy in the draft's thread (Gmail API accounts)
2167
+ data.reference = { threadId };
2168
+ }
2169
+
2170
+ // Run the draft through the same raw-message normalization as raw API submissions:
2171
+ // consumes X-EE control headers, applies the envelope override, backfills Message-ID
2172
+ // and Date, detects Bcc and derives the SMTP envelope from the headers
2173
+ let { raw, hasBcc, envelope, subject, messageId, sendAt, deliveryAttempts, gateway } = await getRawEmail(
2174
+ {
2175
+ raw: draftRaw,
2176
+ envelope: data.envelope,
2177
+ sendAt: data.sendAt,
2178
+ deliveryAttempts: data.deliveryAttempts,
2179
+ gateway: data.gateway
2180
+ },
2181
+ licenseInfo
2182
+ );
2183
+
2184
+ if (!envelope.to || !envelope.to.length) {
2185
+ let err = new Error('Draft message has no recipients');
2186
+ err.code = 'DraftHasNoRecipients';
2187
+ err.statusCode = 400;
2188
+ throw err;
2189
+ }
2190
+
2191
+ // Load gateway configuration if specified
2192
+ let gatewayData;
2193
+ if (gateway) {
2194
+ let gatewayObject = new Gateway({ gateway, redis: this.redis, secret: this.secret });
2195
+ try {
2196
+ gatewayData = await gatewayObject.loadGatewayData();
2197
+ } catch (err) {
2198
+ this.logger.info({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2115
2199
  }
2116
2200
  }
2117
2201
 
2118
- return response;
2202
+ // Verify SMTP capability
2203
+ if (!accountData.smtp && !accountData.oauth2 && !gatewayData) {
2204
+ // can not make connection
2205
+ let err = new Error('SMTP configuration not found');
2206
+ err.code = 'SMTPUnavailable';
2207
+ err.statusCode = 404;
2208
+ throw err;
2209
+ }
2210
+
2211
+ return await this.pushMessageToQueue({ data, meta, raw, hasBcc, envelope, messageId, subject, sendAt, deliveryAttempts, gatewayData, draft });
2212
+ }
2213
+
2214
+ /**
2215
+ * Resolves a stored draft message for sending. Implemented by subclasses.
2216
+ * Must verify that the message exists and is a draft, and return its raw content
2217
+ * together with the draft reference that is stored in the queue entry. May also
2218
+ * report the thread the draft belongs to (Gmail).
2219
+ * @param {string} id - API message id of the draft
2220
+ * @param {Object} connectionOptions - Connection options
2221
+ * @returns {Object} { raw: Buffer, draft: { message [, draftId] }, threadId? }
2222
+ */
2223
+ async resolveDraftForSubmit() {
2224
+ let err = new Error('Draft submission not supported for this account type');
2225
+ err.code = 'UnsupportedOperation';
2226
+ err.statusCode = 400;
2227
+ throw err;
2119
2228
  }
2120
2229
 
2121
2230
  /**
@@ -3066,18 +3175,31 @@ class BaseClient {
3066
3175
  }
3067
3176
 
3068
3177
  // Handle sent mail copy to folder
3069
- const shouldCopy = SentMailCopyDecider.shouldCopy({
3178
+ const copyDeciderInputs = {
3070
3179
  accountData,
3071
3180
  data,
3072
3181
  isGmail: this.isGmail,
3073
3182
  isOutlook: this.isOutlook,
3074
3183
  gatewayData
3075
- });
3184
+ };
3185
+ const shouldCopy = SentMailCopyDecider.shouldCopy(copyDeciderInputs);
3076
3186
 
3077
3187
  const connectionOptions = { allowSecondary: true };
3078
3188
 
3079
- if (shouldCopy) {
3080
- await this.uploadToSentFolder(raw, data, queueId, messageId, connectionOptions);
3189
+ const sentCopySucceeded = shouldCopy ? await this.uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) : false;
3190
+
3191
+ // Remove the submitted draft. Delete it permanently when a copy of the message
3192
+ // exists in the Sent Mail folder - either uploaded above, or filed by the provider
3193
+ // itself (Gmail and Outlook store SMTP-sent messages on their own, which is also
3194
+ // why the upload is suppressed for them). Otherwise move the draft to Trash so the
3195
+ // content is not lost
3196
+ if (data.draft) {
3197
+ await this.cleanupSubmittedDraft(data.draft, {
3198
+ permanent: sentCopySucceeded || SentMailCopyDecider.providerSavesSentCopy(copyDeciderInputs),
3199
+ queueId,
3200
+ messageId,
3201
+ connectionOptions
3202
+ });
3081
3203
  }
3082
3204
 
3083
3205
  // Update reference flags if needed
@@ -3118,6 +3240,7 @@ class BaseClient {
3118
3240
  * @param {string} queueId - Queue ID for logging
3119
3241
  * @param {string} messageId - Message ID for logging
3120
3242
  * @param {Object} connectionOptions - IMAP connection options
3243
+ * @returns {boolean} Whether the message was stored in the Sent folder
3121
3244
  */
3122
3245
  async uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) {
3123
3246
  try {
@@ -3139,10 +3262,32 @@ class BaseClient {
3139
3262
  this.logger.error({ msg: 'IDLE error', err });
3140
3263
  });
3141
3264
  }
3265
+
3266
+ return true;
3142
3267
  }
3143
3268
  } catch (err) {
3144
3269
  this.logger.error({ msg: 'Failed to upload Sent mail', queueId, messageId, err });
3145
3270
  }
3271
+
3272
+ return false;
3273
+ }
3274
+
3275
+ /**
3276
+ * Removes a draft message after it was successfully submitted. Failures are logged
3277
+ * only - the message has already been sent, so the job must not fail or retry.
3278
+ * @param {Object} draft - Draft reference from the queue entry ({ message })
3279
+ * @param {Object} options
3280
+ * @param {boolean} options.permanent - Delete permanently instead of moving to Trash
3281
+ * @param {string} options.queueId - Queue ID for logging
3282
+ * @param {string} options.messageId - Message ID for logging
3283
+ * @param {Object} options.connectionOptions - IMAP connection options
3284
+ */
3285
+ async cleanupSubmittedDraft(draft, { permanent, queueId, messageId, connectionOptions }) {
3286
+ try {
3287
+ await this.deleteMessage(draft.message, permanent, connectionOptions);
3288
+ } catch (err) {
3289
+ this.logger.error({ msg: 'Failed to remove submitted draft', queueId, messageId, draft: draft.message, err });
3290
+ }
3146
3291
  }
3147
3292
 
3148
3293
  /**
@@ -66,4 +66,19 @@ function buildSendRequest(raw, threadId) {
66
66
  };
67
67
  }
68
68
 
69
- module.exports = { buildSendRequest, JSON_SEND_LIMIT };
69
+ /**
70
+ * Builds the Gmail request that sends an existing draft resource. Gmail moves the message
71
+ * from Drafts to Sent itself, so no cleanup call is needed afterwards.
72
+ *
73
+ * @param {String} draftId - Gmail draft resource id (NOT the message id)
74
+ * @returns {Object} { targetEndpoint, contentType, payload } - endpoint is relative to GMAIL_API_BASE
75
+ */
76
+ function buildDraftSendRequest(draftId) {
77
+ return {
78
+ targetEndpoint: `/gmail/v1/users/me/drafts/send`,
79
+ contentType: 'application/json',
80
+ payload: { id: draftId }
81
+ };
82
+ }
83
+
84
+ module.exports = { buildSendRequest, buildDraftSendRequest, JSON_SEND_LIMIT };