const { randomUUID } = require('node:crypto'); const nodemailer = require('nodemailer'); const { normalizeOutgoingAttachments } = require('../mail-attachments.cjs'); function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTransport = nodemailer.createTransport }) { 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 = await smtpTransport(account); const sentMessageId = String(message.messageId || `<${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 = createTransport({ streamTransport: true, buffer: true, newline: 'windows' }); try { const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions); const client = await 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 }; } return { sendMailNow }; } module.exports = { createMailSender };