Skip to content

Commit

Permalink
Stabilize frontend API for non trivial mail content
Browse files Browse the repository at this point in the history
  • Loading branch information
fkantelberg committed Nov 26, 2024
1 parent cf82b47 commit bb337f9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/mail_devel/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -67,6 +81,7 @@ class Frontend:
def __init__(
self,
mailboxes: TestMailboxDict,
*,
user: str,
host: str = "",
port: int = 8080,
Expand Down Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions src/mail_devel/smtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit bb337f9

Please sign in to comment.