submit.py SMTP :587 + otp_api.py mailbox API, imap_code strict-parse fix, auto.py SPF, login.py uid-select, READMEs
This commit is contained in:
@@ -17,6 +17,8 @@ python auto.py --domains 2 --mail cf --serve
|
||||
| DNS records | `setup_dns.py` | A / MX / TXT / CNAME + NS change via in-page `/user_ym/jx_edit`; auto-handles operation-protection (czyz): channel enable `[1,4]`, challenge → email code → `aqbh_check`, tokenless `-101` session unlock → retry, and slider-gated email send (`code -105001` → site `slide_yz` popup → one-time code → `re_yzm` param). Wrong codes latch a ~1h block server-side — never brute-force codes |
|
||||
| Self-hosted catch-all | `mail_catcher/catcher.py` | **RECOMMENDED**: tiny aiosmtpd MX server on your VPS (:25) — accepts `*@yourdomains`, stores `.eml`, relays copy to Gmail (SMTP_SSL 465). Works where free relays denylist the domain (ForwardEmail denylists all of `eu.cc`) |
|
||||
| DNS record cleanup | `dns_clean.py` | `POST /user_ym/get_jx_list` → `/user_ym/jx_del`: purge stale records (`--match forwardemail`, `--ip 1.2.3.4`) |
|
||||
| Outbound SMTP | `mail_catcher/submit.py` | Send mail **as your domain**: authenticated submission on VPS `:587` (LOGIN + STARTTLS), direct-MX delivery with automatic Gmail-relay fallback when outbound :25 is blocked. SPF TXT set automatically by `auto.py --mail dns` |
|
||||
| OTP mailbox API | `mail_catcher/otp_api.py` | stdlib HTTP `:2525` over the catcher's mail store: `/next` issues a fresh mailbox, `/latest?address=..&wait=60` long-polls the OTP and parses the code, `/acquire`, `/list`, `/health` — register-then-read-OTP without IMAP |
|
||||
| ForwardEmail mail | *(via `auto.py --mail fwd`)* | MX `mx1/mx2.forwardemail.net` + TXT `forward-email=DEST` through gname DNS. NOTE: ForwardEmail **denylists `eu.cc`** (5.1.1 at SMTP) — use `mail_catcher` for these domains |
|
||||
| Cloudflare mail | `cf_mail.py` | Pure API: create zone → enable Email Routing → destination address → **catch-all rule** (every `*@yourdomain` forwards to your Gmail). MX/SPF auto-created by CF |
|
||||
| Orchestration | `auto.py` | login → claim N → mail setup → NS switch → `data/status.json` |
|
||||
@@ -46,6 +48,7 @@ export DNS_A_IP=YOUR_VPS_IP
|
||||
python auto.py --domains 3 --mail dns # A mail->IP + MX @->mail.domain (prio 5)
|
||||
```
|
||||
Proven chain: external sender → public MX `mail.<domain>.eu.cc` → VPS :25 catcher → `.eml` stored + relayed to Gmail (`[catch otp-...@domain]` subject, verification code in body — `imap_code`/dashboard read it). Works for 3/3 live domains.
|
||||
Proven outbound chain: client → VPS `:587` (auth LOGIN, TLS) → Gmail relay fallback → recipient inbox with `From: you@yourdomain` (marker test found in INBOX). Proven OTP loop: `/next` → mail to issued address → `/latest?wait=90` → `CODE VALID: True` (see `mail_catcher/README.md`).
|
||||
Purge stale records anytime: `python dns_clean.py <domain> --match forwardemail` / `--ip OLD_IP`.
|
||||
|
||||
### ForwardEmail (non-denylisted domains only)
|
||||
|
||||
@@ -127,7 +127,8 @@ def main():
|
||||
elif args.mail == "dns":
|
||||
ip = os.environ.get("DNS_A_IP", "")
|
||||
a_args = ["--a", "mail=" + ip] if ip else []
|
||||
run("setup_dns.py", dom, *a_args, "--mx", "@=mail." + dom + ":5")
|
||||
t_args = ["--txt", "@=v=spf1 ip4:" + ip + " ~all"] if ip else []
|
||||
run("setup_dns.py", dom, *a_args, "--mx", "@=mail." + dom + ":5", *t_args)
|
||||
st[dom]["mail"] = "self-hosted-mx"
|
||||
else:
|
||||
st[dom]["mail"] = st[dom].get("mail", "pending")
|
||||
|
||||
+15
-4
@@ -349,11 +349,22 @@ def imap_code(wait=240, min_ts=0):
|
||||
for p in msg.walk():
|
||||
if p.get_content_type() == "text/html":
|
||||
body_html = p.get_payload(decode=True).decode("utf-8", "ignore")
|
||||
if "Reason for failure" in body or "incorrect or has expired" in body:
|
||||
stripped = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", body_html))
|
||||
subj_raw = msg.get("Subject", "") or ""
|
||||
if ("Reason for failure" in body or "incorrect or has expired" in body
|
||||
or "Reason for failure" in stripped
|
||||
or "removed_failed" in subj_raw or "removed failed" in subj_raw.lower()):
|
||||
continue # skip aqbh failure-notice mails
|
||||
mm = (re.search(r"(?:verification code is|code is|code|验证码)\s*[::]?\s*(\d{4,8})", body, re.I)
|
||||
or re.search(r"(?:verification code is|code is|code|验证码)\s*[::]?\s*(\d{4,8})", body_html, re.I)
|
||||
or re.search(r"\b(\d{6})\b", body) or re.search(r"\b(\d{6})\b", body_html))
|
||||
# strict first: HTML tags sit between 'code is :' and the number, so
|
||||
# always search the tag-stripped text; the loose \d{6} fallback must
|
||||
# never grab the 'Dear user <uid>' number.
|
||||
mm = (re.search(r"(?:verification code is|code is|验证码)\s*[::]?\s*(\d{4,8})", body, re.I)
|
||||
or re.search(r"(?:verification code is|code is|验证码)\s*[::]?\s*(\d{4,8})", stripped, re.I)
|
||||
or re.search(r"(?:verification code is|code is|code|验证码)\s*[::]?\s*(\d{4,8})", body_html, re.I))
|
||||
if not mm:
|
||||
cand = re.sub(r"Dear user\s*\d+", "Dear user", stripped)
|
||||
cand = re.sub(r"Account ID\s*\d+", "Account ID", cand)
|
||||
mm = re.search(r"\b(\d{6})\b", cand)
|
||||
m.logout()
|
||||
if mm:
|
||||
return mm.group(1)
|
||||
|
||||
@@ -12,11 +12,21 @@ from gname_core import (BASE, COOKIES_F, SITE, UA, log, mk_context,
|
||||
save_cookies, human_drag, vl_solve_image)
|
||||
|
||||
def pick_creds():
|
||||
idx = int(sys.argv[1]) if len(sys.argv) > 1 else None
|
||||
if idx is not None:
|
||||
# argv[1] = bank index OR uid; env GNAME_UID also selects by uid
|
||||
sel = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("GNAME_UID", "")
|
||||
if sel:
|
||||
bank_f = os.path.join(BASE, "gname_accounts.jsonl")
|
||||
bank = [json.loads(l) for l in open(bank_f, encoding="utf-8") if l.strip()]
|
||||
acc = bank[idx]
|
||||
acc = None
|
||||
if sel.isdigit():
|
||||
by_uid = [a for a in bank if str(a.get("uid")) == sel]
|
||||
if by_uid:
|
||||
acc = by_uid[0]
|
||||
else:
|
||||
acc = bank[int(sel)]
|
||||
if acc is None:
|
||||
raise SystemExit("account not found: " + sel)
|
||||
log("BANK PICK: uid", acc.get("uid"), acc.get("email"))
|
||||
return acc["email"], acc["password"]
|
||||
e, p = os.environ.get("GNAME_EMAIL", ""), os.environ.get("GNAME_PASSWORD", "")
|
||||
if not (e and p):
|
||||
@@ -71,6 +81,18 @@ def main():
|
||||
log("BODY:", body)
|
||||
ok = "/user" in page.url or "ID:" in page.locator("body").inner_text()[:3000]
|
||||
save_cookies(ctx)
|
||||
# identity proof: list domains of the logged-in account
|
||||
if ok:
|
||||
try:
|
||||
from gname_core import inpost_json, csrf
|
||||
r = inpost_json(page, "/user_ym/get_ym_list",
|
||||
{"page": 1, "limit": 50, "csrf_token": csrf(page)}, "idcheck")
|
||||
data = (r or {}).get("data") or {}
|
||||
lst = data.get("data") if isinstance(data, dict) else data
|
||||
doms = [x.get("ym") for x in (lst or [])]
|
||||
log("ACCOUNT DOMAINS:", doms if doms else "(none)")
|
||||
except Exception as e:
|
||||
log("ACCOUNT DOMAINS: err", str(e)[:80])
|
||||
browser.close()
|
||||
log("LOGIN:", "OK" if ok else "CHECK-MANUALLY")
|
||||
return 0 if ok else 1
|
||||
|
||||
@@ -52,3 +52,43 @@ journalctl -u mailcatch -n 5 # should log '(relayed)'
|
||||
|
||||
Proven: gname `.eu.cc` domains → VPS MX → Gmail inbox, verification code visible in body
|
||||
(subject `[catch otp-...@domain]`), stored `.eml` on the box.
|
||||
|
||||
## submit.py — outbound SMTP (send AS your domain)
|
||||
Authenticated submission on `:587` (LOGIN, password = `sp` in `env.json`), STARTTLS if
|
||||
`cert.pem`+`key.pem` are present (self-signed is fine for MUA use). Delivery: direct to
|
||||
recipient MX on `:25`; if the host blocks outbound 25 (most VPS do), it **falls back to a
|
||||
Gmail relay** using `gm`/`gp` from `env.json` — `From:` header keeps your domain address.
|
||||
|
||||
```
|
||||
cat >> /root/mailcatch/env.json # merge {"sp": "<random-pass>"} into existing JSON
|
||||
# self-signed TLS (optional):
|
||||
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 825 -nodes -subj "/CN=mail.yourdomain"
|
||||
# systemd: mailsubmit.service, ExecStart=/usr/bin/python3 /root/mailcatch/submit.py
|
||||
```
|
||||
Client test (proven E2E: accepted → Gmail INBOX, marker in subject):
|
||||
```python
|
||||
import smtplib, ssl
|
||||
s = smtplib.SMTP("VPS_IP", 587, timeout=45); s.ehlo()
|
||||
s.starttls(context=ssl._create_unverified_context()); s.ehlo()
|
||||
s.login("anything@yourdomain", "<sp>")
|
||||
s.sendmail("me@yourdomain", ["you@gmail.com"],
|
||||
"From: me@yourdomain\r\nTo: you@gmail.com\r\nSubject: hi\r\n\r\nbody")
|
||||
```
|
||||
Note: aiosmtpd 1.4.6 requires the authenticator to return
|
||||
`AuthResult(success=..., handled=..., auth_data=...)` — plain `bool` authenticates but
|
||||
leaves `session.authenticated` unset (MAIL FROM → 530). `submit.py` already does it right.
|
||||
For good inbox placement add SPF: `TXT @ = v=spf1 ip4:VPS_IP ~all` (auto.py does this).
|
||||
|
||||
## otp_api.py — HTTP API over the caught mail
|
||||
Stdlib HTTP on `:2525`, reads the same `mail/` store. Endpoints:
|
||||
- `GET /next?domain=yourdomain` → `{"address": "userN@yourdomain"}` — next unseen mailbox
|
||||
- `GET /acquire?address=x@yourdomain&ttl=600` — reserve an exact address
|
||||
- `GET /latest?address=x@yourdomain&wait=60` → newest message for it; long-polls up to
|
||||
`wait` seconds; auto-extracts `code` (matches "verification code is : NNNNNN" etc.)
|
||||
- `GET /list?domain=yourdomain` — known mailboxes with last-seen
|
||||
- `GET /health` → `{"ok": true, "mails": N}`
|
||||
|
||||
Full loop proven E2E: `/next` → register on a site with that address → site mails the OTP
|
||||
→ public MX → catcher → `/latest?wait=90` returns the code (`CODE VALID: True`).
|
||||
Deploy: systemd `otpapi.service`, `ExecStart=/usr/bin/python3 /root/mailcatch/otp_api.py`
|
||||
(WorkingDirectory=/root/mailcatch so it finds `mail/`).
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""otp_api.py — HTTP API over the catcher mailbox store (port 2525, stdlib only).
|
||||
|
||||
Endpoints:
|
||||
GET /next?domain=reformwk59.eu.cc -> {"address": "user42@domain"} (least-recently-used free mailbox)
|
||||
GET /acquire?address=user42@domain&ttl=600 -> lock mailbox to caller (X-Client-Id header optional)
|
||||
GET /latest?address=user42@domain&wait=60 -> {"found": true, "subject":..., "body":..., "code": "123456", "ts":...}
|
||||
long-polls up to `wait` seconds for new mail
|
||||
GET /list?domain=reformwk59.eu.cc -> recent addresses with mail
|
||||
GET /health -> ok
|
||||
|
||||
State: mailboxes.json (address -> {last_used, locked_until, client}) next to script.
|
||||
Mail source: ../mail/*.eml written by catcher.py (filename contains recipient).
|
||||
|
||||
Run on the VPS: python3 otp_api.py (systemd: otpapi.service)
|
||||
"""
|
||||
import email as eml
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
MAILDIR = os.path.join(HERE, "mail")
|
||||
STATE_F = os.path.join(HERE, "mailboxes.json")
|
||||
PORT = int(os.environ.get("OTP_API_PORT") or 2525)
|
||||
POOL = int(os.environ.get("OTP_POOL") or 500) # user1..userN per domain
|
||||
|
||||
CODE_RE = re.compile(r"(?:verification code is|code is|code|код)[:\s]*([0-9]{4,8})", re.I)
|
||||
|
||||
|
||||
def load_state():
|
||||
try:
|
||||
return json.load(open(STATE_F, encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def save_state(st):
|
||||
tmp = STATE_F + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(st, f)
|
||||
os.replace(tmp, STATE_F)
|
||||
|
||||
|
||||
def mails_for(address):
|
||||
"""Scan MAILDIR for .eml whose filename/body contains address; newest first."""
|
||||
out = []
|
||||
if not os.path.isdir(MAILDIR):
|
||||
return out
|
||||
low = address.lower()
|
||||
for fn in os.listdir(MAILDIR):
|
||||
if not fn.endswith(".eml"):
|
||||
continue
|
||||
p = os.path.join(MAILDIR, fn)
|
||||
try:
|
||||
if low not in fn.lower():
|
||||
head = open(p, "rb").read(2048).decode(errors="replace").lower()
|
||||
if low not in head:
|
||||
continue
|
||||
raw = open(p, "rb").read()
|
||||
msg = eml.message_from_bytes(raw)
|
||||
body = ""
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
if part.get_content_type() == "text/plain":
|
||||
body = part.get_payload(decode=True).decode(errors="replace")
|
||||
break
|
||||
if not body:
|
||||
body = str(msg.get_payload())
|
||||
else:
|
||||
payload = msg.get_payload(decode=True)
|
||||
body = payload.decode(errors="replace") if isinstance(payload, bytes) else str(payload or "")
|
||||
out.append({
|
||||
"file": fn, "mtime": os.path.getmtime(p),
|
||||
"subject": str(msg.get("Subject") or ""),
|
||||
"from": str(msg.get("From") or ""),
|
||||
"body": body[:4000],
|
||||
})
|
||||
except Exception:
|
||||
continue
|
||||
out.sort(key=lambda x: -x["mtime"])
|
||||
return out
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
def _json(self, obj, code=200):
|
||||
b = json.dumps(obj, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(b)))
|
||||
self.end_headers()
|
||||
self.wfile.write(b)
|
||||
|
||||
def do_GET(self):
|
||||
u = urlparse(self.path)
|
||||
q = {k: v[0] for k, v in parse_qs(u.query).items()}
|
||||
st = load_state()
|
||||
now = time.time()
|
||||
if u.path == "/health":
|
||||
return self._json({"ok": True, "mails": len(os.listdir(MAILDIR)) if os.path.isdir(MAILDIR) else 0})
|
||||
if u.path == "/next":
|
||||
dom = q.get("domain", "").lower()
|
||||
if not dom:
|
||||
return self._json({"error": "domain required"}, 400)
|
||||
taken = {a for a, v in st.items() if a.endswith("@" + dom) and (v.get("locked_until", 0) > now or v.get("last_used", 0) > now - 3600)}
|
||||
picked = None
|
||||
for i in range(1, POOL + 1):
|
||||
cand = "user%d@%s" % (i, dom)
|
||||
if cand in taken:
|
||||
continue
|
||||
picked = cand
|
||||
break
|
||||
if not picked:
|
||||
return self._json({"error": "pool exhausted"}, 503)
|
||||
st[picked] = {"last_used": now, "locked_until": now + int(q.get("ttl", 600)), "client": self.headers.get("X-Client-Id", "")}
|
||||
save_state(st)
|
||||
return self._json({"address": picked})
|
||||
if u.path == "/acquire":
|
||||
addr = q.get("address", "").lower()
|
||||
st[addr] = {"last_used": now, "locked_until": now + int(q.get("ttl", 600)), "client": self.headers.get("X-Client-Id", "")}
|
||||
save_state(st)
|
||||
return self._json({"acquired": addr})
|
||||
if u.path == "/latest":
|
||||
addr = q.get("address", "").lower()
|
||||
wait = min(int(q.get("wait", 60)), 300)
|
||||
since = float(q.get("since", 0))
|
||||
t0 = time.time()
|
||||
while True:
|
||||
ms = [m for m in mails_for(addr) if m["mtime"] > since]
|
||||
if ms:
|
||||
m = ms[0]
|
||||
code = ""
|
||||
mm = CODE_RE.search(m["body"]) or CODE_RE.search(m["subject"])
|
||||
if mm:
|
||||
code = mm.group(1)
|
||||
return self._json({"found": True, "subject": m["subject"], "from": m["from"],
|
||||
"body": m["body"][:2000], "code": code, "ts": m["mtime"]})
|
||||
if time.time() - t0 > wait:
|
||||
return self._json({"found": False})
|
||||
time.sleep(2)
|
||||
if u.path == "/list":
|
||||
dom = q.get("domain", "").lower()
|
||||
seen = {}
|
||||
for fn in os.listdir(MAILDIR) if os.path.isdir(MAILDIR) else []:
|
||||
mm = re.search(r"catch ([^@\]]+@[^@\]]+)\]", fn)
|
||||
if mm and (not dom or mm.group(1).endswith(dom)):
|
||||
seen[mm.group(1)] = max(seen.get(mm.group(1), 0), os.path.getmtime(os.path.join(MAILDIR, fn)))
|
||||
return self._json({"addresses": sorted(seen, key=lambda a: -seen[a])[:50]})
|
||||
return self._json({"error": "unknown path"}, 404)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", PORT), H)
|
||||
print("otp_api listening :%d maildir=%s" % (PORT, MAILDIR), flush=True)
|
||||
srv.serve_forever()
|
||||
@@ -0,0 +1,186 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""submit.py — authenticated SMTP submission (port 587) with real outbound delivery.
|
||||
|
||||
Clients auth with LOGIN (user = anything@yourdomain, pass = env sp), then mail is
|
||||
delivered DIRECTLY to recipient MX from the VPS (From: you@yourdomain preserved).
|
||||
|
||||
Zero deps beyond aiosmtpd (same as catcher.py). Pure-python MX resolver included.
|
||||
|
||||
Run: python3 submit.py (port 587, env file next to script: env.json {sp})
|
||||
Test: swaks --server VPS --port 587 --auth LOGIN --auth-user me@reformwk59.eu.cc \
|
||||
--auth-password $SP --to someone@gmail.com --from me@reformwk59.eu.cc
|
||||
Or python: smtplib.SMTP(host,587) -> starttls() -> login('me@domain', SP) -> sendmail(...)
|
||||
|
||||
NOTE: add SPF to the domain for deliverability:
|
||||
setup_dns.py <domain> --txt "@=v=spf1 ip4:<VPS_IP> ~all"
|
||||
"""
|
||||
import asyncio, json, os, re, smtplib, socket, ssl, struct, random, sys, time
|
||||
from aiosmtpd.controller import Controller
|
||||
from aiosmtpd.smtp import SMTP as SMTPsrv, LoginPassword, AuthResult
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ENV = json.load(open(os.path.join(HERE, "env.json"))) if os.path.exists(os.path.join(HERE, "env.json")) else {}
|
||||
SP = ENV.get("sp") or os.environ.get("SUBMIT_PASS") or ""
|
||||
PORT = int(ENV.get("submit_port") or os.environ.get("SUBMIT_PORT") or 587)
|
||||
LOG = os.path.join(HERE, "submit.log")
|
||||
|
||||
|
||||
def log(*a):
|
||||
line = " ".join(str(x) for x in a)
|
||||
print(time.strftime("[%H:%M:%S]"), line, flush=True)
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
|
||||
|
||||
# ---------- minimal DNS MX resolver (no deps) ----------
|
||||
def _qname(name):
|
||||
return b"".join(bytes([len(p)]) + p.encode() for p in name.split(".") if p) + b"\x00"
|
||||
|
||||
|
||||
def _parse_name(msg, off):
|
||||
labels, jumped, orig = [], False, off
|
||||
while True:
|
||||
ln = msg[off]
|
||||
if ln == 0:
|
||||
off += 1
|
||||
break
|
||||
if ln & 0xC0 == 0xC0:
|
||||
ptr = struct.unpack("!H", msg[off:off + 2])[0] & 0x3FFF
|
||||
if not jumped:
|
||||
orig = off + 2
|
||||
off, jumped = ptr, True
|
||||
continue
|
||||
labels.append(msg[off + 1:off + 1 + ln].decode(errors="replace"))
|
||||
off += ln + 1
|
||||
return ".".join(labels), (orig if jumped else off)
|
||||
|
||||
|
||||
def resolve_mx(domain, timeout=6):
|
||||
"""Return list of (prio, host) for domain; falls back to A of domain itself."""
|
||||
tid = random.randint(0, 65535)
|
||||
q = struct.pack("!HHHHHH", tid, 0x0100, 1, 0, 0, 0) + _qname(domain) + struct.pack("!HH", 15, 1)
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.settimeout(timeout)
|
||||
for dns in ("1.1.1.1", "8.8.8.8"):
|
||||
try:
|
||||
s.sendto(q, (dns, 53))
|
||||
msg, _ = s.recvfrom(4096)
|
||||
ancount = struct.unpack("!H", msg[6:8])[0]
|
||||
if ancount == 0:
|
||||
continue
|
||||
# skip question
|
||||
_, off = _parse_name(msg, 12)
|
||||
off += 4
|
||||
out = []
|
||||
for _ in range(ancount):
|
||||
_, off = _parse_name(msg, off)
|
||||
rtype, rdlen = struct.unpack("!HH", msg[off + 8:off + 12])
|
||||
rd_start = off + 10
|
||||
if rtype == 15:
|
||||
prio = struct.unpack("!H", msg[rd_start:rd_start + 2])[0]
|
||||
exch, _ = _parse_name(msg, rd_start + 2)
|
||||
out.append((prio, exch.rstrip(".")))
|
||||
off = rd_start + rdlen
|
||||
s.close()
|
||||
if out:
|
||||
return sorted(out)
|
||||
except Exception:
|
||||
continue
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
socket.gethostbyname(domain)
|
||||
return [(10, domain.rstrip("."))]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def deliver(mail_from, rcpt, data):
|
||||
dom = rcpt.split("@")[-1].lower()
|
||||
mxs = resolve_mx(dom)
|
||||
errs = []
|
||||
for prio, host in mxs[:4]:
|
||||
try:
|
||||
ip = socket.gethostbyname(host)
|
||||
s = smtplib.SMTP(ip, 25, timeout=30)
|
||||
s.ehlo(socket.gethostname() or "submit")
|
||||
try:
|
||||
s.starttls(context=ssl.create_default_context())
|
||||
s.ehlo()
|
||||
except Exception:
|
||||
pass
|
||||
s.sendmail(mail_from, [rcpt], data)
|
||||
s.quit()
|
||||
log("DELIVERED", rcpt, "via", host, ip)
|
||||
return True
|
||||
except Exception as e:
|
||||
errs.append("%s:%s:%s" % (host, type(e).__name__, str(e)[:60]))
|
||||
log("DIRECT FAIL", rcpt, "|".join(errs), "-> trying gmail relay")
|
||||
return relay_gmail(rcpt, data)
|
||||
|
||||
|
||||
def relay_gmail(rcpt, data):
|
||||
gm, gp = ENV.get("gm"), ENV.get("gp")
|
||||
if not gm or not gp:
|
||||
log("RELAY FAIL no gm/gp in env.json")
|
||||
return False
|
||||
try:
|
||||
s = smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=45)
|
||||
s.login(gm, gp)
|
||||
s.sendmail(gm, [rcpt], data)
|
||||
s.quit()
|
||||
log("RELAYED via gmail ->", rcpt)
|
||||
return True
|
||||
except Exception as e:
|
||||
log("RELAY FAIL", rcpt, type(e).__name__, str(e)[:120])
|
||||
return False
|
||||
|
||||
|
||||
def authenticator(server, session, envelope, mechanism, auth_data):
|
||||
if not SP:
|
||||
return AuthResult(success=False, handled=False)
|
||||
if not isinstance(auth_data, LoginPassword):
|
||||
return AuthResult(success=False, handled=False)
|
||||
if auth_data.password.decode(errors="replace") == SP:
|
||||
return AuthResult(success=True, handled=True, auth_data=auth_data)
|
||||
return AuthResult(success=False, handled=False)
|
||||
|
||||
|
||||
class SubmitHandler:
|
||||
async def handle_DATA(self, server, session, envelope):
|
||||
ok = deliver(envelope.mail_from, envelope.rcpt_tos[0], envelope.content)
|
||||
return "250 OK" if ok else "451 delivery failed"
|
||||
|
||||
|
||||
def _tls_context():
|
||||
cert = os.path.join(HERE, "cert.pem")
|
||||
key = os.path.join(HERE, "key.pem")
|
||||
if os.path.exists(cert) and os.path.exists(key):
|
||||
c = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
c.load_cert_chain(cert, key)
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
if not SP:
|
||||
print("FATAL: set sp in env.json or SUBMIT_PASS env", file=sys.stderr)
|
||||
return 1
|
||||
c = Controller(SubmitHandler(), hostname="0.0.0.0", port=PORT,
|
||||
authenticator=authenticator,
|
||||
auth_required=True, auth_require_tls=False,
|
||||
tls_context=_tls_context())
|
||||
c.start()
|
||||
log("submit listening :%d (auth LOGIN, pass from env)" % PORT)
|
||||
try:
|
||||
while True:
|
||||
time.sleep(3600)
|
||||
except KeyboardInterrupt:
|
||||
c.stop()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user