Refractoring Stage 2 Add Refractor plan.md

This commit is contained in:
2026-10-16 16:27:09 +03:00
parent e5391dbb62
commit e398bc4e1a
23 changed files with 1259 additions and 370 deletions
+64 -366
View File
@@ -11,9 +11,45 @@ const ICAL = require('ical.js');
const openpgp = require('openpgp');
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
const {
CUSTOM_FOLDER_PREFIX,
filterMailboxMessages,
isReservedFolderName,
normalizeAccount,
publicAccount,
validFolderName
} = require('./mail-model.cjs');
const { makeCalendarData, makeVcard } = require('./dav-codecs.cjs');
const { extractMailContent } = require('./mail-content.cjs');
const { createSecureJsonStore } = require('./secure-json-store.cjs');
const { createAccountStore } = require('./account-store.cjs');
const { createMailSender } = require('./mail/send-service.cjs');
const { createFolderService } = require('./mail/folders.cjs');
const { createMailReader } = require('./mail/read-service.cjs');
const { createMessageActionService } = require('./mail/action-service.cjs');
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
const accountJsonStore = createSecureJsonStore({
getFilePath: credentialsPath,
safeStorage,
assertSecureStorage,
unavailableMessage: 'Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.'
});
const accountRepository = createAccountStore(accountJsonStore);
const davJsonStore = createSecureJsonStore({
getFilePath: davCredentialsPath,
safeStorage,
assertSecureStorage,
unavailableMessage: 'Secure credential storage is unavailable.'
});
const pgpJsonStore = createSecureJsonStore({
getFilePath: pgpKeysPath,
safeStorage,
assertSecureStorage,
unavailableMessage: 'Secure key storage is unavailable.'
});
const backgroundSyncIntervalMs = 30 * 1000;
const backgroundRetryIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2;
@@ -203,37 +239,29 @@ async function reconcileIdleWatchers() {
const { createKeyStore } = require('./pgp-keystore.cjs');
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
const pgpKeys = createKeyStore({
async load() {
try {
assertSecureStorage();
const { result } = await safeStorage.decryptStringAsync(await fs.readFile(pgpKeysPath()));
return JSON.parse(result);
return await pgpJsonStore.load();
} catch (error) {
if (error.code === 'ENOENT') return { keys: [] };
throw error;
}
},
async save(data) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.');
await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true });
await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 });
await fs.rename(`${pgpKeysPath()}.tmp`, pgpKeysPath());
}
save(data) { return pgpJsonStore.save(data); }
});
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
const pgpKeyServers = createKeyServerService();
const { findSpecialMailbox, findSentMailbox, listCustomFolders, folderPath } = createFolderService({
customFolderPrefix: CUSTOM_FOLDER_PREFIX,
isReservedFolderName
});
async function readDavStore() {
try {
assertSecureStorage();
const encrypted = await fs.readFile(davCredentialsPath());
const { result } = await safeStorage.decryptStringAsync(encrypted);
return JSON.parse(result);
return await davJsonStore.load();
} catch (error) {
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
throw error;
@@ -241,12 +269,7 @@ async function readDavStore() {
}
async function saveDavStore(store) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure credential storage is unavailable.');
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
await fs.mkdir(path.dirname(davCredentialsPath()), { recursive: true });
await fs.writeFile(`${davCredentialsPath()}.tmp`, encrypted, { mode: 0o600 });
await fs.rename(`${davCredentialsPath()}.tmp`, davCredentialsPath());
return davJsonStore.save(store);
}
function davPublicConfig(config) {
@@ -263,65 +286,6 @@ function activeDavConfig(store, type, id = null) {
return store[key].find(item => item.id === (id || store[activeKey])) || null;
}
function escapeIcal(value = '') { return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;'); }
function escapeVcard(value = '') { return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;'); }
function makeCalendarData(event) {
const uid = event._dav?.uid || randomUUID();
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
const start = event.time ? new Date(`${event.date}T${event.time}:00`).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') : event.date.replace(/-/g, '');
const endDate = event.time ? new Date(new Date(`${event.date}T${event.time}:00`).getTime() + 3600000).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') : null;
return `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${uid}\r\nDTSTAMP:${stamp}\r\n${event.time ? `DTSTART:${start}\r\nDTEND:${endDate}\r\n` : `DTSTART;VALUE=DATE:${start}\r\n` }SUMMARY:${escapeIcal(event.title)}\r\n${event.place ? `LOCATION:${escapeIcal(event.place)}\r\n` : ''}${event.notes ? `DESCRIPTION:${escapeIcal(event.notes)}\r\n` : ''}END:VEVENT\r\nEND:VCALENDAR\r\n`;
}
function makeVcard(contact) {
const name = String(contact.name || '').trim().split(/\s+/);
const first = name.shift() || '';
const last = name.join(' ');
return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${contact._dav?.uid || randomUUID()}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`;
}
function normalizeAccount(input) {
const email = String(input?.email || '').trim();
const password = String(input?.password || '');
const imapHost = String(input?.imapHost || '').trim();
const smtpHost = String(input?.smtpHost || '').trim();
const displayName = String(input?.displayName || '').trim().slice(0, 80);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
throw new Error('Enter a valid email, password, and both mail server names.');
}
if (!displayName) throw new Error('Enter a display name for this mail account.');
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
throw new Error('Choose a supported mailbox sync interval.');
}
const inputRules = Array.isArray(input?.rules) ? input.rules : [];
if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.');
const rules = inputRules.map((rule, index) => {
const senderContains = String(rule?.senderContains || '').trim().slice(0, 200);
const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200);
const action = String(rule?.action || '');
const value = String(rule?.value || '').trim().slice(0, 200);
if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) {
throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`);
}
if ((action === 'move' || action === 'label') && !value) {
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
}
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value) && !value.startsWith(CUSTOM_FOLDER_PREFIX)) {
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders.`);
}
return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value };
});
return {
email, password, displayName, imapHost, smtpHost,
signature: String(input?.signature || '').slice(0, 5000),
notificationsEnabled: input?.notificationsEnabled !== false,
syncIntervalMinutes,
rules,
imapPort: 143,
smtpPort: 587
};
}
function imapClient(account, options = {}) {
return new ImapFlow({
host: account.imapHost,
@@ -363,35 +327,11 @@ function assertSecureStorage() {
}
async function readAccountStore() {
try {
assertSecureStorage();
const encrypted = await fs.readFile(credentialsPath());
const { result } = await safeStorage.decryptStringAsync(encrypted);
const stored = JSON.parse(result);
if (Array.isArray(stored.accounts)) return stored;
if (stored.email) {
const account = { ...stored, id: stored.id || randomUUID() };
const migrated = { accounts: [account], activeId: account.id };
await saveAccountStore(migrated);
return migrated;
}
return { accounts: [], activeId: null };
} catch (error) {
if (error.code === 'ENOENT') return null;
throw error;
}
return accountRepository.load();
}
async function saveAccountStore(store) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) {
throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.');
}
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
const file = credentialsPath();
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 });
await fs.rename(`${file}.tmp`, file);
return accountRepository.save(store);
}
async function readAccount(accountId = null) {
@@ -400,20 +340,6 @@ async function readAccount(accountId = null) {
return store.accounts.find(account => account.id === (accountId || store.activeId)) || null;
}
function publicAccount(account) {
return {
id: account.id,
email: account.email,
displayName: account.displayName || '',
imapHost: account.imapHost,
smtpHost: account.smtpHost,
signature: account.signature || '',
notificationsEnabled: account.notificationsEnabled !== false,
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
rules: Array.isArray(account.rules) ? account.rules : []
};
}
async function saveAccount(account) {
return updateAccountStore(store => {
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
@@ -439,76 +365,6 @@ async function connectMail(account) {
}
}
async function findSpecialMailbox(client, specialUse, fallbackNames, createName = null) {
const mailboxes = await client.list();
const match = mailboxes.find(mailbox => mailbox.specialUse?.toLowerCase() === specialUse.toLowerCase()) ||
mailboxes.find(mailbox => fallbackNames.includes(mailbox.path.toLowerCase().split(/[./]/).pop()));
if (match) return match.path;
if (!createName) return null;
return (await client.mailboxCreate(createName)).path;
}
async function findSentMailbox(client, createIfMissing = false) {
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
}
const CUSTOM_FOLDER_PREFIX = 'Folder:';
const RESERVED_FOLDER_NAMES = new Set(['inbox', 'sent', 'drafts', 'archive', 'trash', 'starred', 'snoozed', 'junk', 'spam']);
async function listCustomFolders(client) {
return (await client.list())
.filter(mailbox => !mailbox.flags?.has('\\Noselect') && !mailbox.specialUse &&
mailbox.path.toUpperCase() !== 'INBOX' &&
!RESERVED_FOLDER_NAMES.has(mailbox.path.toLowerCase().split(/[./]/).pop()) &&
!['sent items', 'sent mail', 'sent messages', 'archives', 'all mail', 'deleted items', 'deleted messages']
.includes(mailbox.path.toLowerCase().split(/[./]/).pop()))
.map(mailbox => ({ name: mailbox.name, path: mailbox.path, id: CUSTOM_FOLDER_PREFIX + mailbox.path }))
.sort((a, b) => a.path.localeCompare(b.path));
}
function validFolderName(input) {
const name = String(input || '').trim();
if (!name || name.length > 100) throw new Error('Enter a folder name of up to 100 characters.');
if (/[\\/.*%#&\u0000-\u001f]/.test(name)) throw new Error('Folder names cannot contain / \\ . * % # & or control characters.');
if (RESERVED_FOLDER_NAMES.has(name.toLowerCase())) throw new Error('That folder name is reserved.');
return name;
}
async function folderPath(client, folder, createIfMissing = false) {
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
const definitions = {
Sent: ['\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], 'Sent'],
Archive: ['\\Archive', ['archive', 'archives', 'all mail'], 'Archive'],
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
};
const definition = definitions[folder];
if (!definition && typeof folder === 'string' && folder.startsWith(CUSTOM_FOLDER_PREFIX)) {
const path = folder.slice(CUSTOM_FOLDER_PREFIX.length);
const match = (await client.list()).find(mailbox => mailbox.path === path);
if (!match || match.flags?.has('\\Noselect')) throw new Error('This folder is not available on the mail server.');
return match.path;
}
if (!definition) throw new Error('This folder is not available on the mail server.');
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
}
function filterMailboxMessages(messages, filters = {}) {
const text = String(filters.query || '').trim().toLowerCase();
const sender = String(filters.sender || '').trim().toLowerCase();
const subject = String(filters.subject || '').trim().toLowerCase();
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
return messages.filter(message => {
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
const date = Number(message.timestamp || 0);
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
(!after || date >= after) && (!before || date <= before) &&
(!filters.hasAttachments || (message.attachments || []).length > 0);
});
}
async function cacheMailboxMessages(accountId, folder, messages) {
if (!messages.length) return;
await updateAccountStore(store => {
@@ -530,59 +386,6 @@ function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
}
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
const client = imapClient(account);
try {
await client.connect();
const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) return { messages: [], total: 0 };
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
const snoozed = new Set((account.snoozedMessages || [])
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
.map(item => Number(item.uid)));
if (Object.values(filters).some(value => value && value !== false)) {
const searchStart = Math.max(1, mailbox.exists - 4999);
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}) : [];
const all = [];
for (const item of fetched) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
all.push(message);
}
await cacheMailboxMessages(account.id, folder, all);
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
const start = Math.max(0, Number(offset) || 0);
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
}
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
const fetched = await client.fetchAll(`${first}:${end}`, {
uid: true,
envelope: true,
flags: true,
internalDate: true,
source: true
});
const messages = [];
for (const item of fetched.reverse()) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
messages.push(message);
}
await cacheMailboxMessages(account.id, folder, messages);
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];
@@ -590,7 +393,7 @@ async function toUiMessage(item, folder) {
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
const content = encrypted
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
: mailContent(parsed);
: extractMailContent(parsed);
const { bodyText, body, links } = content;
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
const date = parsed.date || item.internalDate || new Date();
@@ -624,26 +427,6 @@ async function toUiMessage(item, folder) {
};
}
function mailContent(parsed) {
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
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 html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
.map(match => (match[1] || match[2] || match[3] || '').replace(/&amp;/gi, '&').replace(/&#x2f;/gi, '/'))
.filter(Boolean)
.slice(0, 30);
const files = (parsed.attachments || []).filter(file => !/^application\/pgp-(signature|encrypted)/i.test(file.contentType || ''));
return {
bodyText,
body,
html: html.slice(0, 100000),
links,
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: files[0]?.filename || null,
size: files[0]?.size ? `${(files[0].size / 1048576).toFixed(1)} MB` : ''
};
}
async function fetchSnoozedMailbox(account, offset, limit) {
const now = Date.now();
const pending = (account.snoozedMessages || [])
@@ -681,6 +464,21 @@ async function fetchSnoozedMailbox(account, offset, limit) {
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
}
const { fetchMailbox } = createMailReader({
imapClient,
folderPath,
toUiMessage,
cacheMailboxMessages,
fetchSnoozedMailbox,
filterMailboxMessages
});
const { applyMessageAction } = createMessageActionService({
imapClient,
folderPath,
findSpecialMailbox,
updateAccountStore
});
async function saveAccountSyncState(accountId, generation, folders) {
return updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
@@ -1089,54 +887,6 @@ ipcMain.handle('mail:set-snooze', async (_event, input) => {
return { ok: true, snoozed: dueAt != null };
});
async function applyMessageAction(account, input) {
const uid = Number(input?.uid);
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', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
const client = imapClient(account);
try {
await client.connect();
const sourcePath = await folderPath(client, folder);
if (!sourcePath) throw new Error('That mail folder could not be found.');
const lock = await client.getMailboxLock(sourcePath);
try {
if (action === 'star') {
if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true });
} else if (action === 'unread') {
if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true });
else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true });
} else {
const target = action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: 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(() => {});
}
}
function isConnectivityFailure(error) {
const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']);
for (let current = error; current; current = current.cause) {
@@ -1380,7 +1130,7 @@ ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
const outer = await simpleParser(source);
try {
const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null });
const content = mailContent(result.parsed);
const content = extractMailContent(result.parsed);
return {
ok: true,
body: content.body,
@@ -1600,59 +1350,7 @@ ipcMain.handle('mail:sync-inbox', async () => {
return fetchMailbox(account, 'Inbox');
});
async function sendMailNow(account, message) {
const to = String(message?.to || '').trim();
if (!to) throw new Error('Add at least one recipient.');
const attachments = normalizeOutgoingAttachments(message?.attachments);
const transport = smtpTransport(account);
const sentMessageId = String(message.messageId || `<${require('node:crypto').randomUUID()}@ep-mail.local>`);
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
const body = String(message?.text || '').slice(0, 500000);
const signature = String(account.signature || '').slice(0, 5000);
const messageOptions = {
from: { name: fromName, address: account.email },
to,
cc: String(message.cc || '').trim() || undefined,
subject: String(message.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: sentMessageId,
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
};
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
try {
if (rawMessage) await transport.sendMail({ envelope: message.envelope, raw: rawMessage });
else await transport.sendMail(messageOptions);
} finally {
transport.close();
}
let savedToSent = false;
const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
try {
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
const client = imapClient(account);
try {
await client.connect();
const sentPath = await findSentMailbox(client, true);
const lock = await client.getMailboxLock(sentPath);
try {
const existing = await client.search({ header: { 'message-id': sentMessageId } }, { uid: true });
if (!existing.length) await client.append(sentPath, rendered.message, ['\\Seen'], new Date());
savedToSent = true;
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
} catch {
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
}
return { ok: true, savedToSent };
}
const { sendMailNow } = createMailSender({ smtpTransport, imapClient, findSentMailbox });
ipcMain.handle('mail:send', async (event, message) => {
const account = await readAccount();