feat: HTML-письма цитируются и отправляются как multipart/alternative

Проблема: ответы на HTML-письма всегда уходили как text/plain,
получатели видели голый текст без форматирования оригинала.

Решение:
- ComposeData.htmlBody — хранит HTML-блокквоту оригинального письма
- quoteBodyHtml() в compose.store строит <blockquote> из body.html
  с атрибуцией (От/Дата/Тема) при ответе и пересылке
- buildHtmlBody() в imap.provider собирает полный HTML: текст
  пользователя (через textToHtml) + htmlBody блокквота
- sendMessage() и buildRawMessage() передают html: если htmlBody задан,
  nodemailer шлёт multipart/alternative (text/plain + text/html)

Для plain-text оригиналов htmlBody = undefined → поведение не меняется.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Aero Mail Dev 2026-04-17 05:00:11 +00:00
parent 7061d566a5
commit a0209539a4
3 changed files with 66 additions and 3 deletions

View file

@ -319,6 +319,7 @@ export class ImapProvider implements IEmailProvider {
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: compose.body,
html: compose.htmlBody ? this.buildHtmlBody(compose) : undefined,
inReplyTo: compose.inReplyTo,
references: compose.references,
attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? []
@ -367,6 +368,7 @@ export class ImapProvider implements IEmailProvider {
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: compose.body,
html: compose.htmlBody ? this.buildHtmlBody(compose) : undefined,
messageId,
inReplyTo: compose.inReplyTo,
references: compose.references,
@ -625,6 +627,36 @@ export class ImapProvider implements IEmailProvider {
}
}
/**
* Строит полный HTML-body письма: текст пользователя (→ HTML) + HTML-блокквота оригинала.
* compose.htmlBody содержит только блокквоту; пользовательский текст берём из compose.body
* до разделителя "--- Оригинальное письмо ---".
*/
private buildHtmlBody(compose: ComposeData): string {
const SEPARATOR = '\n\n--- Оригинальное письмо ---'
const replyText = compose.body.includes(SEPARATOR)
? compose.body.split(SEPARATOR)[0].trim()
: compose.body.trim()
return ImapProvider.textToHtml(replyText) + (compose.htmlBody ?? '')
}
/**
* Конвертирует plain text в минимальный HTML (параграфы + переносы строк).
*/
private static textToHtml(text: string): string {
if (!text) return ''
const escaped = text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
const paragraphs = escaped.split(/\n\n+/).filter((p) => p.trim())
if (paragraphs.length === 0) return '<p></p>'
return paragraphs
.map((p) => `<p>${p.replace(/\n/g, '<br>')}</p>`)
.join('\n')
}
/**
* Ищет имя отправителя в последнем письме папки Sent.
* Возвращает display name из заголовка From или null если Sent пуста / не найдена.

View file

@ -31,12 +31,16 @@ function htmlToText(html: string): string {
.trim()
}
function escHtml(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
/** Plain-text версия цитаты (для text/plain части письма) */
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
// body.text проставляется в main-процессе; fallback на HTML если вдруг null
const rawText = body?.text ?? (body?.html ? htmlToText(body.html) : '')
const lines = rawText
? rawText.split('\n').map((l) => `> ${l}`).join('\n')
@ -44,6 +48,30 @@ function quoteBody(envelope: MessageEnvelope, body: MessageBody | null): string
return `\n\n--- Оригинальное письмо ---\nОт: ${from}\nДата: ${date}\nТема: ${envelope.subject}\n\n${lines}`
}
/**
* HTML-блокквота оригинала (для 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)} &lt;${escHtml(envelope.from.email)}&gt;`
: escHtml(envelope.from.email)
return (
`<br>` +
`<div style="font-size:12px;color:#888;margin-bottom:4px">` +
`&#8212; Оригинальное письмо &#8212;<br>` +
`От: ${from}<br>` +
`Дата: ${escHtml(date)}<br>` +
`Тема: ${escHtml(envelope.subject)}` +
`</div>` +
`<blockquote style="margin:0 0 0 .8ex;border-left:3px solid #ccc;padding-left:1ex">` +
body.html +
`</blockquote>`
)
}
export const useComposeStore = defineStore('compose', () => {
const { invoke } = useIpc()
const accountsStore = useAccountsStore()
@ -87,6 +115,7 @@ export const useComposeStore = defineStore('compose', () => {
bcc: [],
subject: envelope.subject.startsWith('Re:') ? envelope.subject : `Re: ${envelope.subject}`,
body: quoteBody(envelope, body),
htmlBody: quoteBodyHtml(envelope, body),
inReplyTo: envelope.messageId,
// RFC 2822: References = родительские references + messageId родителя
// body.references содержит полную цепочку, полученную при загрузке тела
@ -107,7 +136,8 @@ 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: quoteBody(envelope, body),
htmlBody: quoteBodyHtml(envelope, body)
}
invoke('compose:open', session)
}

View file

@ -58,7 +58,8 @@ export interface ComposeData {
cc: string[]
bcc: string[]
subject: string
body: string // plain text
body: string // plain text (полная версия: текст пользователя + текстовая цитата)
htmlBody?: string // HTML-блокквота оригинала; если задана — шлём multipart/alternative
attachments?: ComposeAttachment[]
inReplyTo?: string // Message-ID оригинала (для ответа)
references?: string // References header