diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.py index 572b5c11455d3..864cf4626e677 100644 --- a/plugins/platforms/email/adapter.py +++ b/plugins/platforms/email/adapter.py @@ -46,6 +46,92 @@ from utils import env_int, env_bool logger = logging.getLogger(__name__) + +# ── HTML Email Styling ────────────────────────────────────────────────────── +# Inline CSS for maximum email client compatibility (Gmail, Outlook, Apple Mail). + +_HTML_PREFIX = """\ + + +
+ + tag loop,
+ # otherwise the general loop adds style= to first and the
+ # override regex (?![^>]*style=) can no longer match.
+ html = re.sub(
+ r'(]*>.*?)]*style=)(\s|>)',
+ r'\1]*style=)(\s|>)',
+ rf'<{tag} {style}\1',
+ html,
+ )
+ return html
+
# Automated sender patterns — emails from these are silently ignored
_NOREPLY_PATTERNS = (
"noreply", "no-reply", "no_reply", "donotreply", "do-not-reply",
@@ -447,6 +533,7 @@ def __init__(self, config: PlatformConfig):
# email:
# skip_attachments: true
self._skip_attachments = extra.get("skip_attachments", False)
+ self._html_format = extra.get("html_format", True)
# Require the sender's From: domain to be authenticated (SPF/DKIM/DMARC)
# before trusting it for authorization. The From: header is
@@ -946,7 +1033,7 @@ def _send_email(
msg_id = f""
msg["Message-ID"] = msg_id
- msg.attach(MIMEText(body, "plain", "utf-8"))
+ self._attach_body(msg, body)
smtp = self._connect_smtp()
try:
@@ -964,6 +1051,74 @@ def _send_email(
async def send_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""Email has no typing indicator — no-op."""
+ # ── HTML email helpers ──────────────────────────────────────────────────
+
+ def _attach_body(self, msg: MIMEMultipart, body: str) -> None:
+ """Attach body as plain text + optional HTML to a message.
+
+ Always wraps in multipart/alternative so email clients correctly
+ choose between plain and HTML representations.
+ """
+ alt = MIMEMultipart("alternative")
+ self._attach_parts(alt, body)
+ msg.attach(alt)
+
+ def _create_body_part(self, body: str) -> MIMEMultipart:
+ """Create a multipart/alternative body part (for use inside multipart/mixed)."""
+ alt = MIMEMultipart("alternative")
+ self._attach_parts(alt, body)
+ return alt
+
+ def _attach_parts(self, container: MIMEMultipart, body: str) -> None:
+ """Attach plain + optional HTML parts to a multipart container."""
+ # Check if body already contains HTML (from cron/model output).
+ # Models sometimes produce full HTML documents or fragments with
+ # preamble text before the first HTML tag.
+ html_match = _HTML_RE.search(body)
+ if html_match and self._html_format:
+ # Body already contains HTML — strip preamble and trailing
+ # commentary, then send as multipart/alternative.
+ html_body = body[html_match.start():]
+
+ # Strip content after