"""Read a stored email (MIME) for display: headers, plain text, attachments.
Used by the browse view. Nothing here renders HTML: an HTML body becomes
text, so a backed-up message cannot run script or load remote images in
the admin's browser.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from email import policy
from email.message import EmailMessage, MIMEPart
from email.parser import BytesParser
from html.parser import HTMLParser
from typing import Any
[docs]
MAX_BODY = 200_000 # characters shown; the full message is in the .eml download
_BLOCK = frozenset(
{"p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6", "table", "blockquote", "hr"}
)
class _Text(HTMLParser):
"""Collect the visible text of an HTML document."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self._skip = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
"""Track hidden sections and line breaks."""
if tag in ("script", "style", "head", "title"):
self._skip += 1
elif tag in _BLOCK:
self.parts.append("\n")
def handle_endtag(self, tag: str) -> None:
"""Leave hidden sections; end blocks with a line break."""
if tag in ("script", "style", "head", "title"):
self._skip = max(0, self._skip - 1)
elif tag in _BLOCK:
self.parts.append("\n")
def handle_data(self, data: str) -> None:
"""Keep visible text."""
if not self._skip:
self.parts.append(data)
[docs]
def html_to_text(html: str) -> str:
"""Convert HTML to readable plain text.
Args:
html: An HTML document or fragment.
Returns:
The visible text with paragraph breaks.
"""
parser = _Text()
parser.feed(html)
parser.close()
text = "".join(parser.parts).replace("\xa0", " ")
text = re.sub(r"[ \t\r\f\v]+", " ", text)
text = re.sub(r" *\n *", "\n", text)
return re.sub(r"\n{3,}", "\n\n", text).strip()
@dataclass(slots=True)
[docs]
class MessageView:
"""An email prepared for display.
Attributes:
subject: Subject.
sender: From.
to: To.
cc: Cc.
date: Date header as sent.
body: Plain-text body (HTML converted), possibly truncated.
body_was_html: The body came from an HTML part.
truncated: The body was cut at :data:`MAX_BODY` characters.
attachments: ``{"filename", "content_type", "size"}`` per attachment.
"""
[docs]
body_was_html: bool = False
[docs]
truncated: bool = False
[docs]
attachments: list[dict[str, Any]] = field(default_factory=list)
def _text_of(part: MIMEPart) -> str:
try:
content = part.get_content()
except (LookupError, ValueError, AssertionError): # unknown charset or broken encoding
payload = part.get_payload(decode=True)
content = payload.decode("utf-8", "replace") if isinstance(payload, bytes) else ""
return content if isinstance(content, str) else ""
[docs]
def read_message(raw: bytes) -> MessageView:
"""Parse a MIME message for display.
Args:
raw: The message as stored (RFC 5322 / MIME).
Returns:
Headers, plain-text body and attachment list.
"""
msg = BytesParser(policy=policy.default).parsebytes(raw)
assert isinstance(msg, EmailMessage) # noqa: S101 - policy.default makes EmailMessage
view = MessageView(
subject=str(msg.get("subject", "") or ""),
sender=str(msg.get("from", "") or ""),
to=str(msg.get("to", "") or ""),
cc=str(msg.get("cc", "") or ""),
date=str(msg.get("date", "") or ""),
)
body_part = msg.get_body(preferencelist=("plain", "html"))
if body_part is not None:
text = _text_of(body_part)
if body_part.get_content_subtype() == "html":
text, view.body_was_html = html_to_text(text), True
if len(text) > MAX_BODY:
text, view.truncated = text[:MAX_BODY], True
view.body = text
for part in msg.iter_attachments():
payload = part.get_payload(decode=True)
name = part.get_filename()
if name is None and part.get_content_type() == "message/rfc822":
inner = part.get_payload()
first = inner[0] if isinstance(inner, list) and inner else None
subject = first.get("subject") if isinstance(first, EmailMessage) else None
name = f"{subject or 'message'}.eml"
view.attachments.append(
{
"filename": str(name or "(unnamed)"),
"content_type": part.get_content_type(),
"size": len(payload) if isinstance(payload, bytes) else len(str(part)),
}
)
return view