Preserve QOutlook HTML EML bodies

This commit is contained in:
Курнат Андрей
2026-06-02 06:30:26 +03:00
parent e5727b4484
commit c4fd683ef3
7 changed files with 269 additions and 5 deletions
+2
View File
@@ -146,6 +146,8 @@ export const initialState: QOfficeState = {
cc: "qa@qoffice.local",
subject: "Контрольный список запуска",
body: "Пожалуйста, проверьте этапы редакторов, цели упаковки и ответственных за качество до пятницы.",
bodyHtml:
"<h3>Контрольный список запуска</h3><p>Пожалуйста, проверьте <strong>этапы редакторов</strong>, цели упаковки и ответственных за качество до пятницы.</p><ul><li>QWord: страницы и DOCX</li><li>QExcell: XLSX round-trip</li><li>QOutlook: EML/MSG импорт</li></ul>",
time: "09:24",
read: false,
flagged: true,
+97 -1
View File
@@ -38,6 +38,93 @@ function formatBytes(bytes: number): string {
return `${Number.isInteger(value) ? value : value.toFixed(1)} ${units[unitIndex]}`;
}
const allowedMailHtmlTags = new Set([
"a",
"b",
"blockquote",
"br",
"code",
"div",
"em",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"i",
"img",
"li",
"ol",
"p",
"pre",
"span",
"strong",
"sub",
"sup",
"table",
"tbody",
"td",
"tfoot",
"th",
"thead",
"tr",
"u",
"ul"
]);
const allowedMailHtmlAttributes = new Set(["align", "alt", "colspan", "height", "href", "rowspan", "src", "title", "width"]);
const allowedMailHtmlProtocols = new Set(["http:", "https:", "mailto:", "tel:"]);
const unsafeMailHtmlSelector = "script, style, iframe, object, embed, meta, link, base, form, input, button, textarea, select";
function sanitizeMailHtml(html: string): string {
const parser = new DOMParser();
const document = parser.parseFromString(html, "text/html");
document.querySelectorAll(unsafeMailHtmlSelector).forEach((element) => element.remove());
document.body.querySelectorAll("*").forEach((element) => {
const tagName = element.tagName.toLowerCase();
if (!allowedMailHtmlTags.has(tagName)) {
element.replaceWith(...Array.from(element.childNodes));
return;
}
Array.from(element.attributes).forEach((attribute) => {
const name = attribute.name.toLowerCase();
if (!allowedMailHtmlAttributes.has(name) || name.startsWith("on") || !isSafeMailHtmlAttribute(name, attribute.value)) {
element.removeAttribute(attribute.name);
}
});
if (tagName === "a" && element.hasAttribute("href")) {
element.setAttribute("rel", "noopener noreferrer");
element.setAttribute("target", "_blank");
}
});
return document.body.innerHTML;
}
function isSafeMailHtmlAttribute(name: string, value: string): boolean {
if (name !== "href" && name !== "src") {
return true;
}
const trimmed = value.trim();
if (name === "src" && /^data:image\/(?:png|jpe?g|gif|bmp|webp);base64,/i.test(trimmed)) {
return true;
}
try {
const parsed = new URL(trimmed, window.location.origin);
return allowedMailHtmlProtocols.has(parsed.protocol);
} catch {
return false;
}
}
export function QOutlook({ mail, onChange, onFolderChange }: QOutlookProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const draftAttachmentInputRef = useRef<HTMLInputElement>(null);
@@ -73,6 +160,7 @@ export function QOutlook({ mail, onChange, onFolderChange }: QOutlookProps) {
message.priority ?? "",
message.subject,
message.body,
message.bodyHtml ?? "",
...(message.attachments ?? []).map((attachment) => attachment.fileName)
].some((field) => field.toLowerCase().includes(normalizedQuery));
return inFolder && matchesQuery;
@@ -341,7 +429,15 @@ export function QOutlook({ mail, onChange, onFolderChange }: QOutlookProps) {
{activeMessage.priority ? `Priority: ${activeMessage.priority}` : ""}
</p>
) : null}
<p>{activeMessage.body}</p>
{activeMessage.bodyHtml ? (
<div
className="message-html-body"
aria-label="HTML содержимое письма"
dangerouslySetInnerHTML={{ __html: sanitizeMailHtml(activeMessage.bodyHtml) }}
/>
) : (
<p>{activeMessage.body}</p>
)}
{activeAttachments.length > 0 ? (
<section className="attachments-panel" aria-label="Вложения письма">
<h3>Вложения</h3>
+29
View File
@@ -7,6 +7,7 @@ import {
decodeTransferBody,
extractMessageAttachments,
extractMessageBody,
extractMessageHtmlBody,
htmlToPlainText,
importEmlFile,
isSupportedEmlFileName,
@@ -203,6 +204,7 @@ describe("outlookMail helpers", () => {
expect(imported.subject).toBe("Мультипарт");
expect(imported.body).toBe("Привет, письмо");
expect(imported.bodyHtml).toBe("<p>HTML</p>");
expect(imported.from).toBe("sender@example.com");
expect(imported.to).toBe("reader@example.com");
expect(imported.cc).toBe("copy@example.com");
@@ -298,11 +300,13 @@ describe("outlookMail helpers", () => {
xPriority: "5",
priority: "non-urgent",
subject: "MSG отчет",
bodyHtml: "<p>HTML&nbsp;текст</p>",
body: "HTML текст",
time: "Mon, 01 Jun 2026 10:00:00 GMT",
read: false,
flagged: false
});
expect(message.bodyHtml).toBe("<p>HTML&nbsp;текст</p>");
expect(message.id).toMatch(/^msg-/);
expect(message.attachments).toEqual([
{
@@ -355,6 +359,28 @@ describe("outlookMail helpers", () => {
expect(eml.endsWith("Текст")).toBe(true);
});
it("exports HTML body as multipart/alternative EML", () => {
const message: MailMessage = {
id: "html-1",
folder: "sent",
from: "sender@example.com",
to: "reader@example.com",
subject: "HTML message",
body: "Plain text",
bodyHtml: "<p><strong>HTML text</strong></p>",
time: "Mon, 01 Jan 2024 10:00:00 +0000",
read: true,
flagged: false
};
const eml = buildEmlSource(message);
const parsed = parseEmlSource(eml);
expect(eml).toContain("Content-Type: multipart/alternative");
expect(extractMessageBody(parsed.headers, parsed.body)).toBe("Plain text");
expect(extractMessageHtmlBody(parsed.headers, parsed.body)).toBe("<p><strong>HTML text</strong></p>");
});
it("собирает multipart/mixed EML с вложениями и RFC 2231 filename", () => {
const message: MailMessage = {
id: "1",
@@ -372,6 +398,7 @@ describe("outlookMail helpers", () => {
priority: "urgent",
subject: "Тема",
body: "Текст",
bodyHtml: "<p><strong>Текст</strong></p>",
time: "Mon, 01 Jan 2024 10:00:00 +0000",
read: true,
flagged: false,
@@ -392,6 +419,7 @@ describe("outlookMail helpers", () => {
const attachments = extractMessageAttachments(parsed.headers, parsed.body);
expect(eml).toContain("Content-Type: multipart/mixed");
expect(eml).toContain("Content-Type: multipart/alternative");
expect(eml).toContain("Cc: copy@example.com");
expect(eml).toContain("Bcc: hidden@example.com");
expect(eml).toContain("Reply-To: support@example.com");
@@ -403,6 +431,7 @@ describe("outlookMail helpers", () => {
expect(eml).toContain("Priority: urgent");
expect(eml).toContain("filename*=utf-8''%D0%BE%D1%82%D1%87%D0%B5%D1%82%2E%74%78%74");
expect(extractMessageBody(parsed.headers, parsed.body)).toBe("Текст");
expect(extractMessageHtmlBody(parsed.headers, parsed.body)).toBe("<p><strong>Текст</strong></p>");
expect(attachments[0]).toMatchObject({
fileName: "отчет.txt",
contentType: "text/plain",
+93 -4
View File
@@ -81,6 +81,7 @@ export async function importEmlFile(file: File): Promise<ImportedMailMessage> {
const raw = await file.text();
const parsed = parseEmlSource(raw);
const bodyHtml = extractMessageHtmlBody(parsed.headers, parsed.body);
return {
id: `eml-${Date.now()}`,
@@ -94,6 +95,7 @@ export async function importEmlFile(file: File): Promise<ImportedMailMessage> {
...mailPriorityHeaders(parsed.headers),
subject: decodeMimeWords(parsed.headers.subject || "Без темы"),
body: extractMessageBody(parsed.headers, parsed.body),
...(bodyHtml ? { bodyHtml } : {}),
time: parsed.headers.date || new Date().toLocaleString("ru-RU"),
read: false,
flagged: false,
@@ -121,6 +123,7 @@ export function msgDataToMailMessage(reader: Pick<MsgReaderInstance, "getAttachm
const cc = msgRecipientList(data.recipients, "cc") || decodeMimeWords(headerFields.cc || "");
const bcc = msgRecipientList(data.recipients, "bcc") || decodeMimeWords(headerFields.bcc || "");
const replyTo = decodeMimeWords(headerFields["reply-to"] || "");
const bodyHtml = msgBodyHtml(data);
return {
id: `msg-${Date.now()}`,
folder: "inbox",
@@ -133,6 +136,7 @@ export function msgDataToMailMessage(reader: Pick<MsgReaderInstance, "getAttachm
...mailPriorityHeaders(headerFields),
subject: firstText(data.subject, decodeMimeWords(headerFields.subject || ""), "Без темы"),
body: msgBodyText(data),
...(bodyHtml ? { bodyHtml } : {}),
time: firstText(data.messageDeliveryTime, data.clientSubmitTime, data.creationTime, data.lastModificationTime, headerFields.date, new Date().toLocaleString("ru-RU")),
read: false,
flagged: false,
@@ -229,6 +233,31 @@ export function extractMessageBody(headers: MailHeaders, body: string): string {
return contentType.mediaType === "text/html" ? htmlToPlainText(decoded) : normalizeMailNewlines(decoded).trim();
}
export function extractMessageHtmlBody(headers: MailHeaders, body: string): string {
const contentType = parseContentType(headers["content-type"]);
if (contentType.mediaType.startsWith("multipart/")) {
const boundary = contentType.parameters.boundary;
if (!boundary) {
return "";
}
return (
parseMultipartBody(body, boundary)
.filter((part) => !isAttachmentPart(part.headers))
.filter((part) => isMessageBodyPart(part.headers))
.map((part) => extractMessageHtmlBody(part.headers, part.body))
.find((html) => html.trim()) ?? ""
);
}
if (contentType.mediaType !== "text/html") {
return "";
}
return decodeTransferBody(body, headers["content-transfer-encoding"], contentType.parameters.charset).trim();
}
export function extractMessageAttachments(headers: MailHeaders, body: string): MailAttachment[] {
return collectAttachmentParts(headers, body).map((part, index) => attachmentFromPart(part, index));
}
@@ -271,6 +300,19 @@ function msgBodyText(data: MsgFileData): string {
return "";
}
function msgBodyHtml(data: MsgFileData): string {
const htmlBody = firstText(data.bodyHtml);
if (htmlBody) {
return htmlBody;
}
if (data.html && data.html.byteLength > 0) {
return decodeBytes(data.html, msgCharset(data)).trim();
}
return "";
}
function msgCharset(data: MsgFileData) {
const headerFields = data.headers ? parseEmlHeaders(data.headers) : {};
return parseContentType(headerFields["content-type"]).parameters.charset || "utf-8";
@@ -417,8 +459,10 @@ export function parseContentType(value = "text/plain"): ParsedContentType {
export function buildEmlSource(message: MailMessage): string {
const attachments = message.attachments ?? [];
const hasHtmlBody = Boolean(message.bodyHtml?.trim());
if (attachments.length > 0) {
const boundary = createMultipartBoundary(message);
const alternativeBoundary = createAlternativeBoundary(message);
const lines = [
`From: ${sanitizeHeaderValue(message.from)}`,
`To: ${sanitizeHeaderValue(message.to)}`,
@@ -431,10 +475,7 @@ export function buildEmlSource(message: MailMessage): string {
`Content-Type: multipart/mixed; boundary="${boundary}"`,
"",
`--${boundary}`,
"Content-Type: text/plain; charset=utf-8",
"Content-Transfer-Encoding: 8bit",
"",
normalizeMailNewlines(message.body || ""),
...(hasHtmlBody ? buildAlternativePartLines(alternativeBoundary, message) : buildPlainTextPartLines(message)),
...attachments.flatMap((attachment) => buildAttachmentPartLines(boundary, attachment)),
`--${boundary}--`,
""
@@ -443,6 +484,30 @@ export function buildEmlSource(message: MailMessage): string {
return lines.join("\r\n");
}
if (hasHtmlBody) {
const boundary = createAlternativeBoundary(message);
const lines = [
`From: ${sanitizeHeaderValue(message.from)}`,
`To: ${sanitizeHeaderValue(message.to)}`,
...optionalAddressHeaders(message),
`Subject: ${encodeHeaderValue(message.subject || "Без темы")}`,
`Date: ${sanitizeHeaderValue(message.time || new Date().toUTCString())}`,
...optionalThreadHeaders(message),
...optionalPriorityHeaders(message),
"MIME-Version: 1.0",
`Content-Type: multipart/alternative; boundary="${boundary}"`,
"",
`--${boundary}`,
...buildPlainTextPartLines(message),
`--${boundary}`,
...buildHtmlPartLines(message),
`--${boundary}--`,
""
];
return lines.join("\r\n");
}
const lines = [
`From: ${sanitizeHeaderValue(message.from)}`,
`To: ${sanitizeHeaderValue(message.to)}`,
@@ -461,6 +526,26 @@ export function buildEmlSource(message: MailMessage): string {
return lines.join("\r\n");
}
function buildPlainTextPartLines(message: MailMessage): string[] {
return ["Content-Type: text/plain; charset=utf-8", "Content-Transfer-Encoding: 8bit", "", normalizeMailNewlines(message.body || "")];
}
function buildHtmlPartLines(message: MailMessage): string[] {
return ["Content-Type: text/html; charset=utf-8", "Content-Transfer-Encoding: 8bit", "", normalizeMailNewlines(message.bodyHtml || "")];
}
function buildAlternativePartLines(boundary: string, message: MailMessage): string[] {
return [
`Content-Type: multipart/alternative; boundary="${boundary}"`,
"",
`--${boundary}`,
...buildPlainTextPartLines(message),
`--${boundary}`,
...buildHtmlPartLines(message),
`--${boundary}--`
];
}
function optionalAddressHeaders(message: MailMessage): string[] {
return [
...(message.cc?.trim() ? [`Cc: ${sanitizeHeaderValue(message.cc)}`] : []),
@@ -659,6 +744,10 @@ function createMultipartBoundary(message: MailMessage): string {
return `qoffice-${normalizedSeed || "message"}`;
}
function createAlternativeBoundary(message: MailMessage): string {
return `${createMultipartBoundary(message)}-alternative`;
}
function buildAttachmentPartLines(boundary: string, attachment: MailAttachment): string[] {
const safeContentType = sanitizeMimeType(attachment.contentType);
const disposition = attachment.disposition === "inline" ? "inline" : "attachment";
+44
View File
@@ -1693,6 +1693,50 @@ button {
font-size: 15px;
}
.message-html-body {
max-width: 840px;
overflow-x: auto;
color: #111827;
font-size: 15px;
line-height: 1.58;
}
.message-html-body :where(p, ul, ol, blockquote, pre, table) {
margin: 0 0 12px;
}
.message-html-body :where(h1, h2, h3, h4, h5, h6) {
margin: 18px 0 10px;
color: #111827;
line-height: 1.25;
}
.message-html-body :where(ul, ol) {
padding-left: 22px;
}
.message-html-body table {
width: max-content;
max-width: 100%;
border-collapse: collapse;
}
.message-html-body :where(th, td) {
padding: 6px 8px;
border: 1px solid #d7dce5;
text-align: left;
vertical-align: top;
}
.message-html-body img {
max-width: 100%;
height: auto;
}
.message-html-body a {
color: #0f5fae;
}
.attachments-panel {
max-width: 760px;
margin-top: 24px;
+1
View File
@@ -145,6 +145,7 @@ export interface MailMessage {
priority?: string;
subject: string;
body: string;
bodyHtml?: string;
time: string;
read: boolean;
flagged: boolean;