完善脚本

This commit is contained in:
xiaobai committed 2026-03-23 21:42:02 +08:00
1 parent 9d9509a26b
commit 0c740f5a53
9 files changed
+1176 -212

No files matched your search

+345 -169
View File
@@ -1,256 +1,425 @@
"""临时邮箱 — [GPTMail](https://mail.chatgpt.org.uk) 网页模拟
"""临时邮箱 — mail.chatgpt.org.uk
对外接口:
对外接口(与 register / oauth_login 一致):
- create_temp_email() -> Optional[str]
- fetch_emails(email_address) -> list[dict]
- wait_for_code(email_address, timeout=120) -> Optional[str]
通过网页同款鉴权(/api/inbox-token + X-Inbox-Token)访问收件接口,
避免 API key 配额限制。
模式由环境变量 **EMAIL_PROVIDER** 控制:
- **api**(默认):`GET /api/generate-email`,需 `MAIL_API_KEY` 或 `EMAIL_API_KEY`
- **web**:Playwright 打开网页自动取号;取码时轮询收件页
服务器首次使用 web 模式需安装浏览器内核:`playwright install chromium`
"""
from __future__ import annotations
import os
import random
import re
import string
import time
from typing import Optional
from datetime import datetime
from typing import Any, Optional
import requests
GPTMAIL_BASE = "https://mail.chatgpt.org.uk"
MAIL_API_BASE = "https://mail.chatgpt.org.uk/api"
MAIL_API_KEY = os.getenv("MAIL_API_KEY") or os.getenv("EMAIL_API_KEY") or "gpt-test"
EMAIL_PROVIDER = os.getenv("EMAIL_PROVIDER", "web").lower() # 'api' or 'web'
# 当前进程内:本脚本创建的邮箱 -> 会话信息
_MAIL_STATE: dict[str, dict] = {}
_UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136 Safari/537.36"
UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136 Safari/537.36"
_MAIL_STATE: dict[str, dict[str, Any]] = {}
def _gptmail_headers() -> dict:
return {
"User-Agent": UA,
"Accept": "application/json",
}
_EMAIL_DEBUG = os.getenv("EMAIL_DEBUG", "").strip().lower() in {"1", "true", "yes", "on"}
_HTTP = requests.Session()
def _normalize_gptmail_message(raw: dict) -> dict:
"""统一成 extract_code / wait_for_code 可用的字段"""
sender = (raw.get("from_address") or raw.get("from") or "").strip()
mid = raw.get("id")
text = raw.get("content") or raw.get("text") or ""
html = raw.get("html_content") or raw.get("html") or ""
return {
"id": mid,
"from": sender,
"sender": sender,
"subject": raw.get("subject", "") or "",
"text_content": text,
"html_content": html,
"content": text,
"body": text,
"date": raw.get("created_at") or raw.get("timestamp"),
}
def _proxies() -> dict[str, str]:
h = (os.getenv("HTTP_PROXY") or os.getenv("http_proxy") or "").strip()
hs = (os.getenv("HTTPS_PROXY") or os.getenv("https_proxy") or "").strip()
if not h and not hs:
return {}
return {"http": h or hs, "https": hs or h}
def _new_session() -> requests.Session:
s = requests.Session()
s.headers.update(_gptmail_headers())
return s
def _bootstrap_session(session: requests.Session) -> bool:
"""先访问首页拿 gm_sid,后续 inbox-token 才会通过"""
def _safe_print(msg: str) -> None:
try:
r = session.get(
f"{GPTMAIL_BASE}/",
headers={
"Referer": f"{GPTMAIL_BASE}/",
"Origin": GPTMAIL_BASE,
**_gptmail_headers(),
},
timeout=20,
)
return r.status_code == 200
except Exception:
return False
print(msg, flush=True)
except OSError:
pass
def _refresh_inbox_token(session: requests.Session, email: str = "") -> Optional[dict]:
r = session.post(
f"{GPTMAIL_BASE}/api/inbox-token",
json={"email": (email or "").strip().lower()},
headers={
"Content-Type": "application/json",
"Referer": f"{GPTMAIL_BASE}/",
"Origin": GPTMAIL_BASE,
**_gptmail_headers(),
},
timeout=20,
)
if r.status_code != 200:
return None
try:
body = r.json()
except Exception:
return None
if not body.get("success"):
return None
auth = body.get("auth") or {}
if not isinstance(auth, dict):
return None
token = (auth.get("token") or "").strip()
if not token:
return None
def _dlog(msg: str) -> None:
if _EMAIL_DEBUG:
_safe_print(f"[email][mail_api] {msg}")
def _clip(s: str, n: int = 240) -> str:
s = (s or "").replace("\n", " ").replace("\r", " ")
return s if len(s) <= n else s[:n] + "..."
def _api_headers() -> dict[str, str]:
return {
"token": token,
"email": (auth.get("email") or "").strip().lower(),
"expires_at": int(auth.get("expires_at") or 0),
"User-Agent": _UA,
"X-API-Key": MAIL_API_KEY,
}
def _auth_fetch(
session: requests.Session,
def _request(
method: str,
path: str,
url: str,
*,
auth_email: str,
params: dict | None = None,
json_data: dict | None = None,
timeout: int = 15,
retries: int = 2,
**kwargs: Any,
) -> requests.Response:
auth = _refresh_inbox_token(session, auth_email)
headers = {}
if auth and auth.get("token"):
headers["X-Inbox-Token"] = auth["token"]
return session.request(
method,
f"{GPTMAIL_BASE}{path}",
params=params,
json=json_data,
headers=headers,
timeout=20,
last_exc: Optional[Exception] = None
now = datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
px = _proxies()
if px:
kwargs.setdefault("proxies", px)
for attempt in range(retries + 1):
try:
r = _HTTP.request(method, url, timeout=timeout, **kwargs)
except requests.RequestException as e:
last_exc = e
_dlog(
f"[{formatted_time}]{method} {url} network_error={e.__class__.__name__}: {e} "
f"(attempt {attempt + 1}/{retries + 1})"
)
if attempt >= retries:
raise
time.sleep(0.6 * (2**attempt) + random.random() * 0.2)
continue
if r.status_code in (429, 500, 502, 503, 504):
_dlog(
f"[{formatted_time}]{method} {url} status={r.status_code} body={_clip(r.text)} "
f"(attempt {attempt + 1}/{retries + 1})"
)
if attempt >= retries:
return r
sleep_s = 0.8 * (2**attempt) + random.random() * 0.2
if r.status_code == 429:
ra = (r.headers.get("Retry-After") or "").strip()
if ra.isdigit():
sleep_s = max(sleep_s, float(ra))
time.sleep(min(sleep_s, 8.0))
continue
return r
if last_exc:
raise last_exc
raise RuntimeError("request failed")
def _mailapi_create_email() -> Optional[str]:
r = _request(
"GET",
f"{MAIL_API_BASE}/generate-email",
headers=_api_headers(),
timeout=15,
retries=2,
)
def _gptmail_fetch_detail(session: requests.Session, email_address: str, email_id: str) -> Optional[dict]:
r = _auth_fetch(session, "GET", f"/api/email/{email_id}", auth_email=email_address)
if r.status_code != 200:
return None
try:
body = r.json()
except Exception:
return None
if not body.get("success"):
return None
data = body.get("data") or {}
return data if isinstance(data, dict) else None
def _gptmail_create_email() -> Optional[str]:
session = _new_session()
if not _bootstrap_session(session):
print("[email] GPTMail 会话初始化失败")
return None
r = _auth_fetch(session, "GET", "/api/generate-email", auth_email="")
try:
body = r.json()
except Exception:
print(f"[email] GPTMail 响应非 JSON: HTTP {r.status_code}")
_dlog(f"GET /generate-email failed: status={r.status_code} body={_clip(r.text)}")
return None
if not body.get("success"):
err = body.get("error") or body.get("message") or r.text[:200]
print(f"[email] GPTMail 创建失败: {err}")
data = r.json() if r.content else {}
if not data.get("success"):
_dlog(f"GET /generate-email success=false body={_clip(r.text)}")
return None
data = body.get("data") or {}
email = (data.get("email") or "").strip()
if not email or "@" not in email:
print("[email] GPTMail 返回缺少 email")
email = ((data.get("data") or {}).get("email") or "").strip()
if not email:
_dlog("generate-email missing email field")
return None
_MAIL_STATE[email] = {
"provider": "gptmail",
"session": session,
"provider": "mail_api",
"created_at": time.time(),
}
_dlog(f"email created ok: {email}")
return email
def create_temp_email() -> Optional[str]:
"""创建临时邮箱,返回邮箱地址"""
def _web_create_email() -> Optional[str]:
try:
return _gptmail_create_email()
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
except ImportError:
_safe_print(
"[email] EMAIL_PROVIDER=web 需要安装 playwright:pip install playwright && playwright install chromium"
)
return None
try:
with sync_playwright() as p:
browser = p.chromium.launch(
headless=True,
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
],
)
try:
context = browser.new_context(
viewport={"width": 1920, "height": 1080},
user_agent=_UA,
)
page = context.new_page()
_dlog("[playwright] Navigating to mail site...")
page.goto(
"https://mail.chatgpt.org.uk/",
timeout=60000,
wait_until="domcontentloaded",
)
try:
page.wait_for_selector("//button[contains(., '我知道了')]", timeout=8000)
page.click("//button[contains(., '我知道了')]")
_dlog("[playwright] Closed popup.")
except PlaywrightTimeoutError:
pass
_dlog("[playwright] Waiting for auto-generated email...")
try:
email_el = page.wait_for_selector("#emailDisplay", timeout=30000)
for _ in range(40):
raw = email_el.text_content() or ""
email_text = raw.strip()
if "@" in email_text and "loading" not in email_text.lower():
_MAIL_STATE[email_text] = {
"provider": "playwright_web",
"created_at": time.time(),
}
_dlog(f"[playwright] email created ok: {email_text}")
return email_text
time.sleep(0.5)
_dlog("[playwright] Timeout waiting for valid email text.")
try:
page.screenshot(path="debug_create_email_timeout.png")
except OSError:
pass
return None
except Exception as e:
_dlog(f"[playwright] Error finding email element: {e}")
try:
page.screenshot(path="debug_create_email_error.png")
except OSError:
pass
return None
finally:
browser.close()
except Exception as e:
print(f"[email] 创建失败: {e}")
_safe_print(f"[email][playwright] _web_create_email failed: {e}")
return None
def _web_wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]:
try:
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
except ImportError:
return None
try:
with sync_playwright() as p:
browser = p.chromium.launch(
headless=True,
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
],
)
try:
context = browser.new_context(
viewport={"width": 1920, "height": 1080},
user_agent=_UA,
)
page = context.new_page()
inbox_url = f"https://mail.chatgpt.org.uk/{email_address}"
_dlog(f"[playwright] Starting poll on {inbox_url}")
page.goto(inbox_url, timeout=30000)
try:
page.wait_for_selector("//button[contains(., '我知道了')]", timeout=5000)
page.click("//button[contains(., '我知道了')]")
except PlaywrightTimeoutError:
pass
start_time = time.time()
while time.time() - start_time < timeout:
_dlog("[playwright] Scanning page text for code...")
try:
body_text = page.locator("body").text_content() or ""
patterns = [
r"Your ChatGPT code is\s*(\d{6})",
r"verification code:?\s*(\d{6})",
r"code is\s*(\d{6})",
]
found_code: Optional[str] = None
for pat in patterns:
match = re.search(pat, body_text, re.IGNORECASE)
if match:
found_code = match.group(1)
break
if found_code:
_dlog(f"[playwright] Success! Found code: {found_code}")
return found_code
match = re.search(r"(\d{6})", body_text)
if match:
code = match.group(1)
_dlog(f"[playwright] Success! Found code (generic): {code}")
return code
except Exception as e:
_dlog(f"[playwright] Error reading text: {e}")
try:
refresh_btn = page.locator("//button[contains(., '刷新')]")
if refresh_btn.is_visible():
refresh_btn.click()
else:
page.reload()
except Exception:
page.reload()
time.sleep(5)
_dlog("[playwright] Timeout polling for code.")
return None
finally:
browser.close()
except Exception as e:
_safe_print(f"[email][playwright] _web_wait_for_code failed: {e}")
return None
def create_temp_email() -> Optional[str]:
try:
if EMAIL_PROVIDER == "web":
_safe_print("[email] Using web provider (Playwright)")
return _web_create_email()
_safe_print("[email] Using api provider")
return _mailapi_create_email()
except Exception as e:
_safe_print(f"[email] create failed: {e}")
return None
def fetch_emails(email_address: str) -> list[dict]:
"""获取邮件列表(统一输出字典列表)"""
state = _MAIL_STATE.get(email_address)
if not state or state.get("provider") != "gptmail":
if not state:
return []
if state.get("provider") != "mail_api":
return []
session = state.get("session")
if not isinstance(session, requests.Session):
session = _new_session()
_bootstrap_session(session)
state["session"] = session
try:
r = _auth_fetch(
session,
headers = _api_headers()
r = _request(
"GET",
"/api/emails",
auth_email=email_address,
f"{MAIL_API_BASE}/emails",
params={"email": email_address},
headers=headers,
timeout=20,
retries=2,
)
if r.status_code != 200:
_dlog(f"GET /emails failed: status={r.status_code} body={_clip(r.text)}")
return []
body = r.json()
if not body.get("success"):
data = r.json() if r.content else {}
if not data.get("success"):
_dlog(f"GET /emails success=false body={_clip(r.text)}")
return []
data = body.get("data") or {}
members = data.get("emails") or []
payload = data.get("data")
if isinstance(payload, dict) and "emails" in payload:
members = payload.get("emails") or []
else:
members = payload or []
if not isinstance(members, list):
_dlog("GET /emails data is not a list")
return []
out: list[dict] = []
out: list[dict[str, Any]] = []
for msg in members:
if not isinstance(msg, dict):
continue
mid = msg.get("id")
detail = msg
if mid and not (msg.get("content") or msg.get("html_content")):
d = _gptmail_fetch_detail(session, email_address, mid)
if d:
detail = {**msg, **d}
out.append(_normalize_gptmail_message(detail))
mid = msg.get("id") or msg.get("email_id")
detail: dict[str, Any] = {}
if mid:
rd = _request(
"GET",
f"{MAIL_API_BASE}/email/{mid}",
headers=headers,
timeout=20,
retries=2,
)
if rd.status_code == 200:
d = rd.json() if rd.content else {}
detail = d.get("data") if isinstance(d, dict) else {}
sender = (
detail.get("from_address")
or msg.get("from_address")
or msg.get("from")
or msg.get("sender")
or ""
)
subject = detail.get("subject") or msg.get("subject") or ""
text_content = detail.get("content") or msg.get("content") or ""
html_content = detail.get("html_content") or msg.get("html_content") or ""
created_at = detail.get("created_at") or msg.get("created_at")
timestamp = detail.get("timestamp") or msg.get("timestamp")
out.append(
{
"id": mid,
"from": sender,
"sender": sender,
"subject": subject,
"text_content": text_content,
"html_content": html_content,
"content": text_content,
"body": text_content,
"date": created_at or timestamp,
}
)
return out
except Exception as e:
print(f"[email] 获取邮件错误: {e}")
_safe_print(f"[email] fetch failed: {e}")
return []
def extract_code(email_data: dict) -> Optional[str]:
"""从邮件中提取验证码"""
for field in ["subject", "html_content", "content", "text_content", "body"]:
content = email_data.get(field, "")
if not content:
continue
# HTML <div class="code">
m = re.search(r'<div[^>]*class="code"[^>]*>(\d{6})</div>', content, re.I)
if m:
return m.group(1)
# verification code: XXXXXX
m = re.search(r'[Vv]erification\s+code:?\s*(\d{6})', content)
m = re.search(r"[Vv]erification\s+code:?\s*(\d{6})", content)
if m:
return m.group(1)
# code: XXXXXX
m = re.search(r'code:?\s*(\d{6})', content, re.I)
m = re.search(r"code:?\s*(\d{6})", content, re.I)
if m:
return m.group(1)
# 独立6位数字
clean = re.sub(r"<[^>]+>", " ", content)
m = re.search(r"\b(\d{6})\b", clean)
if m and m.group(1) != "177010":
@@ -259,9 +428,16 @@ def extract_code(email_data: dict) -> Optional[str]:
def wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]:
"""轮询等待验证码"""
state = _MAIL_STATE.get(email_address, {})
provider = state.get("provider")
if provider == "playwright_web":
_safe_print("[email] Waiting for code via web provider (Playwright UI)")
return _web_wait_for_code(email_address, timeout=timeout)
_safe_print("[email] Waiting for code via api provider")
start = time.time()
seen = set()
seen: set[Any] = set()
while time.time() - start < timeout:
for mail in fetch_emails(email_address):
mid = mail.get("id") or mail.get("date")