diff --git a/README.md b/README.md
index 9300447..723cfa5 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,12 @@
# ep-mail
-An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
+An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, snooze reminders, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
## Desktop app
The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. The app uses required STARTTLS for IMAP port 143 and SMTP port 587 and stores the password encrypted through the operating system credential store. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
-The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab.
+The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
## Android app
diff --git a/TODO.md b/TODO.md
index 1c5a145..ad0a91d 100644
--- a/TODO.md
+++ b/TODO.md
@@ -5,8 +5,19 @@
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
- [ ] Add Android support for the mail app.
+- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
- [x] Show the app version after **ep-mail** in the window title.
+## Mail workflow
+
+- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
+- [ ] Add Undo Send and scheduled sending.
+- [ ] Improve mail search with sender, subject, date, folder, and attachment filters.
+- [ ] Add offline reading and drafts, with queued actions when connectivity returns.
+- [ ] Add user-configurable rules to sort, archive, label, or flag messages automatically.
+- [ ] Add per-account signatures, notification preferences, and sync settings.
+- [ ] Block remote images by default and let users load them per message.
+
## Mail security
- [ ] Add support for encrypting and decrypting mail with private/public keys or a suitable standard. Decide on the encryption format, key storage and exchange flow, and compatibility requirements before implementation.
diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt
index cb73bb4..da108c2 100644
--- a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt
+++ b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt
@@ -132,6 +132,61 @@ internal object AndroidAccountVault {
}
}
+ @Synchronized
+ fun setSnooze(id: String, uid: Long, folder: String, dueAt: Long?, subject: String) {
+ val store = read()
+ val accounts = store.optJSONArray("accounts") ?: return
+ for (index in 0 until accounts.length()) {
+ val account = accounts.getJSONObject(index)
+ if (account.optString("id") != id) continue
+ val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
+ val updated = JSONArray()
+ for (itemIndex in 0 until previous.length()) {
+ val item = previous.getJSONObject(itemIndex)
+ if (item.optLong("uid") != uid || item.optString("folder") != folder) updated.put(item)
+ }
+ if (dueAt != null) {
+ updated.put(JSONObject()
+ .put("uid", uid)
+ .put("folder", folder)
+ .put("dueAt", dueAt)
+ .put("subject", subject.take(200)))
+ }
+ account.put("snoozedMessages", updated)
+ write(store)
+ return
+ }
+ }
+
+ @Synchronized
+ fun takeDueSnoozes(id: String, now: Long): JSONArray {
+ val store = read()
+ val accounts = store.optJSONArray("accounts") ?: return JSONArray()
+ for (index in 0 until accounts.length()) {
+ val account = accounts.getJSONObject(index)
+ if (account.optString("id") != id) continue
+ val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
+ val remaining = JSONArray()
+ val due = JSONArray()
+ for (itemIndex in 0 until previous.length()) {
+ val item = previous.getJSONObject(itemIndex)
+ if (item.optLong("dueAt") <= now) {
+ due.put(JSONObject(item.toString())
+ .put("accountId", id)
+ .put("email", account.optString("email")))
+ } else {
+ remaining.put(item)
+ }
+ }
+ if (due.length() > 0) {
+ account.put("snoozedMessages", remaining)
+ write(store)
+ }
+ return due
+ }
+ return JSONArray()
+ }
+
fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray {
val result = JSONArray()
for (index in 0 until accounts.length()) {
diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt
index c7288ab..faeb710 100644
--- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt
+++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt
@@ -57,8 +57,9 @@ internal object AndroidMailService {
JSONObject().put("mailbox", "INBOX").put("messages", count)
}
- fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject =
- withStore(account) { _, store ->
+ fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject {
+ if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
+ return withStore(account) { _, store ->
val folder = resolveFolder(store, requestedFolder)
if (folder == null) return@withStore JSONObject()
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
@@ -73,7 +74,15 @@ internal object AndroidMailService {
val first = (end - 19).coerceAtLeast(1)
val result = JSONArray()
val batch = folder.getMessages(first, end).reversed()
+ val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
for (message in batch) {
+ val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
+ val isSnoozed = (0 until snoozed.length()).any { index ->
+ val item = snoozed.getJSONObject(index)
+ item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
+ item.optLong("dueAt") > System.currentTimeMillis()
+ }
+ if (isSnoozed) continue
result.put(messageJson(folder, message, requestedFolder))
}
JSONObject().put("messages", result).put("total", total)
@@ -82,13 +91,44 @@ internal object AndroidMailService {
folder.close(false)
}
}
+ }
+
+ private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
+ withStore(account) { _, store ->
+ val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
+ val pending = (0 until snoozes.length())
+ .map { snoozes.getJSONObject(it) }
+ .filter { it.optLong("dueAt") > System.currentTimeMillis() }
+ .sortedBy { it.optLong("dueAt") }
+ val page = pending.drop(offset.coerceAtLeast(0)).take(20)
+ val messages = JSONArray()
+ for (snooze in page) {
+ val sourceFolder = snooze.optString("folder", "Inbox")
+ val folder = resolveFolder(store, sourceFolder) ?: continue
+ folder.open(Folder.READ_ONLY)
+ try {
+ val message = (folder as? UIDFolder)?.getMessageByUID(snooze.optLong("uid")) ?: continue
+ messages.put(messageJson(folder, message, "Snoozed")
+ .put("sourceFolder", sourceFolder)
+ .put("snoozedUntil", snooze.optLong("dueAt")))
+ } finally {
+ folder.close(false)
+ }
+ }
+ JSONObject()
+ .put("messages", messages)
+ .put("total", pending.size)
+ .put("start", if (page.isEmpty()) 0 else offset + 1)
+ .put("end", offset + messages.length())
+ .put("folder", "Snoozed")
+ }
fun updateMessage(account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store ->
val uid = input.optLong("uid")
require(uid > 0) { "That message could not be identified." }
val action = input.optString("action")
- require(action in setOf("star", "unread", "archive", "delete")) { "That mail action is not supported." }
+ require(action in setOf("star", "unread", "archive", "delete", "inbox")) { "That mail action is not supported." }
val source = resolveFolder(store, input.optString("folder", "Inbox"))
?: throw IllegalStateException("That mail folder could not be found.")
var expungeDeleted = false
@@ -99,18 +139,38 @@ internal object AndroidMailService {
when (action) {
"star" -> message.setFlag(Flags.Flag.FLAGGED, input.optBoolean("enabled"))
"unread" -> message.setFlag(Flags.Flag.SEEN, !input.optBoolean("enabled"))
- "archive", "delete" -> {
- expungeDeleted = true
- val targetName = if (action == "archive") "Archive" else "Trash"
+ "archive", "delete", "inbox" -> {
+ val targetName = when (action) {
+ "archive" -> "Archive"
+ "delete" -> "Trash"
+ else -> "Inbox"
+ }
val target = resolveFolder(store, targetName) ?: store.getFolder(targetName)
if (!target.exists()) target.create(Folder.HOLDS_MESSAGES)
- source.copyMessages(arrayOf(message), target)
- message.setFlag(Flags.Flag.DELETED, true)
+ if (source.fullName == target.fullName) {
+ if (action == "delete") {
+ expungeDeleted = true
+ message.setFlag(Flags.Flag.DELETED, true)
+ }
+ } else {
+ expungeDeleted = true
+ source.copyMessages(arrayOf(message), target)
+ message.setFlag(Flags.Flag.DELETED, true)
+ }
}
}
} finally {
source.close(expungeDeleted)
}
+ if (action == "archive" || action == "delete" || action == "inbox") {
+ AndroidAccountVault.setSnooze(
+ account.optString("id"),
+ uid,
+ input.optString("folder", "Inbox"),
+ null,
+ ""
+ )
+ }
JSONObject().put("ok", true)
}
diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt
index 9ab1209..8bee720 100644
--- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt
+++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt
@@ -159,6 +159,49 @@ class EpMailPlugin : Plugin() {
}
}
+ @PluginMethod
+ fun setSnooze(call: PluginCall) {
+ try {
+ val account = AndroidAccountVault.account()
+ ?: throw IllegalStateException("Add a mail account before setting a reminder.")
+ val uid = call.getLong("uid") ?: throw IllegalArgumentException("That message could not be identified.")
+ require(uid > 0) { "That message could not be identified." }
+ val folder = call.getString("sourceFolder") ?: call.getString("folder") ?: "Inbox"
+ require(folder in setOf("Inbox", "Sent", "Archive", "Trash")) { "That mailbox cannot be snoozed." }
+ val dueAt = call.getLong("dueAt")
+ if (dueAt != null && dueAt <= System.currentTimeMillis()) {
+ throw IllegalArgumentException("Choose a reminder time in the future.")
+ }
+ AndroidAccountVault.setSnooze(
+ account.optString("id"),
+ uid,
+ folder,
+ dueAt,
+ call.getString("subject").orEmpty()
+ )
+ val update = JSONObject()
+ .put("accountId", account.optString("id"))
+ .put("foldersChanged", JSONArray().put("Snoozed").put(folder))
+ context.sendBroadcast(Intent(MailIdleService.ACTION_MAIL_SYNC)
+ .setPackage(context.packageName)
+ .putExtra(MailIdleService.EXTRA_SYNC_UPDATE, update.toString()))
+ MailIdleService.start(context)
+ call.resolve(JSObject().put("ok", true).put("snoozed", dueAt != null))
+ } catch (error: Exception) {
+ call.reject(error.message ?: "Could not set the reminder.")
+ }
+ }
+
+ @PluginMethod
+ fun checkSnoozeReminders(call: PluginCall) {
+ try {
+ MailIdleService.checkSnoozeReminders(context)
+ call.resolve()
+ } catch (error: Exception) {
+ call.reject(error.message ?: "Could not check mail reminders.")
+ }
+ }
+
@PluginMethod
fun saveAttachment(call: PluginCall) {
try {
diff --git a/android/app/src/main/java/studio/daybreak/mail/MailFallbackWorker.kt b/android/app/src/main/java/studio/daybreak/mail/MailFallbackWorker.kt
index e8bfe43..8331d32 100644
--- a/android/app/src/main/java/studio/daybreak/mail/MailFallbackWorker.kt
+++ b/android/app/src/main/java/studio/daybreak/mail/MailFallbackWorker.kt
@@ -14,6 +14,7 @@ class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worke
override fun doWork(): Result {
return try {
AndroidAccountVault.initialize(applicationContext)
+ MailIdleService.checkSnoozeReminders(applicationContext)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
diff --git a/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt
index fccbce5..abcd2cc 100644
--- a/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt
+++ b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt
@@ -181,6 +181,21 @@ class MailIdleService : Service() {
MailFallbackWorker.cancel(context)
}
+ fun checkSnoozeReminders(context: Context) {
+ AndroidAccountVault.initialize(context)
+ val accounts = AndroidAccountVault.accounts()
+ for (index in 0 until accounts.length()) {
+ val account = accounts.getJSONObject(index)
+ val reminders = AndroidAccountVault.takeDueSnoozes(
+ account.optString("id"),
+ System.currentTimeMillis()
+ )
+ for (reminderIndex in 0 until reminders.length()) {
+ notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
+ }
+ }
+ }
+
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
if (count <= 0) return
val appContext = context.applicationContext
@@ -223,5 +238,54 @@ class MailIdleService : Service() {
android.util.Log.w(TAG, "Notification permission is unavailable", error)
}
}
+
+ fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
+ val appContext = context.applicationContext
+ val email = account.optString("email")
+ val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
+ manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
+ manager.createNotificationChannel(NotificationChannel(
+ MAIL_CHANNEL_ID,
+ "Mail reminders",
+ NotificationManager.IMPORTANCE_DEFAULT
+ ))
+ }
+ val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
+ .setSmallIcon(android.R.drawable.ic_dialog_email)
+ .setContentTitle("Mail reminder")
+ .setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" })
+ .setAutoCancel(true)
+ .setPriority(NotificationCompat.PRIORITY_DEFAULT)
+ .setContentIntent(appPendingIntentFor(appContext))
+ .build()
+ try {
+ NotificationManagerCompat.from(appContext).notify(
+ (email + reminder.optLong("uid")).hashCode(),
+ notification
+ )
+ } catch (error: SecurityException) {
+ android.util.Log.w(TAG, "Reminder notification permission is unavailable", error)
+ }
+ val update = JSONObject()
+ .put("accountId", account.optString("id"))
+ .put("snoozeReminder", true)
+ .put("foldersChanged", org.json.JSONArray()
+ .put("Snoozed")
+ .put(reminder.optString("folder", "Inbox")))
+ appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
+ .setPackage(appContext.packageName)
+ .putExtra(EXTRA_SYNC_UPDATE, update.toString()))
+ }
+
+ private fun appPendingIntentFor(context: Context): PendingIntent {
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
+ ?: Intent(context, MainActivity::class.java)
+ intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ return PendingIntent.getActivity(
+ context, 0, intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ }
}
}
diff --git a/desktop/main.cjs b/desktop/main.cjs
index 64e3143..9cb2ad6 100644
--- a/desktop/main.cjs
+++ b/desktop/main.cjs
@@ -13,9 +13,11 @@ const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-account
const backgroundSyncIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2;
const backgroundIdleConcurrency = 2;
+const snoozeCheckIntervalMs = 30 * 1000;
let accountStoreQueue = Promise.resolve();
let backgroundSyncInProgress = false;
let backgroundSyncRequested = false;
+let snoozeReminderCheckInProgress = false;
const backgroundSyncGenerations = new Map();
const backgroundSyncFailures = new Map();
const flagSnapshots = new Map();
@@ -41,6 +43,48 @@ function sendMailSyncUpdate(update) {
}
}
+async function checkSnoozeReminders() {
+ if (snoozeReminderCheckInProgress) return;
+ snoozeReminderCheckInProgress = true;
+ try {
+ const current = await readAccountStore();
+ if (!current?.accounts.some(account =>
+ (account.snoozedMessages || []).some(item => Number(item.dueAt) <= Date.now())
+ )) return;
+ const due = await updateAccountStore(store => {
+ const reminders = [];
+ for (const account of store.accounts) {
+ const snoozes = account.snoozedMessages || [];
+ const remaining = [];
+ for (const item of snoozes) {
+ if (Number(item.dueAt) <= Date.now()) reminders.push({ accountId: account.id, email: account.email, ...item });
+ else remaining.push(item);
+ }
+ account.snoozedMessages = remaining;
+ }
+ return reminders;
+ });
+ for (const reminder of due) {
+ if (Notification.isSupported()) {
+ new Notification({
+ title: 'Mail reminder',
+ body: `${reminder.subject || 'A message'}${reminder.email ? ` · ${reminder.email}` : ''}`
+ }).show();
+ }
+ sendMailSyncUpdate({
+ accountId: reminder.accountId,
+ snoozeReminder: true,
+ snoozedFolder: reminder.folder,
+ foldersChanged: ['Snoozed', reminder.folder]
+ });
+ }
+ } catch (error) {
+ console.error('Could not process snooze reminders:', error);
+ } finally {
+ snoozeReminderCheckInProgress = false;
+ }
+}
+
function requestBackgroundSync(accountId = null, force = false) {
if (accountId) {
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
@@ -326,6 +370,7 @@ async function folderPath(client, folder, createIfMissing = false) {
}
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
+ if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
const client = imapClient(account);
try {
await client.connect();
@@ -342,43 +387,85 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
internalDate: true,
source: true
});
+ const snoozed = new Set((account.snoozedMessages || [])
+ .filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
+ .map(item => Number(item.uid)));
const messages = [];
for (const item of fetched.reverse()) {
- if (!item.source) continue;
- const parsed = await simpleParser(item.source);
- const sender = parsed.from?.value?.[0];
- const bodyText = String(parsed.text || '').replace(/\r/g, '').trim();
- const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
- const date = parsed.date || item.internalDate || new Date();
- messages.push({
- id: Number(item.uid),
- initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
- color: '#dce6df',
- sender: sender?.name || sender?.address || 'Unknown sender',
- email: sender?.address || '',
- subject: parsed.subject || '(no subject)',
- snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
- time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
- date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
- unread: !item.flags?.has('\\Seen'),
- star: item.flags?.has('\\Flagged') || false,
- tags: [folder],
- sent: folder === 'Sent',
- archived: folder === 'Archive',
- deleted: folder === 'Trash',
- body,
- uid: Number(item.uid),
- attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
- attachment: parsed.attachments?.[0]?.filename || null,
- size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
- });
+ if (!item.source || snoozed.has(Number(item.uid))) continue;
+ messages.push(await toUiMessage(item, folder));
}
- return { messages, total: mailbox.exists, start: first, end: Math.min(end, mailbox.exists), folder };
+ return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
+async function toUiMessage(item, folder) {
+ const parsed = await simpleParser(item.source);
+ const sender = parsed.from?.value?.[0];
+ const bodyText = String(parsed.text || '').replace(/\r/g, '').trim();
+ const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
+ const date = parsed.date || item.internalDate || new Date();
+ return {
+ id: Number(item.uid),
+ initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
+ color: '#dce6df',
+ sender: sender?.name || sender?.address || 'Unknown sender',
+ email: sender?.address || '',
+ subject: parsed.subject || '(no subject)',
+ snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
+ time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
+ date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
+ unread: !item.flags?.has('\\Seen'),
+ star: item.flags?.has('\\Flagged') || false,
+ tags: [folder],
+ sent: folder === 'Sent',
+ archived: folder === 'Archive',
+ deleted: folder === 'Trash',
+ body,
+ uid: Number(item.uid),
+ attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
+ attachment: parsed.attachments?.[0]?.filename || null,
+ size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
+ };
+}
+
+async function fetchSnoozedMailbox(account, offset, limit) {
+ const now = Date.now();
+ const pending = (account.snoozedMessages || [])
+ .filter(item => Number(item.dueAt) > now)
+ .sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
+ const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
+ const client = imapClient(account);
+ const messages = [];
+ try {
+ await client.connect();
+ for (const snooze of selected) {
+ const sourceFolder = String(snooze.folder || 'Inbox');
+ const mailboxPath = await folderPath(client, sourceFolder);
+ if (!mailboxPath) continue;
+ const lock = await client.getMailboxLock(mailboxPath);
+ try {
+ const item = await client.fetchOne(Number(snooze.uid), {
+ uid: true, envelope: true, flags: true, internalDate: true, source: true
+ }, { uid: true });
+ if (!item?.source) continue;
+ messages.push({
+ ...await toUiMessage(item, 'Snoozed'),
+ sourceFolder,
+ snoozedUntil: Number(snooze.dueAt)
+ });
+ } finally {
+ lock.release();
+ }
+ }
+ } finally {
+ if (client.usable) await client.logout().catch(() => {});
+ }
+ return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
+}
+
async function saveAccountSyncState(accountId, generation, folders) {
return updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
@@ -579,7 +666,11 @@ ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
if (!current) throw new Error('That mail account is no longer available.');
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
store.accounts = store.accounts.map(item => item.id === existing.id
- ? { ...account, syncState: endpointChanged ? undefined : current.syncState }
+ ? {
+ ...account,
+ syncState: endpointChanged ? undefined : current.syncState,
+ snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || [])
+ }
: item);
return store.accounts.find(item => item.id === existing.id);
});
@@ -610,6 +701,39 @@ ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) =
return fetchMailbox(account, folder, offset);
});
+ipcMain.handle('mail:set-snooze', async (_event, input) => {
+ const account = await readAccount();
+ if (!account) throw new Error('Add a mail account before setting a reminder.');
+ const uid = Number(input?.uid);
+ const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
+ if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
+ if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.');
+ const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
+ if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
+ throw new Error('Choose a reminder time in the future.');
+ }
+ await updateAccountStore(store => {
+ const saved = store.accounts.find(item => item.id === account.id);
+ if (!saved) throw new Error('That mail account is no longer available.');
+ const snoozes = saved.snoozedMessages || [];
+ const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
+ if (dueAt != null) {
+ remaining.push({
+ uid,
+ folder,
+ dueAt,
+ subject: String(input.subject || '').slice(0, 200)
+ });
+ }
+ saved.snoozedMessages = remaining;
+ });
+ sendMailSyncUpdate({
+ accountId: account.id,
+ foldersChanged: ['Snoozed', folder]
+ });
+ return { ok: true, snoozed: dueAt != null };
+});
+
ipcMain.handle('mail:update-message', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before changing messages.');
@@ -617,7 +741,7 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
const folder = String(input?.folder || 'Inbox');
const action = String(input?.action || '');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
- if (!['star', 'unread', 'archive', 'delete'].includes(action)) throw new Error('That mail action is not supported.');
+ if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
const client = imapClient(account);
try {
await client.connect();
@@ -634,13 +758,26 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
} else {
const target = action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
- : await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash');
- if (action === 'delete' && sourcePath === target) await client.messageDelete(uid, { uid: true });
+ : action === 'delete'
+ ? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
+ : 'INBOX';
+ if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
+ if (action === 'delete') await client.messageDelete(uid, { uid: true });
+ }
else await client.messageMove(uid, target, { uid: true });
}
} finally {
lock.release();
}
+ if (action === 'archive' || action === 'delete' || action === 'inbox') {
+ await updateAccountStore(store => {
+ const saved = store.accounts.find(item => item.id === account.id);
+ if (saved) {
+ saved.snoozedMessages = (saved.snoozedMessages || [])
+ .filter(item => Number(item.uid) !== uid || item.folder !== folder);
+ }
+ });
+ }
return { ok: true };
} finally {
if (client.usable) await client.logout().catch(() => {});
@@ -934,6 +1071,9 @@ app.whenReady().then(() => {
createWindow();
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
syncTimer.unref();
+ const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs);
+ snoozeTimer.unref();
+ void checkSnoozeReminders();
requestBackgroundSync();
powerMonitor.on('suspend', () => {
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
diff --git a/desktop/preload.cjs b/desktop/preload.cjs
index 9e996a8..c6f4fba 100644
--- a/desktop/preload.cjs
+++ b/desktop/preload.cjs
@@ -12,6 +12,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
+ setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
send: message => ipcRenderer.invoke('mail:send', message),
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
diff --git a/index.html b/index.html
index 3d1670d..944d6de 100644
--- a/index.html
+++ b/index.html
@@ -65,6 +65,7 @@
+