diff --git a/src/main/providers/imap.provider.ts b/src/main/providers/imap.provider.ts index 9275984..7c887a2 100644 --- a/src/main/providers/imap.provider.ts +++ b/src/main/providers/imap.provider.ts @@ -37,6 +37,8 @@ export class ImapProvider implements IEmailProvider { // uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message private notifiedUids = new Map() private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes + // Промис с именем отправителя из Sent-папки; await-ится в sendMessage() + private senderNamePromise: Promise = Promise.resolve(null) constructor(private config: AccountConfig) { const creds = config.credentials as ImapCredentials @@ -58,6 +60,8 @@ export class ImapProvider implements IEmailProvider { ) await Promise.race([this.client.connect(), timeout]) this.connected = true + // Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке + this.senderNamePromise = this.fetchSenderName().catch(() => null) } async disconnect(): Promise { @@ -179,7 +183,7 @@ export class ImapProvider implements IEmailProvider { // imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится const download = await this.client.download(messageId, undefined, { uid: true }) if (!download?.content) { - return { id: messageId, html: null, text: null, inlineImages: [], attachments: [] } + return { id: messageId, html: null, text: null, references: null, inlineImages: [], attachments: [] } } const parsed = await simpleParser(download.content) @@ -204,10 +208,21 @@ export class ImapProvider implements IEmailProvider { } } + // References header: mailparser returns string[] — join to space-separated string + const refsArray = (parsed as unknown as { references?: string | string[] }).references + const references = Array.isArray(refsArray) + ? refsArray.join(' ') + : (typeof refsArray === 'string' ? refsArray : null) + + const sanitizedHtml = parsed.html ? sanitizeHtml(parsed.html) : null + // Если text/plain части нет — деривируем из HTML (правильно: style/script уже отфильтрованы) + const text = parsed.text ?? (parsed.html ? this.htmlToPlainText(parsed.html) : null) + return { id: messageId, - html: parsed.html ? sanitizeHtml(parsed.html) : null, - text: parsed.text ?? null, + html: sanitizedHtml, + text, + references, inlineImages, attachments } @@ -288,10 +303,21 @@ export class ImapProvider implements IEmailProvider { ? this.config.email : `${this.config.email}@${creds.host.replace(/^[^.]+\./, '')}` - const from = this.config.label - ? { name: this.config.label, address: emailAddress } + // Имя отправителя: await-им промис из connect() — гарантирует что имя готово + const senderName = await this.senderNamePromise + const displayName = senderName ?? this.config.label + const from = displayName + ? { name: displayName, address: emailAddress } : emailAddress + // Собираем text + html из отдельных частей + const fullText = compose.quotedText + ? compose.body + '\n\n' + compose.quotedText + : compose.body + const fullHtml = compose.htmlBody + ? ImapProvider.textToHtml(compose.body) + compose.htmlBody + : undefined + console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j', smtpHost, smtpPort, smtpSecure, from, compose.to) @@ -301,7 +327,8 @@ export class ImapProvider implements IEmailProvider { cc: compose.cc.length ? compose.cc.join(', ') : undefined, bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined, subject: compose.subject, - text: compose.body, + text: fullText, + html: fullHtml, inReplyTo: compose.inReplyTo, references: compose.references, attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? [] @@ -343,13 +370,21 @@ export class ImapProvider implements IEmailProvider { ): Promise { try { const transporter = nodemailer.createTransport({ streamTransport: true, newline: 'unix' }) + const fullText = compose.quotedText + ? compose.body + '\n\n' + compose.quotedText + : compose.body + const fullHtml = compose.htmlBody + ? ImapProvider.textToHtml(compose.body) + compose.htmlBody + : undefined + const mail = await transporter.sendMail({ from, to: compose.to.join(', '), cc: compose.cc.length ? compose.cc.join(', ') : undefined, bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined, subject: compose.subject, - text: compose.body, + text: fullText, + html: fullHtml, messageId, inReplyTo: compose.inReplyTo, references: compose.references, @@ -608,6 +643,81 @@ export class ImapProvider implements IEmailProvider { } } + /** + * Конвертирует plain text в минимальный HTML (параграфы + переносы строк). + */ + private static textToHtml(text: string): string { + if (!text) return '' + const escaped = text + .replace(/&/g, '&') + .replace(//g, '>') + const paragraphs = escaped.split(/\n\n+/).filter((p) => p.trim()) + if (paragraphs.length === 0) return '

' + return paragraphs + .map((p) => `

${p.replace(/\n/g, '
')}

`) + .join('\n') + } + + /** + * Ищет имя отправителя в последнем письме папки Sent. + * Возвращает display name из заголовка From или null если Sent пуста / не найдена. + */ + private async fetchSenderName(): Promise { + try { + const tree = await this.client.listTree() as { folders?: ImapMailbox[] } + const sentPath = this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent) + if (!sentPath) return null + + const status = await this.client.status(sentPath, { messages: true }) as { messages?: number } | null + const total = status?.messages ?? 0 + if (total === 0) return null + + const lock = await this.client.getMailboxLock(sentPath) + try { + let name: string | null = null + // Берём только самое последнее письмо + for await (const msg of this.client.fetch(`${total}:${total}`, { envelope: true })) { + const fromList = (msg as { envelope?: { from?: Array<{ name?: string }> } }).envelope?.from + const candidate = fromList?.[0]?.name?.trim() + if (candidate) { name = candidate; break } + } + return name + } finally { + lock.release() + } + } catch { + return null + } + } + + private htmlToPlainText(html: string): string { + return html + // Убираем целиком блоки diff --git a/src/renderer/src/stores/compose.store.ts b/src/renderer/src/stores/compose.store.ts index 195e6ec..5a218b8 100644 --- a/src/renderer/src/stores/compose.store.ts +++ b/src/renderer/src/stores/compose.store.ts @@ -4,14 +4,69 @@ import type { MessageEnvelope, MessageBody } from '@shared/types/message' import { useAccountsStore } from './accounts.store' import { useIpc } from '../composables/useIpc' +/** + * Стриппер HTML → plain text для цитирования. + * Применяется только как fallback когда body.text отсутствует (HTML-only письма + * до перезапуска main-процесса или из старого кеша). + */ +function htmlToText(html: string): string { + return html + .replace(/]*>[\s\S]*?<\/style>/gi, '') + .replace(//gi, '\n') + .replace(/<\/p>/gi, '\n\n') + .replace(/<\/div>/gi, '\n') + .replace(/<\/li>/gi, '\n') + .replace(/<\/tr>/gi, '\n') + .replace(/<\/h[1-6]>/gi, '\n\n') + .replace(/<[^>]+>/g, '') + .replace(/ /g, ' ') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, '&') + .replace(/\n{3,}/g, '\n\n') + .trim() +} + +function escHtml(s: string): string { + return s.replace(/&/g, '&').replace(//g, '>') +} + +/** Plain-text цитата оригинала (> строки с атрибуцией). Без ведущих \n\n. */ function quoteBody(envelope: MessageEnvelope, body: MessageBody | null): string { const date = envelope.date ? new Date(envelope.date).toLocaleString('ru') : '' const from = envelope.from.name ? `${envelope.from.name} <${envelope.from.email}>` : envelope.from.email - const text = body?.text ?? '' - const lines = text.split('\n').map((l) => `> ${l}`).join('\n') - return `\n\n--- Оригинальное письмо ---\nОт: ${from}\nДата: ${date}\nТема: ${envelope.subject}\n\n${lines}` + const rawText = body?.text ?? (body?.html ? htmlToText(body.html) : '') + const lines = rawText + ? rawText.split('\n').map((l) => `> ${l}`).join('\n') + : '' + return `--- Оригинальное письмо ---\nОт: ${from}\nДата: ${date}\nТема: ${envelope.subject}\n\n${lines}` +} + +/** + * HTML-блокквота оригинала (для рендера в compose + text/html часть). + * Возвращает undefined если оригинал — plain-text (тогда шлём только text/plain). + */ +function quoteBodyHtml(envelope: MessageEnvelope, body: MessageBody | null): string | undefined { + if (!body?.html) return undefined + const date = envelope.date ? new Date(envelope.date).toLocaleString('ru') : '' + const from = envelope.from.name + ? `${escHtml(envelope.from.name)} <${escHtml(envelope.from.email)}>` + : escHtml(envelope.from.email) + return ( + `
` + + `— Оригинальное письмо —
` + + `От: ${from}
` + + `Дата: ${escHtml(date)}
` + + `Тема: ${escHtml(envelope.subject)}` + + `
` + + `
` + + body.html + + `
` + ) } export const useComposeStore = defineStore('compose', () => { @@ -30,14 +85,14 @@ export const useComposeStore = defineStore('compose', () => { function openNew(): void { const acc = getAccountSession() - if (!acc) return + if (!acc) { console.warn('[compose] no active account'); return } const session: ComposeSession = { ...acc, mode: 'new', to: [], cc: [], bcc: [], subject: '', body: '' } - invoke('compose:open', session) + invoke('compose:open', session).catch((e) => console.error('[compose:open]', e)) } function openReply(envelope: MessageEnvelope, body: MessageBody | null, replyAll = false): void { @@ -56,15 +111,17 @@ export const useComposeStore = defineStore('compose', () => { cc, bcc: [], subject: envelope.subject.startsWith('Re:') ? envelope.subject : `Re: ${envelope.subject}`, - body: quoteBody(envelope, body), + body: '', + quotedText: quoteBody(envelope, body), + htmlBody: quoteBodyHtml(envelope, body), inReplyTo: envelope.messageId, references: envelope.messageId - ? [envelope.inReplyTo, envelope.messageId].filter(Boolean).join(' ') + ? [body?.references ?? envelope.inReplyTo, envelope.messageId].filter(Boolean).join(' ').trim() || undefined : undefined, replyToMessageId: envelope.id, replyToFolderId: envelope.folderId } - invoke('compose:open', session) + invoke('compose:open', session).catch((e) => console.error('[compose:open]', e)) } function openForward(envelope: MessageEnvelope, body: MessageBody | null): void { @@ -75,9 +132,11 @@ export const useComposeStore = defineStore('compose', () => { mode: 'forward', to: [], cc: [], bcc: [], subject: envelope.subject.startsWith('Fwd:') ? envelope.subject : `Fwd: ${envelope.subject}`, - body: quoteBody(envelope, body) + body: '', + quotedText: quoteBody(envelope, body), + htmlBody: quoteBodyHtml(envelope, body) } - invoke('compose:open', session) + invoke('compose:open', session).catch((e) => console.error('[compose:open]', e)) } return { openNew, openReply, openForward } diff --git a/src/renderer/src/views/ComposeView.vue b/src/renderer/src/views/ComposeView.vue index 3455691..edab260 100644 --- a/src/renderer/src/views/ComposeView.vue +++ b/src/renderer/src/views/ComposeView.vue @@ -15,6 +15,8 @@ const cc = ref([]) const bcc = ref([]) const subject = ref('') const body = ref('') +const quotedText = ref('') +const htmlBody = ref('') const showCc = ref(false) const showBcc = ref(false) @@ -27,11 +29,85 @@ const ccInputEl = ref(null) const bccInputEl = ref(null) const bodyEl = ref(null) +// ── Quote ───────────────────────────────────────────────── +const quoteExpanded = ref(true) +const hasQuote = computed(() => !!(htmlBody.value || quotedText.value)) +const isReplyOrForward = computed(() => { + const m = session.value?.mode + return m === 'reply' || m === 'replyAll' || m === 'forward' +}) + +/** srcdoc для iframe с оригинальным HTML-письмом */ +const quoteSrcdoc = computed(() => { + if (htmlBody.value) { + return ` + + +${htmlBody.value}` + } + + if (quotedText.value) { + const escaped = quotedText.value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/\n/g, '
') + return ` + + +${escaped}` + } + + return '' +}) + // ── Attachments ─────────────────────────────────────────── interface LocalAttachment extends ComposeAttachment { id: string } const attachments = ref([]) const isDragging = ref(false) -let dragCounter = 0 // track nested dragenter/dragleave +let dragCounter = 0 // ── Status ──────────────────────────────────────────────── const sending = ref(false) @@ -41,21 +117,19 @@ const sendError = ref('') onMounted(async () => { const data = await invoke('compose:getData') if (!data) return - session.value = data - to.value = [...(data.to ?? [])] - cc.value = [...(data.cc ?? [])] - bcc.value = [...(data.bcc ?? [])] - subject.value = data.subject ?? '' - body.value = data.body ?? '' - showCc.value = cc.value.length > 0 - showBcc.value = bcc.value.length > 0 + session.value = data + to.value = [...(data.to ?? [])] + cc.value = [...(data.cc ?? [])] + bcc.value = [...(data.bcc ?? [])] + subject.value = data.subject ?? '' + body.value = data.body ?? '' + quotedText.value = data.quotedText ?? '' + htmlBody.value = data.htmlBody ?? '' + showCc.value = cc.value.length > 0 + showBcc.value = bcc.value.length > 0 nextTick(() => { - if (data.mode === 'new') toInputEl.value?.focus() - else { - bodyEl.value?.focus() - bodyEl.value?.setSelectionRange(0, 0) - } + bodyEl.value?.focus() }) }) @@ -186,9 +260,11 @@ async function handleSend(): Promise { bcc: [...bcc.value], subject: subject.value, body: body.value, + quotedText: quotedText.value || undefined, + htmlBody: htmlBody.value || undefined, attachments: attachments.value.map(({ path, filename, size }) => ({ path, filename, size })), inReplyTo: sess.inReplyTo, - references: sess.references ? [...sess.references] : undefined, + references: sess.references || undefined, replyToMessageId: sess.replyToMessageId, replyToFolderId: sess.replyToFolderId } @@ -240,7 +316,7 @@ const totalAttachSize = computed(() =>
- {{ session.accountLabel || session.accountEmail }} + {{ session.accountEmail }}
@@ -292,7 +368,7 @@ const totalAttachSize = computed(() => @blur="commitInput('cc')" /> - + @@ -317,7 +393,7 @@ const totalAttachSize = computed(() => @blur="commitInput('bcc')" /> - + @@ -340,9 +416,31 @@ const totalAttachSize = computed(() => ref="bodyEl" class="compose-body" v-model="body" - placeholder="Напишите сообщение…" + :placeholder="isReplyOrForward ? 'Напишите ответ…' : 'Напишите сообщение…'" /> + +