"""A tiny SMTP server that hands SigNoz's email to exe.dev's email gateway. SigNoz speaks SMTP; exe.dev VMs send mail with an HTTP call (https://exe.dev/docs/send-email). This listens on port 2525 inside the SigNoz Compose network (it is not published) and sends each message to each recipient through the gateway. The gateway takes plain text, so an HTML-only message (SigNoz's alert emails) is turned into text first. The gateway delivers only to the VM's owner, their exe.dev team, and people the VM is shared with who have signed in to it; mail to anyone else is dropped, with the gateway's reason in the log: docker compose -f ~/signoz/pours/deployment/compose.yaml logs exe-mailer """ import asyncio import email import email.policy import html import json import re import threading import urllib.error import urllib.request from html.parser import HTMLParser from aiosmtpd.controller import Controller GATEWAY = "http://169.254.169.254/gateway/email/send" class Text(HTMLParser): """Keeps the text of an HTML email, with line breaks and link targets.""" def __init__(self): super().__init__(convert_charrefs=True) self.out, self.skip = [], 0 def handle_starttag(self, tag, attrs): if tag in ("style", "script", "head"): self.skip += 1 elif tag in ("br", "p", "div", "tr", "h1", "h2", "h3", "li", "table"): self.out.append("\n") elif tag == "a": self.href = dict(attrs).get("href") def handle_endtag(self, tag): if tag in ("style", "script", "head"): self.skip = max(0, self.skip - 1) elif tag == "a" and getattr(self, "href", None): self.out.append(f" <{self.href}>") self.href = None elif tag in ("td", "th"): self.out.append(" ") def handle_data(self, data): if not self.skip: self.out.append(data) def to_text(markup): p = Text() p.feed(markup) lines = (re.sub(r"[ \t\xa0]+", " ", line).strip() for line in "".join(p.out).splitlines()) return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() def send(to, subject, body): req = urllib.request.Request( GATEWAY, data=json.dumps({"to": to, "subject": subject, "body": body}).encode(), headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(req, timeout=30) as r: r.read() class Relay: async def handle_DATA(self, server, session, envelope): msg = email.message_from_bytes(envelope.original_content, policy=email.policy.default) subject = " ".join(str(msg.get("Subject", "")).split()) or "(no subject)" part = msg.get_body(preferencelist=("plain", "html")) body = part.get_content() if part else "" if part is not None and part.get_content_type() == "text/html": body = to_text(body) for rcpt in envelope.rcpt_tos: try: await asyncio.to_thread(send, rcpt, subject, body) print(f"sent to {rcpt}: {subject}", flush=True) except urllib.error.HTTPError as e: print(f"gateway refused {rcpt}: {e.code} {e.read().decode(errors='replace')[:300]}", flush=True) except OSError as e: print(f"gateway unreachable for {rcpt}: {e}", flush=True) # Accept the message either way, so a refused address doesn't turn an # invitation into an error in SigNoz. The log says why. return "250 OK" Controller(Relay(), hostname="0.0.0.0", port=2525).start() print("mail relay listening on :2525", flush=True) threading.Event().wait()