Add bounce mailbox processing

This commit is contained in:
2026-07-31 22:48:07 +02:00
parent 2721ee6542
commit fe309dbff5
13 changed files with 1770 additions and 7 deletions
@@ -5,6 +5,8 @@ import hashlib
import json
from collections import Counter
from datetime import datetime, timedelta, timezone
from email import policy
from email.parser import BytesParser
from typing import Any
from sqlalchemy import or_, select
@@ -105,6 +107,18 @@ def _message_bytes(command: MailDeliveryCommand) -> bytes:
return message
def _rfc_message_id(message: bytes) -> str | None:
try:
value = BytesParser(policy=policy.default).parsebytes(
message,
headersonly=True,
).get("Message-ID")
except Exception:
return None
normalized = " ".join(str(value or "").split())
return normalized[:998] or None
def _delivery_payload(
*,
command_type: str,
@@ -169,6 +183,7 @@ def submit_delivery_command(
if retention_days < 1:
raise MailDeliveryError("Mail payload retention must be at least one day")
digest = hashlib.sha256(message_bytes).hexdigest()
rfc_message_id = _rfc_message_id(message_bytes)
request_hash = _canonical_hash(
_delivery_payload(
command_type=command_type,
@@ -219,6 +234,7 @@ def submit_delivery_command(
from_header_encrypted=encrypt_secret(from_header),
message_encrypted=encrypt_secret(base64.b64encode(message_bytes).decode("ascii")),
message_sha256=digest,
rfc_message_id=rfc_message_id,
message_size_bytes=len(message_bytes),
recipient_count=len(clean_recipients),
status="pending",
@@ -299,6 +315,7 @@ def delivery_command_summary(
"failure_code": command.failure_code,
"failure_summary": command.failure_summary,
"message_sha256": command.message_sha256,
"rfc_message_id": command.rfc_message_id,
"message_size_bytes": command.message_size_bytes,
"created_at": command.created_at,
"completed_at": command.completed_at,