Files
codex_auto/email_service.py
2026-03-23 21:42:02 +08:00

458 lines
16 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""临时邮箱 — 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]
模式由环境变量 **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 datetime import datetime
from typing import Any, Optional
import requests
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'
_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]] = {}
_EMAIL_DEBUG = os.getenv("EMAIL_DEBUG", "").strip().lower() in {"1", "true", "yes", "on"}
_HTTP = requests.Session()
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 _safe_print(msg: str) -> None:
try:
print(msg, flush=True)
except OSError:
pass
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 {
"User-Agent": _UA,
"X-API-Key": MAIL_API_KEY,
}
def _request(
method: str,
url: str,
*,
timeout: int = 15,
retries: int = 2,
**kwargs: Any,
) -> requests.Response:
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,
)
if r.status_code != 200:
_dlog(f"GET /generate-email failed: status={r.status_code} body={_clip(r.text)}")
return None
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
email = ((data.get("data") or {}).get("email") or "").strip()
if not email:
_dlog("generate-email missing email field")
return None
_MAIL_STATE[email] = {
"provider": "mail_api",
"created_at": time.time(),
}
_dlog(f"email created ok: {email}")
return email
def _web_create_email() -> Optional[str]:
try:
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:
_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:
return []
if state.get("provider") != "mail_api":
return []
try:
headers = _api_headers()
r = _request(
"GET",
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 []
data = r.json() if r.content else {}
if not data.get("success"):
_dlog(f"GET /emails success=false body={_clip(r.text)}")
return []
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[str, Any]] = []
for msg in members:
if not isinstance(msg, dict):
continue
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:
_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
m = re.search(r'<div[^>]*class="code"[^>]*>(\d{6})</div>', content, re.I)
if m:
return m.group(1)
m = re.search(r"[Vv]erification\s+code:?\s*(\d{6})", content)
if m:
return m.group(1)
m = re.search(r"code:?\s*(\d{6})", content, re.I)
if m:
return m.group(1)
clean = re.sub(r"<[^>]+>", " ", content)
m = re.search(r"\b(\d{6})\b", clean)
if m and m.group(1) != "177010":
return m.group(1)
return None
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[Any] = set()
while time.time() - start < timeout:
for mail in fetch_emails(email_address):
mid = mail.get("id") or mail.get("date")
if mid in seen:
continue
seen.add(mid)
sender = str(mail.get("from", "") or mail.get("sender", "")).lower()
subject = str(mail.get("subject", "")).lower()
if any(
k in sender or k in subject
for k in ("openai", "chatgpt", "verification", "noreply")
):
code = extract_code(mail)
if code:
return code
time.sleep(5)
return None