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:
parent
7061d566a5
commit
a0209539a4
3 changed files with 66 additions and 3 deletions
|
|
@ -319,6 +319,7 @@ export class ImapProvider implements IEmailProvider {
|
||||||
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
|
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
|
||||||
subject: compose.subject,
|
subject: compose.subject,
|
||||||
text: compose.body,
|
text: compose.body,
|
||||||
|
html: compose.htmlBody ? this.buildHtmlBody(compose) : undefined,
|
||||||
inReplyTo: compose.inReplyTo,
|
inReplyTo: compose.inReplyTo,
|
||||||
references: compose.references,
|
references: compose.references,
|
||||||
attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? []
|
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,
|
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
|
||||||
subject: compose.subject,
|
subject: compose.subject,
|
||||||
text: compose.body,
|
text: compose.body,
|
||||||
|
html: compose.htmlBody ? this.buildHtmlBody(compose) : undefined,
|
||||||
messageId,
|
messageId,
|
||||||
inReplyTo: compose.inReplyTo,
|
inReplyTo: compose.inReplyTo,
|
||||||
references: compose.references,
|
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, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
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.
|
* Ищет имя отправителя в последнем письме папки Sent.
|
||||||
* Возвращает display name из заголовка From или null если Sent пуста / не найдена.
|
* Возвращает display name из заголовка From или null если Sent пуста / не найдена.
|
||||||
|
|
|
||||||
|
|
@ -31,12 +31,16 @@ function htmlToText(html: string): string {
|
||||||
.trim()
|
.trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function escHtml(s: string): string {
|
||||||
|
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plain-text версия цитаты (для text/plain части письма) */
|
||||||
function quoteBody(envelope: MessageEnvelope, body: MessageBody | null): string {
|
function quoteBody(envelope: MessageEnvelope, body: MessageBody | null): string {
|
||||||
const date = envelope.date ? new Date(envelope.date).toLocaleString('ru') : ''
|
const date = envelope.date ? new Date(envelope.date).toLocaleString('ru') : ''
|
||||||
const from = envelope.from.name
|
const from = envelope.from.name
|
||||||
? `${envelope.from.name} <${envelope.from.email}>`
|
? `${envelope.from.name} <${envelope.from.email}>`
|
||||||
: envelope.from.email
|
: envelope.from.email
|
||||||
// body.text проставляется в main-процессе; fallback на HTML если вдруг null
|
|
||||||
const rawText = body?.text ?? (body?.html ? htmlToText(body.html) : '')
|
const rawText = body?.text ?? (body?.html ? htmlToText(body.html) : '')
|
||||||
const lines = rawText
|
const lines = rawText
|
||||||
? rawText.split('\n').map((l) => `> ${l}`).join('\n')
|
? 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}`
|
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)} <${escHtml(envelope.from.email)}>`
|
||||||
|
: escHtml(envelope.from.email)
|
||||||
|
return (
|
||||||
|
`<br>` +
|
||||||
|
`<div style="font-size:12px;color:#888;margin-bottom:4px">` +
|
||||||
|
`— Оригинальное письмо —<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', () => {
|
export const useComposeStore = defineStore('compose', () => {
|
||||||
const { invoke } = useIpc()
|
const { invoke } = useIpc()
|
||||||
const accountsStore = useAccountsStore()
|
const accountsStore = useAccountsStore()
|
||||||
|
|
@ -87,6 +115,7 @@ export const useComposeStore = defineStore('compose', () => {
|
||||||
bcc: [],
|
bcc: [],
|
||||||
subject: envelope.subject.startsWith('Re:') ? envelope.subject : `Re: ${envelope.subject}`,
|
subject: envelope.subject.startsWith('Re:') ? envelope.subject : `Re: ${envelope.subject}`,
|
||||||
body: quoteBody(envelope, body),
|
body: quoteBody(envelope, body),
|
||||||
|
htmlBody: quoteBodyHtml(envelope, body),
|
||||||
inReplyTo: envelope.messageId,
|
inReplyTo: envelope.messageId,
|
||||||
// RFC 2822: References = родительские references + messageId родителя
|
// RFC 2822: References = родительские references + messageId родителя
|
||||||
// body.references содержит полную цепочку, полученную при загрузке тела
|
// body.references содержит полную цепочку, полученную при загрузке тела
|
||||||
|
|
@ -107,7 +136,8 @@ export const useComposeStore = defineStore('compose', () => {
|
||||||
mode: 'forward',
|
mode: 'forward',
|
||||||
to: [], cc: [], bcc: [],
|
to: [], cc: [], bcc: [],
|
||||||
subject: envelope.subject.startsWith('Fwd:') ? envelope.subject : `Fwd: ${envelope.subject}`,
|
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)
|
invoke('compose:open', session)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -58,7 +58,8 @@ export interface ComposeData {
|
||||||
cc: string[]
|
cc: string[]
|
||||||
bcc: string[]
|
bcc: string[]
|
||||||
subject: string
|
subject: string
|
||||||
body: string // plain text
|
body: string // plain text (полная версия: текст пользователя + текстовая цитата)
|
||||||
|
htmlBody?: string // HTML-блокквота оригинала; если задана — шлём multipart/alternative
|
||||||
attachments?: ComposeAttachment[]
|
attachments?: ComposeAttachment[]
|
||||||
inReplyTo?: string // Message-ID оригинала (для ответа)
|
inReplyTo?: string // Message-ID оригинала (для ответа)
|
||||||
references?: string // References header
|
references?: string // References header
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue