From bb337f90e90fd718e2ab2e5f685378309d037d72 Mon Sep 17 00:00:00 2001 From: draos Date: Tue, 26 Nov 2024 21:40:36 +0100 Subject: [PATCH] Stabilize frontend API for non trivial mail content --- src/mail_devel/http.py | 23 +++++++++++++++++++---- src/mail_devel/smtp.py | 1 + 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/mail_devel/http.py b/src/mail_devel/http.py index 14e00a6..32941dd 100644 --- a/src/mail_devel/http.py +++ b/src/mail_devel/http.py @@ -35,6 +35,20 @@ def decode_header(value: str) -> str: return str(header.make_header(header.decode_header(value))) +def decode_payload(part: Message) -> str: + payload = part.get_payload(decode=True) + if isinstance(payload, bytes): + try: + return payload.decode() + except UnicodeDecodeError: + return "" + + if isinstance(payload, str): + return payload + + return "" + + def flags_to_api(flags: frozenset[Flag]) -> list[str]: return [f.value.decode().strip("\\").lower() for f in flags] @@ -67,6 +81,7 @@ class Frontend: def __init__( self, mailboxes: TestMailboxDict, + *, user: str, host: str = "", port: int = 8080, @@ -224,13 +239,13 @@ async def _convert_message( {"name": name, "url": f"/attachment/{msg_hash}/{name}"} ) elif ctype == "text/plain": - result["body_plain"] = part.get_payload(decode=True).decode() + result["body_plain"] = decode_payload(part) elif ctype == "text/html": - result["body_html"] = part.get_payload(decode=True).decode() + result["body_html"] = decode_payload(part) elif message.get_content_type() == "text/html": - result["body_html"] = message.get_payload(decode=True).decode() + result["body_html"] = decode_payload(message) else: - result["body_plain"] = message.get_payload(decode=True).decode() + result["body_plain"] = decode_payload(message) result["attachments"] = attachments result["content"] = bytes(content).decode() diff --git a/src/mail_devel/smtp.py b/src/mail_devel/smtp.py index 203daa0..d232ab3 100644 --- a/src/mail_devel/smtp.py +++ b/src/mail_devel/smtp.py @@ -38,6 +38,7 @@ class MemoryHandler(AsyncMessage): def __init__( self, mailboxes: TestMailboxDict, + *, flagged_seen: bool = False, ensure_message_id: bool = True, message_class: Type[Message] | None = None,