@postalsys/ee-client 1.6.0 → 1.7.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 (4) hide show
  1. package/README.md +12 -1
  2. package/index.d.ts +23 -0
  3. package/index.js +238 -8
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -181,6 +181,16 @@ Send a plain-text email. `to` may be:
181
181
 
182
182
  Resolves to EmailEngine's submit response.
183
183
 
184
+ ### `saveDraft(to?, subject?, text?): Promise<object>`
185
+
186
+ Store a plain-text message as a draft instead of sending it (`POST /v1/account/{account}/message`). The message is uploaded to the account's Drafts special-use folder with the `\Draft` flag set and the account's own name and address as the sender, so it can later be delivered with `submitDraft()`. `to` accepts the same values as `sendMessage()` and may be omitted for a draft without recipients. Resolves to EmailEngine's upload response (`{ id, path, uid, ... }`).
187
+
188
+ ### `submitDraft(messageId: string, options?: SubmitDraftOptions): Promise<object>`
189
+
190
+ Send an existing draft message as-is (`POST /v1/account/{account}/message/{message}/submit`). 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). The provider removes the draft once it has been sent and files the sent copy into the Sent Mail folder. Requires EmailEngine v2.76.0 or later.
191
+
192
+ The optional `options` object mirrors the API's SubmitDraft payload (`envelope`, `copy`, `sentMailPath`, `sendAt`, ...). Resolves to EmailEngine's submit response (`{ response, messageId, queueId, sendAt }`).
193
+
184
194
  ### `downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>`
185
195
 
186
196
  Browser only. Fetch an attachment and trigger a download, using the filename from the `Content-Disposition` header when available.
@@ -204,8 +214,9 @@ When a `container` is provided the client builds a full webmail interface:
204
214
  - Folder tree with special-folder ordering (Inbox, Drafts, Sent, Trash, Junk, Archive) and nested folders
205
215
  - Paginated message list with a selectable page size (persisted to `localStorage`)
206
216
  - Message viewer with mark read/unread, delete, move-to-folder, download original, and attachment downloads
217
+ - Draft messages show a "Send Draft" button that submits the stored draft for delivery after confirmation (requires EmailEngine v2.76.0 or later; editing the draft first is not supported)
207
218
  - Quoted thread history collapsed behind a "Show quoted text" control
208
- - Compose modal (floating button) for sending plain-text mail
219
+ - Compose modal (floating button) for sending plain-text mail, with a Save Draft option that stores the message in the Drafts folder instead of sending it
209
220
  - Dark mode toggle with the preference persisted to `localStorage`
210
221
 
211
222
  ### Quoted thread history
package/index.d.ts CHANGED
@@ -46,6 +46,9 @@ export interface Message {
46
46
  cc?: EmailAddress[];
47
47
  date: string;
48
48
  unseen: boolean;
49
+ draft?: boolean;
50
+ /** Special-use flag of the folder the message is stored in, e.g. "\\Drafts" */
51
+ messageSpecialUse?: string;
49
52
  intro?: string;
50
53
  text?: MessageText;
51
54
  attachments?: Attachment[];
@@ -59,6 +62,24 @@ export interface MessageListResponse {
59
62
 
60
63
  export type SendRecipient = string | EmailAddress;
61
64
 
65
+ /**
66
+ * Optional payload for `submitDraft()`. Mirrors the SubmitDraft schema of the
67
+ * EmailEngine API; all fields are optional and most only apply to SMTP deliveries.
68
+ */
69
+ export interface SubmitDraftOptions {
70
+ /** SMTP envelope override; derived from the draft's headers when omitted */
71
+ envelope?: { from?: string; to?: string[] };
72
+ /** Copy the sent message to the Sent Mail folder (SMTP only; account default when unset) */
73
+ copy?: boolean | null;
74
+ /** Upload the sent message to this folder instead of the default Sent Mail folder (SMTP only) */
75
+ sentMailPath?: string;
76
+ /** Schedule the send instead of sending immediately */
77
+ sendAt?: string | Date;
78
+ deliveryAttempts?: number;
79
+ gateway?: string;
80
+ [key: string]: unknown;
81
+ }
82
+
62
83
  /**
63
84
  * Custom dialog handler. Invoked by the client as
64
85
  * `(message, title, cancelText, okText)`; `cancelText` is `null` for alerts.
@@ -113,6 +134,8 @@ export declare class EmailEngineClient {
113
134
  deleteMessage(messageId: string): Promise<boolean>;
114
135
  moveMessage(messageId: string, targetPath: string): Promise<boolean>;
115
136
  sendMessage(to: SendRecipient | SendRecipient[], subject: string, text: string): Promise<any>;
137
+ saveDraft(to?: SendRecipient | SendRecipient[] | null, subject?: string, text?: string): Promise<any>;
138
+ submitDraft(messageId: string, options?: SubmitDraftOptions | null): Promise<any>;
116
139
  downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>;
117
140
  downloadOriginalMessage(messageId: string, subject?: string): Promise<void>;
118
141
  formatDate(dateStr: string): string;
package/index.js CHANGED
@@ -310,14 +310,25 @@ export class EmailEngineClient {
310
310
  }
311
311
  }
312
312
 
313
+ _normalizeRecipients(to) {
314
+ return Array.isArray(to)
315
+ ? to.map(addr => (typeof addr === 'string' ? { address: addr } : addr))
316
+ : [typeof to === 'string' ? { address: to } : to];
317
+ }
318
+
319
+ // Account details (name, email address) fetched once and cached for the lifetime
320
+ // of the instance; used as the From identity of saved drafts.
321
+ async _getAccountInfo() {
322
+ if (!this._accountInfo) {
323
+ this._accountInfo = await this.apiRequest('GET', `/v1/account/${this.account}`);
324
+ }
325
+ return this._accountInfo;
326
+ }
327
+
313
328
  async sendMessage(to, subject, text) {
314
329
  try {
315
- const toAddresses = Array.isArray(to)
316
- ? to.map(addr => (typeof addr === 'string' ? { address: addr } : addr))
317
- : [typeof to === 'string' ? { address: to } : to];
318
-
319
330
  const messageData = {
320
- to: toAddresses,
331
+ to: this._normalizeRecipients(to),
321
332
  subject: subject,
322
333
  text: text
323
334
  };
@@ -332,6 +343,77 @@ export class EmailEngineClient {
332
343
  }
333
344
  }
334
345
 
346
+ async saveDraft(to, subject, text) {
347
+ try {
348
+ if (!this.folders.length) {
349
+ await this.loadFolders();
350
+ }
351
+ const draftsFolder = this.folders.find(f => f.specialUse === '\\Drafts');
352
+ if (!draftsFolder) {
353
+ throw new Error('No Drafts folder found for this account');
354
+ }
355
+
356
+ const messageData = {
357
+ path: draftsFolder.path,
358
+ flags: ['\\Draft'],
359
+ subject: subject,
360
+ text: text
361
+ };
362
+
363
+ const recipients = to ? this._normalizeRecipients(to) : [];
364
+ if (recipients.length) {
365
+ messageData.to = recipients;
366
+ }
367
+
368
+ // The upload endpoint does not add a From header on its own, but the draft
369
+ // needs one to be deliverable later - use the account's own identity.
370
+ try {
371
+ const accountInfo = await this._getAccountInfo();
372
+ if (accountInfo && accountInfo.email) {
373
+ messageData.from = { name: accountInfo.name || '', address: accountInfo.email };
374
+ }
375
+ } catch (err) {
376
+ // Non-fatal: the draft is saved without a From header
377
+ }
378
+
379
+ const response = await this.apiRequest('POST', `/v1/account/${this.account}/message`, messageData);
380
+ return response;
381
+ } catch (error) {
382
+ console.error('Failed to save draft:', error);
383
+ this._parseApiError(error);
384
+ throw error;
385
+ }
386
+ }
387
+
388
+ async submitDraft(messageId, options = null) {
389
+ try {
390
+ const response = await this.apiRequest(
391
+ 'POST',
392
+ `/v1/account/${this.account}/message/${messageId}/submit`,
393
+ options
394
+ );
395
+ return response;
396
+ } catch (error) {
397
+ console.error('Failed to submit draft:', error);
398
+ this._parseApiError(error);
399
+ throw error;
400
+ }
401
+ }
402
+
403
+ // A message counts as a draft when the server marks it as one (the \Draft flag on IMAP,
404
+ // the DRAFT label on Gmail, a draft message on MS Graph) or when it sits in the Drafts
405
+ // special-use folder.
406
+ _isDraftMessage(msg) {
407
+ if (!msg) {
408
+ return false;
409
+ }
410
+ if (msg.draft || msg.messageSpecialUse === '\\Drafts') {
411
+ return true;
412
+ }
413
+ const folder = this.folders.find(f => f.path === this.currentFolder);
414
+ return !!(folder && folder.specialUse === '\\Drafts');
415
+ }
416
+
335
417
  _parseApiError(error) {
336
418
  try {
337
419
  // If error has response text, try to parse it
@@ -368,7 +450,10 @@ export class EmailEngineClient {
368
450
  return mainMessage;
369
451
  }
370
452
 
371
- // Fallback to generic error message
453
+ // No field-level details - fall back to the API-provided message, then to a generic one
454
+ if (error.details && typeof error.details.message === 'string' && error.details.message) {
455
+ return error.details.message;
456
+ }
372
457
  return 'Failed to send email. Please check your input and try again.';
373
458
  }
374
459
 
@@ -1095,11 +1180,34 @@ export class EmailEngineClient {
1095
1180
  font-size: 14px;
1096
1181
  cursor: pointer;
1097
1182
  }
1098
-
1183
+
1099
1184
  .ee-compose-cancel:hover {
1100
1185
  background: #545b62;
1101
1186
  }
1102
1187
 
1188
+ .ee-compose-save-draft {
1189
+ background: transparent;
1190
+ color: #007bff;
1191
+ border: 1px solid #007bff;
1192
+ padding: 10px 20px;
1193
+ border-radius: 4px;
1194
+ font-size: 14px;
1195
+ font-weight: 500;
1196
+ cursor: pointer;
1197
+ }
1198
+
1199
+ .ee-compose-save-draft:hover:not(:disabled) {
1200
+ background: #007bff;
1201
+ color: white;
1202
+ }
1203
+
1204
+ .ee-compose-save-draft:disabled {
1205
+ color: #6c757d;
1206
+ border-color: #6c757d;
1207
+ cursor: not-allowed;
1208
+ opacity: 0.6;
1209
+ }
1210
+
1103
1211
  /* Dark mode toggle button */
1104
1212
  .ee-dark-mode-toggle {
1105
1213
  position: absolute;
@@ -1314,6 +1422,16 @@ export class EmailEngineClient {
1314
1422
  .ee-dark-mode .ee-compose-cancel:hover {
1315
1423
  background: #555;
1316
1424
  }
1425
+
1426
+ .ee-dark-mode .ee-compose-save-draft {
1427
+ color: #66b2ff;
1428
+ border-color: #66b2ff;
1429
+ }
1430
+
1431
+ .ee-dark-mode .ee-compose-save-draft:hover:not(:disabled) {
1432
+ background: #66b2ff;
1433
+ color: #1a1a1a;
1434
+ }
1317
1435
  `;
1318
1436
  document.head.appendChild(style);
1319
1437
  this._styleElement = style;
@@ -1564,8 +1682,10 @@ export class EmailEngineClient {
1564
1682
 
1565
1683
  const msg = this.currentMessage;
1566
1684
  const isUnseen = msg.unseen;
1685
+ const isDraft = this._isDraftMessage(msg);
1567
1686
  const html = `
1568
1687
  <div class="ee-message-actions">
1688
+ ${isDraft ? '<button class="ee-button" data-action="send-draft">Send Draft</button>' : ''}
1569
1689
  <button class="ee-button" data-action="toggle-read">Mark as ${isUnseen ? 'seen' : 'unseen'}</button>
1570
1690
  <button class="ee-button" data-action="delete">Delete</button>
1571
1691
  <button class="ee-button" data-action="download-original">Download Original</button>
@@ -1640,6 +1760,41 @@ export class EmailEngineClient {
1640
1760
 
1641
1761
  this._labelCollapsedThreads(viewer);
1642
1762
 
1763
+ const sendDraftButton = viewer.querySelector('[data-action="send-draft"]');
1764
+ if (sendDraftButton) {
1765
+ sendDraftButton.addEventListener('click', async () => {
1766
+ const result = await this.confirmMethod(
1767
+ 'Send this draft to its recipients now? The draft is removed from the Drafts folder once it has been sent.',
1768
+ 'Send Draft',
1769
+ 'Cancel',
1770
+ 'Send'
1771
+ );
1772
+ if (!result) {
1773
+ return;
1774
+ }
1775
+
1776
+ const originalText = sendDraftButton.textContent;
1777
+ sendDraftButton.disabled = true;
1778
+ sendDraftButton.textContent = 'Sending...';
1779
+
1780
+ try {
1781
+ await this.submitDraft(msg.id);
1782
+ await this.alertMethod('Draft queued for delivery.', 'Success', null, 'OK');
1783
+ // Refresh the folder view - the provider removes the draft once it is sent,
1784
+ // immediately for Gmail and MS Graph, after SMTP delivery for IMAP accounts.
1785
+ if (!this._destroyed && this.currentFolder) {
1786
+ await this.loadMessages(this.currentFolder);
1787
+ }
1788
+ } catch (error) {
1789
+ console.error('Failed to send draft:', error);
1790
+ const errorMessage = this._formatSendError(error);
1791
+ await this.alertMethod(errorMessage, 'Send Error', null, 'OK');
1792
+ sendDraftButton.disabled = false;
1793
+ sendDraftButton.textContent = originalText;
1794
+ }
1795
+ });
1796
+ }
1797
+
1643
1798
  viewer.querySelector('[data-action="toggle-read"]').addEventListener('click', () => {
1644
1799
  const currentlyUnseen = msg.unseen;
1645
1800
  this.markAsRead(msg.id, currentlyUnseen);
@@ -1754,6 +1909,7 @@ export class EmailEngineClient {
1754
1909
  </form>
1755
1910
  <div class="ee-compose-actions">
1756
1911
  <button type="button" class="ee-compose-cancel">Cancel</button>
1912
+ <button type="button" class="ee-compose-save-draft">Save Draft</button>
1757
1913
  <button type="button" class="ee-compose-send">Send</button>
1758
1914
  </div>
1759
1915
  </div>
@@ -1776,6 +1932,7 @@ export class EmailEngineClient {
1776
1932
  const modal = this.container.querySelector('.ee-compose-modal');
1777
1933
  const closeButton = this.container.querySelector('.ee-compose-close');
1778
1934
  const cancelButton = this.container.querySelector('.ee-compose-cancel');
1935
+ const saveDraftButton = this.container.querySelector('.ee-compose-save-draft');
1779
1936
  const sendButton = this.container.querySelector('.ee-compose-send');
1780
1937
  const form = this.container.querySelector('.ee-compose-form');
1781
1938
 
@@ -1811,6 +1968,52 @@ export class EmailEngineClient {
1811
1968
  };
1812
1969
  document.addEventListener('keydown', this._composeKeydownHandler);
1813
1970
 
1971
+ // Save the composed message as a draft instead of sending it
1972
+ saveDraftButton.addEventListener('click', async () => {
1973
+ const formData = new FormData(form);
1974
+ const to = formData.get('to').trim();
1975
+ const subject = formData.get('subject').trim();
1976
+ const message = formData.get('message').trim();
1977
+
1978
+ if (!to && !subject && !message) {
1979
+ modal.classList.remove('show');
1980
+ await this.alertMethod(
1981
+ 'Nothing to save - fill in at least one field first.',
1982
+ 'Validation Error',
1983
+ null,
1984
+ 'OK'
1985
+ );
1986
+ modal.classList.add('show');
1987
+ setTimeout(() => form.querySelector('input[name="to"]').focus(), 100);
1988
+ return;
1989
+ }
1990
+
1991
+ const originalText = saveDraftButton.textContent;
1992
+ saveDraftButton.disabled = true;
1993
+ saveDraftButton.textContent = 'Saving...';
1994
+
1995
+ try {
1996
+ const response = await this.saveDraft(to || null, subject, message);
1997
+ closeModal();
1998
+ await this.alertMethod('Draft saved to the Drafts folder.', 'Success', null, 'OK');
1999
+ // Refresh the list when the user is looking at the Drafts folder
2000
+ if (!this._destroyed && response && response.path && this.currentFolder === response.path) {
2001
+ await this.loadMessages(this.currentFolder);
2002
+ }
2003
+ } catch (error) {
2004
+ console.error('Failed to save draft:', error);
2005
+ // Close modal before showing error alert, then reopen with preserved values
2006
+ modal.classList.remove('show');
2007
+ const errorMessage = this._formatSendError(error);
2008
+ await this.alertMethod(errorMessage, 'Save Error', null, 'OK');
2009
+ modal.classList.add('show');
2010
+ setTimeout(() => form.querySelector('input[name="to"]').focus(), 100);
2011
+ } finally {
2012
+ saveDraftButton.disabled = false;
2013
+ saveDraftButton.textContent = originalText;
2014
+ }
2015
+ });
2016
+
1814
2017
  // Send email
1815
2018
  sendButton.addEventListener('click', async () => {
1816
2019
  const formData = new FormData(form);
@@ -1889,6 +2092,17 @@ export class EmailEngineClient {
1889
2092
  const buttonSize = 56; // Button width/height
1890
2093
  const margin = 20; // Desired margin from edges
1891
2094
 
2095
+ // A hidden container (display: none) reports a zero-size rect; positioning
2096
+ // against it would push the fixed-position button off-screen. Hide the button
2097
+ // instead and let the ResizeObserver below restore it once the container is
2098
+ // shown - hosts often create the client inside a container that is only made
2099
+ // visible afterwards.
2100
+ if (!containerRect.width && !containerRect.height) {
2101
+ composeButton.style.display = 'none';
2102
+ return;
2103
+ }
2104
+ composeButton.style.display = '';
2105
+
1892
2106
  // Calculate the ideal position (bottom-right of container with margin)
1893
2107
  const idealBottom = window.innerHeight - containerRect.bottom + margin;
1894
2108
  const idealRight = window.innerWidth - containerRect.right + margin;
@@ -1917,10 +2131,26 @@ export class EmailEngineClient {
1917
2131
  window.addEventListener('scroll', updateWithThrottle);
1918
2132
  window.addEventListener('resize', updateWithThrottle);
1919
2133
 
1920
- // Store cleanup function for potential future use
2134
+ // Reposition when the container itself changes size or becomes visible - window
2135
+ // scroll/resize events never fire for those. Calls the update directly instead of
2136
+ // the throttled wrapper: the throttle drops trailing calls, which would leave the
2137
+ // button hidden when the observer fires twice in quick succession (initial
2138
+ // notification followed by the container being shown). Observer callbacks are
2139
+ // already batched per frame by the browser, so there is nothing to throttle.
2140
+ let resizeObserver = null;
2141
+ if (typeof ResizeObserver !== 'undefined') {
2142
+ resizeObserver = new ResizeObserver(updateButtonPosition);
2143
+ resizeObserver.observe(this.container);
2144
+ }
2145
+
2146
+ // Cleanup runs from destroy()
1921
2147
  this._composeButtonCleanup = () => {
1922
2148
  window.removeEventListener('scroll', updateWithThrottle);
1923
2149
  window.removeEventListener('resize', updateWithThrottle);
2150
+ if (resizeObserver) {
2151
+ resizeObserver.disconnect();
2152
+ resizeObserver = null;
2153
+ }
1924
2154
  };
1925
2155
  }
1926
2156
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postalsys/ee-client",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "EmailEngine client library for browser and Node.js applications",
5
5
  "main": "index.js",
6
6
  "module": "index.js",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "eslint": "^8.57.1",
46
- "prettier": "^3.9.5"
46
+ "prettier": "^3.9.6"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "node-fetch": "^3.0.0"