Spaces:
Running
Running
OpenCode Bot commited on
Commit ·
11d5d1b
1
Parent(s): 49be412
Proxy Resend email delivery over HTTPS
Browse filesFiles changed (4)
- Dockerfile+14-2
- README.md+2
- smtp-proxy.pyAdded+201
- start.shAdded+15
1123456789101112131415166 unmodified lines2324251426FROM calciumion/new-api:latestFROM calciumion/new-api:latest AS upstream
FROM python:3.13-slim
RUN apt-get update \ && apt-get install -y --no-install-recommends ca-certificates tzdata \ && rm -rf /var/lib/apt/lists/* \ && update-ca-certificates
COPY --from=upstream /new-api /new-apiCOPY smtp-proxy.py /app/smtp-proxy.pyCOPY start.sh /app/start.shRUN chmod +x /app/start.sh
ENV PORT=7860 \ TZ=Asia/Shanghai \6 unmodified linesRUN mkdir -p /dataWORKDIR /data
CMD ["sh", "-c", "echo SQL_DSN configured: ${SQL_DSN:+yes}; echo SESSION_SECRET configured: ${SESSION_SECRET:+yes}; exec /new-api"]CMD ["/app/start.sh"]15 unmodified lines16171819202115 unmodified lines
Deployment uses the upstream Docker image and keeps secrets in Hugging Face settings.
Email delivery is proxied locally from `smtp.resend.com:587` to Resend's HTTPS API to avoid SMTP hangs from Hugging Face Spaces.
Runtime configuration is provided through Hugging Face Space secrets and variables.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#!/usr/bin/env python3import asyncioimport base64import jsonimport loggingimport osimport reimport urllib.requestfrom email import message_from_bytesfrom email.header import decode_header
RESEND_API_URL = "https://api.resend.com/emails"LISTEN_HOST = "127.0.0.1"LISTEN_PORT = 587FALLBACK_API_KEY = os.environ.get("RESEND_API_KEY", "").strip()
logging.basicConfig(level=logging.INFO, format="%(asctime)s [smtp-proxy] %(message)s")log = logging.getLogger(__name__)
def decode_header_value(value: str) -> str: parts = [] for item, charset in decode_header(value or ""): if isinstance(item, bytes): parts.append(item.decode(charset or "utf-8", errors="replace")) else: parts.append(item) return "".join(parts)
def parse_addr(value: str) -> str: match = re.search(r"<([^>]+)>", value or "") return (match.group(1) if match else value).strip()
def parse_plain_auth(value: str) -> tuple[str, str]: raw = base64.b64decode(value.encode("ascii"), validate=False).decode("utf-8", errors="replace") parts = raw.split("\x00") if len(parts) >= 3: return parts[-2], parts[-1] if len(parts) == 2: return parts[0], parts[1] return "", raw
def extract_body(data: bytes) -> str: text = data.decode("utf-8", errors="replace") if "\r\n\r\n" in text: return text.split("\r\n\r\n", 1)[1].rstrip("\r\n") if "\n\n" in text: return text.split("\n\n", 1)[1].rstrip("\n") return text
def send_resend(api_key: str, mail_from: str, rcpts: list[str], data: bytes) -> tuple[bool, str]: if not api_key: return False, "missing Resend API key"
msg = message_from_bytes(data) subject = decode_header_value(msg.get("Subject", "")) from_header = decode_header_value(msg.get("From", "")) from_addr = from_header or mail_from html = extract_body(data) payload = json.dumps({"from": from_addr, "to": rcpts, "subject": subject, "html": html}, ensure_ascii=False).encode("utf-8") request = urllib.request.Request( RESEND_API_URL, data=payload, headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json; charset=utf-8", }, method="POST", ) try: with urllib.request.urlopen(request, timeout=15) as response: body = response.read(500).decode("utf-8", errors="replace") if 200 <= response.status < 300: return True, body return False, f"HTTP {response.status}: {body}" except Exception as exc: return False, str(exc)
class SMTPSession: def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter): self.reader = reader self.writer = writer self.mail_from = "" self.rcpts: list[str] = [] self.api_key = FALLBACK_API_KEY
async def send(self, line: str) -> None: self.writer.write((line + "\r\n").encode("utf-8")) await self.writer.drain()
async def read_line(self) -> str: data = await asyncio.wait_for(self.reader.readline(), timeout=60) if not data: return "" return data.decode("utf-8", errors="replace").rstrip("\r\n")
async def handle_auth_plain(self, arg: str) -> None: if not arg: await self.send("334 ") arg = await self.read_line() _, password = parse_plain_auth(arg) self.api_key = password.strip() or self.api_key await self.send("235 2.7.0 Authentication successful")
async def handle_auth_login(self) -> None: await self.send("334 VXNlcm5hbWU6") await self.read_line() await self.send("334 UGFzc3dvcmQ6") password_b64 = await self.read_line() try: self.api_key = base64.b64decode(password_b64.encode("ascii"), validate=False).decode("utf-8", errors="replace").strip() or self.api_key except Exception: pass await self.send("235 2.7.0 Authentication successful")
async def handle_data(self) -> None: await self.send("354 End data with <CR><LF>.<CR><LF>") chunks: list[bytes] = [] while True: line = await asyncio.wait_for(self.reader.readline(), timeout=120) if line in {b".\r\n", b".\n", b"."}: break if line.startswith(b".."): line = line[1:] chunks.append(line) payload = b"".join(chunks) ok, detail = await asyncio.to_thread(send_resend, self.api_key, self.mail_from, self.rcpts, payload) if ok: log.info("sent email via Resend API to=%s", self.rcpts) await self.send("250 2.0.0 OK") else: log.error("Resend delivery failed: %s", detail) await self.send("550 5.0.0 Delivery failed")
async def run(self) -> None: await self.send("220 smtp.resend.com ESMTP") while True: line = await self.read_line() if not line: break command, _, arg = line.partition(" ") upper = command.upper() if upper in {"EHLO", "HELO"}: await self.send("250-smtp.resend.com") await self.send("250-AUTH PLAIN LOGIN") await self.send("250 8BITMIME") elif upper == "AUTH": mech, _, rest = arg.partition(" ") if mech.upper() == "PLAIN": await self.handle_auth_plain(rest.strip()) elif mech.upper() == "LOGIN": await self.handle_auth_login() else: await self.send("504 5.5.4 Unrecognized authentication type") elif upper == "MAIL": self.mail_from = parse_addr(arg.split(":", 1)[-1]) await self.send("250 2.1.0 OK") elif upper == "RCPT": self.rcpts.append(parse_addr(arg.split(":", 1)[-1])) await self.send("250 2.1.5 OK") elif upper == "DATA": await self.handle_data() elif upper == "RSET": self.mail_from = "" self.rcpts = [] await self.send("250 2.0.0 OK") elif upper == "NOOP": await self.send("250 2.0.0 OK") elif upper == "QUIT": await self.send("221 2.0.0 Bye") break else: await self.send("502 5.5.1 Command not implemented") self.writer.close() await self.writer.wait_closed()
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: try: await SMTPSession(reader, writer).run() except Exception as exc: log.error("SMTP session failed: %s", exc) writer.close() await writer.wait_closed()
async def main() -> None: server = await asyncio.start_server(handle_client, LISTEN_HOST, LISTEN_PORT) log.info("listening on %s:%s and forwarding to Resend API", LISTEN_HOST, LISTEN_PORT) async with server: await server.serve_forever()
if __name__ == "__main__": asyncio.run(main())123456789101112131415#!/bin/shset -eu
echo "Starting local SMTP-to-Resend API proxy on 127.0.0.1:587..."printf '\n127.0.0.1 smtp.resend.com\n' >> /etc/hostspython3 /app/smtp-proxy.py &PROXY_PID=$!
sleep 1if ! kill -0 "$PROXY_PID" 2>/dev/null; then echo "WARNING: SMTP proxy failed to start; email verification may fail"fi
echo "Starting new-api..."exec /new-apiDockerfile+14-2
README.md+2
smtp-proxy.pyAdded+201
start.shAdded+15