Spaces:
Running
Running
Update smtp-proxy.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149#!/usr/bin/env python3"""SMTP-to-Resend-API ProxyListens on localhost:2525 as an SMTP server,forwards all emails to Resend HTTP API.This avoids the slow SMTP connection from HF Spaces to smtp.resend.com."""
import osimport sysimport jsonimport emailimport asyncioimport loggingfrom email.mime.text import MIMETextfrom aiosmtpd.controller import Controllerfrom aiosmtpd.smtp import SMTPimport requests
RESEND_API_KEY = os.environ.get("RESEND_API_KEY", "")RESEND_API_URL = "https://api.resend.com/emails"LISTEN_PORT = int(os.environ.get("SMTP_PROXY_PORT", "2525"))ALLOWED_FROM_DOMAIN = os.environ.get("SMTP_FROM_DOMAIN", "") # e.g. iwara.ccwu.cc
logging.basicConfig( level=logging.INFO, format="%(asctime)s [SMTP-PROXY] %(message)s",)log = logging.getLogger(__name__)
class ResendAPIHandler: async def handle_DATA(self, server, session, envelope): mail_from = envelope.mail_from rcpt_tos = envelope.rcpt_tos data = envelope.content
if isinstance(data, bytes): data = data.decode("utf-8", errors="replace")
log.info(f"Received email from={mail_from} to={rcpt_tos}")
# Validate sender domain if configured if ALLOWED_FROM_DOMAIN: from_domain = mail_from.split("@")[-1].lower() if "@" in mail_from else "" if from_domain != ALLOWED_FROM_DOMAIN.lower(): log.warning(f"Rejected email from unauthorized domain: {mail_from}") return "550 Sender domain not allowed"
# Parse the email msg = email.message_from_string(data)
# Properly decode RFC 2047 encoded headers (e.g. =?UTF-8?B?...?=) from email.header import decode_header def decode_header_value(value): if not value: return "" decoded_parts = decode_header(value) result = [] for part, charset in decoded_parts: if isinstance(part, bytes): result.append(part.decode(charset or "utf-8", errors="replace")) else: result.append(part) return "".join(result)
subject = decode_header_value(msg.get("Subject", "")) from_addr = decode_header_value(msg.get("From", mail_from))
# Extract HTML body directly from raw data # CRITICAL: Do NOT use msg.get_payload(decode=True) - Python's email library # converts UTF-8 Chinese chars to \uXXXX Unicode escapes when there's no # Content-Transfer-Encoding header. Go's net/smtp doesn't set this header, # causing Python to misinterpret the payload. # Instead, split raw data at the header/body boundary. html_body = "" if "\r\n\r\n" in data: html_body = data.split("\r\n\r\n", 1)[1] elif "\n\n" in data: html_body = data.split("\n\n", 1)[1]
# Strip trailing \r\n or \n if html_body.endswith("\r\n"): html_body = html_body[:-2] elif html_body.endswith("\n"): html_body = html_body[:-1]
# Send via Resend API if not RESEND_API_KEY: log.error("RESEND_API_KEY not set, cannot send email") return "550 RESEND_API_KEY not configured"
try: # Manual JSON serialization with ensure_ascii=False # Python's requests.post(json=...) uses json.dumps(ensure_ascii=True) # which converts Chinese chars to \uXXXX escape sequences payload = json.dumps({ "from": from_addr, "to": rcpt_tos, "subject": subject, "html": html_body, }, ensure_ascii=False)
resp = requests.post( RESEND_API_URL, headers={ "Authorization": f"Bearer {RESEND_API_KEY}", "Content-Type": "application/json; charset=utf-8", }, data=payload.encode("utf-8"), timeout=30, ) if resp.status_code == 200: resp_data = resp.json() log.info(f"Email sent via Resend API: id={resp_data.get('id', '?')}") return "250 OK" else: log.error(f"Resend API error: {resp.status_code} {resp.text[:200]}") return f"550 Delivery failed" except Exception as e: log.error(f"Failed to send via Resend API: {e}") return "550 Delivery failed"
async def main(): if not RESEND_API_KEY: log.warning("RESEND_API_KEY not set! Emails will not be sent.")
handler = ResendAPIHandler() controller = Controller( handler, hostname="127.0.0.1", port=LISTEN_PORT, )
controller.start() log.info(f"SMTP proxy listening on 127.0.0.1:{LISTEN_PORT}") log.info(f"Forwarding to Resend API at {RESEND_API_URL}")
# Keep running try: await asyncio.Event().wait() except (KeyboardInterrupt, SystemExit): log.info("Shutting down...") controller.stop()
if __name__ == "__main__": asyncio.run(main())smtp-proxy.pyAdded+149