#!/usr/bin/env python3 """A tiny SMTP server that hands mail to exe.dev's email gateway. Apps that only speak SMTP (Metabase, for one) can send email from an exe.dev VM without an outside mail service. Each message becomes one plain-text email per recipient through http://169.254.169.254/gateway/email/send (https://exe.dev/docs/send-email): the text part is used as is, an HTML-only message is turned into text, and images and attached files are attached. No TLS and no passwords: listen only where your app can reach it, never on a port the internet can. Standard library only. SMTP_RELAY_LISTEN address to listen on (default 127.0.0.1) SMTP_RELAY_PORT port (default 2525) EXE_EMAIL_GATEWAY gateway URL (default as above) """ import asyncio, base64, email, email.policy, html.parser, json, os, re, sys import urllib.error, urllib.request LISTEN = os.environ.get("SMTP_RELAY_LISTEN", "127.0.0.1") PORT = int(os.environ.get("SMTP_RELAY_PORT", "2525")) GATEWAY = os.environ.get("EXE_EMAIL_GATEWAY", "http://169.254.169.254/gateway/email/send") MAX_MESSAGE = 25 * 1024 * 1024 # The gateway's limits (Nov 2026): 10 attachments, 1 MiB in all. MAX_ATTACHMENTS = 10 MAX_ATTACHMENT_BYTES = 1024 * 1024 def log(*args): print(*args, file=sys.stderr, flush=True) class HTMLText(html.parser.HTMLParser): """Just enough HTML to text for emails: blocks, links, image names.""" BLOCK = {"p", "div", "br", "tr", "li", "table", "hr", "h1", "h2", "h3", "h4", "h5", "h6"} SKIP = {"style", "script", "head", "title"} def __init__(self, cid_names): super().__init__(convert_charrefs=True) self.out, self.skip, self.links, self.cid_names = [], 0, [], cid_names def handle_starttag(self, tag, attrs): a = dict(attrs) if tag in self.SKIP: self.skip += 1 elif tag in self.BLOCK: self.out.append("\n") elif tag in ("td", "th"): self.out.append(" ") elif tag == "a": self.links.append((a.get("href") or "", len(self.out))) elif tag == "img": src = a.get("src") or "" name = self.cid_names.get(src[4:].strip("<>")) if src.startswith("cid:") else None label = name or a.get("alt") or "" if label: self.out.append(f"[image: {label}]") def handle_endtag(self, tag): if tag in self.SKIP: self.skip = max(0, self.skip - 1) elif tag in self.BLOCK: self.out.append("\n") elif tag in ("td", "th"): self.out.append(" ") elif tag == "a" and self.links: href, start = self.links.pop() text = "".join(self.out[start:]).strip() if href.startswith(("http://", "https://")) and href != text: self.out.append(f" <{href}>") def handle_data(self, data): if not self.skip: self.out.append(data) def text(self): lines = [re.sub(r"[ \t\r\f\v\xa0]+", " ", l).strip() for l in "".join(self.out).split("\n")] return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() + "\n" def convert(raw): """Return (subject, body text, attachments) for one MIME message.""" msg = email.message_from_bytes(raw, policy=email.policy.default) subject = str(msg.get("subject") or "(no subject)") body_part = msg.get_body(preferencelist=("plain", "html")) attachments, cid_names = [], {} for n, part in enumerate(msg.walk()): if part.is_multipart() or part is body_part: continue ctype = part.get_content_type() if ctype in ("text/plain", "text/html") and part.get_content_disposition() != "attachment": continue # the other half of a text/HTML pair data = part.get_payload(decode=True) or b"" cid = (part.get("content-id") or "").strip("<> ") if cid and part.get_content_disposition() != "attachment": if len(data) < 1024: continue # icons and spacers name = f"image-{sum(1 for a in attachments if a['filename'].startswith('image-')) + 1}.{part.get_content_subtype()}" cid_names[cid] = name else: name = part.get_filename() or f"part-{n}.{part.get_content_subtype()}" attachments.append({"filename": name, "content_type": ctype, "data": data, "file": part.get_content_disposition() == "attachment"}) if body_part is None: body = "" elif body_part.get_content_type() == "text/html": parser = HTMLText(cid_names) parser.feed(body_part.get_content()) body = parser.text() else: body = body_part.get_content() # Attached files (CSV, XLSX) first, then images, while they fit. kept, total, left_out = [], 0, [] for a in sorted(attachments, key=lambda a: not a["file"]): if len(kept) < MAX_ATTACHMENTS and total + len(a["data"]) <= MAX_ATTACHMENT_BYTES: kept.append({"filename": a["filename"], "content_type": a["content_type"], "content": base64.b64encode(a["data"]).decode()}) total += len(a["data"]) else: left_out.append(a["filename"]) if left_out: body += f"\n(Too big for one email, left out: {', '.join(left_out)})\n" return subject, body, kept def post(payload): req = urllib.request.Request(GATEWAY, data=json.dumps(payload).encode(), method="POST", headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=60) as r: return None, r.read().decode(errors="replace") except urllib.error.HTTPError as e: return f"HTTP {e.code}: {e.read().decode(errors='replace').strip()}", None except OSError as e: return str(e), None def deliver(rcpts, raw): """Send to each recipient; return None, or the first error.""" subject, body, attachments = convert(raw) first_error = None for to in rcpts: payload = {"to": to, "subject": subject, "body": body or "(empty message)"} if attachments: payload["attachments"] = attachments err, _ = post(payload) if err and attachments: # The gateway limits attachments; send the text anyway. log(f"to {to}: with {len(attachments)} attachments: {err}; retrying without") payload.pop("attachments") payload["body"] += f"\n\n({len(attachments)} attachment(s) left out: {err})\n" err, _ = post(payload) log(f"to {to}: {subject!r}: {err or 'sent'}") first_error = first_error or err return first_error async def session(reader, writer): async def reply(line): writer.write(line.encode() + b"\r\n") await writer.drain() rcpts = [] await reply("220 smtp-relay ESMTP") try: while line := await reader.readline(): cmd = line.decode(errors="replace").strip() verb = cmd[:4].upper() if verb == "EHLO": await reply(f"250-smtp-relay\r\n250-8BITMIME\r\n250 SIZE {MAX_MESSAGE}") elif verb == "HELO": await reply("250 smtp-relay") elif verb == "MAIL": rcpts = [] await reply("250 OK") elif verb == "RCPT": m = re.search(r"<([^>]*)>", cmd) if not m or "@" not in m.group(1): await reply("501 Bad recipient") continue rcpts.append(m.group(1)) await reply("250 OK") elif verb == "DATA": if not rcpts: await reply("503 No recipients") continue await reply("354 End data with .") lines, size = [], 0 while (l := await reader.readline()) not in (b".\r\n", b".\n", b""): size += len(l) if size <= MAX_MESSAGE: lines.append(l[1:] if l.startswith(b".") else l) if size > MAX_MESSAGE: await reply("552 Message too large") else: err = await asyncio.to_thread(deliver, rcpts, b"".join(lines)) await reply("250 OK sent" if not err else f"554 {err[:400]}") rcpts = [] elif verb == "RSET": rcpts = [] await reply("250 OK") elif verb == "NOOP": await reply("250 OK") elif verb == "QUIT": await reply("221 Bye") break else: await reply("502 Not implemented") except (ConnectionError, asyncio.IncompleteReadError): pass finally: writer.close() async def main(): server = await asyncio.start_server(session, LISTEN, PORT, limit=MAX_MESSAGE) log(f"smtp-relay listening on {LISTEN}:{PORT}, sending through {GATEWAY}") async with server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main())