#!/usr/bin/env python3 """Download the daily China Merchants Bank statement delivered by email.""" from __future__ import annotations import argparse import email import email.policy import hashlib import html import imaplib import json import os import re import ssl import sys import urllib.parse import urllib.request import zipfile from dataclasses import dataclass from datetime import date, datetime, timedelta from email.utils import parsedate_to_datetime from html.parser import HTMLParser from pathlib import Path, PurePosixPath from typing import Any from zoneinfo import ZoneInfo SHANGHAI = ZoneInfo("Asia/Shanghai") MONTHS = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ) DEFAULT_SENDER = "95555@message.cmbchina.com" DEFAULT_SUBJECT = "招商银行企业交易明细" DOWNLOAD_TEXT = "点击此处下载文件" DATE_RANGE = re.compile(r"(?P\d{8})-(?P\d{8})") SUPPORTED_FILES = {".xlsx", ".xls", ".csv"} MAX_DOWNLOAD_BYTES = 300 * 1024 * 1024 MAX_EXTRACTED_BYTES = 600 * 1024 * 1024 MAX_ARCHIVE_MEMBERS = 1000 class CmbMailError(RuntimeError): """The CMB email or statement package cannot be safely processed.""" @dataclass(frozen=True) class DownloadLink: url: str archive_name: str date_start: str date_end: str class _AnchorParser(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.links: list[tuple[str, str]] = [] self._href = "" self._text: list[str] = [] def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: if tag.lower() != "a": return attributes = {key.lower(): value or "" for key, value in attrs} self._href = attributes.get("href", "").strip() self._text = [] def handle_data(self, data: str) -> None: if self._href: self._text.append(data) def handle_endtag(self, tag: str) -> None: if tag.lower() == "a" and self._href: self.links.append((self._href, "".join(self._text).strip())) self._href = "" self._text = [] def text(value: Any) -> str: return "" if value is None else str(value).strip() def compact(value: Any) -> str: return re.sub(r"\s+", "", text(value)) def parse_date(value: str) -> date: try: parsed = date.fromisoformat(value) except ValueError as exception: raise CmbMailError("日期必须使用 YYYY-MM-DD 格式。") from exception if parsed.isoformat() != value: raise CmbMailError("日期必须使用 YYYY-MM-DD 格式。") return parsed def imap_date(value: date) -> str: return f"{value.day:02d}-{MONTHS[value.month - 1]}-{value.year}" def write_json(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text( json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) os.replace(temporary, path) def connect_mail(mail: dict[str, Any]) -> imaplib.IMAP4_SSL: imaplib.Commands["ID"] = ("AUTH",) connection = imaplib.IMAP4_SSL( str(mail["host"]), int(mail.get("port", 993)), ssl_context=ssl.create_default_context(), ) connection.login(str(mail["username"]), str(mail["auth_code"])) connection._simple_command( "ID", '("name" "CaiWuXiTong" "version" "1.0" "vendor" "CaiWuXiTong")', ) status, data = connection.select("INBOX", readonly=True) if status != "OK": connection.logout() raise CmbMailError(f"无法打开邮箱收件箱:{data!r}") return connection def message_date(message: email.message.Message) -> datetime: try: parsed = parsedate_to_datetime(str(message.get("Date", ""))) if parsed.tzinfo is None: return parsed.replace(tzinfo=SHANGHAI) return parsed.astimezone(SHANGHAI) except (TypeError, ValueError): return datetime.min.replace(tzinfo=SHANGHAI) def message_text_parts(message: email.message.Message) -> list[str]: parts: list[str] = [] for part in message.walk(): disposition = text(part.get("Content-Disposition")).lower() if "attachment" in disposition: continue content_type = text(part.get_content_type()).lower() if content_type not in {"text/html", "text/plain"}: continue payload = part.get_payload(decode=True) if payload is None: continue charset = part.get_content_charset() or "utf-8" try: parts.append(payload.decode(charset, errors="replace")) except LookupError: parts.append(payload.decode("utf-8", errors="replace")) return parts def download_link_from_body(body: str) -> DownloadLink | None: parser = _AnchorParser() parser.feed(body) for href, label in parser.links: if compact(label) != DOWNLOAD_TEXT: continue url = html.unescape(href.strip()) if url.startswith("//"): url = "https:" + url elif not url.lower().startswith(("http://", "https://")): url = "https://" + url.lstrip("/") parsed = urllib.parse.urlsplit(url) if parsed.hostname not in {"s3gw.cmbimg.com"}: continue decoded = url for _ in range(3): next_decoded = urllib.parse.unquote(decoded) if next_decoded == decoded: break decoded = next_decoded dates = DATE_RANGE.search(decoded) filename_match = re.search( r'filename\*?=(?:UTF-8\'\')?"?([^";&]+)', decoded, flags=re.IGNORECASE, ) archive_name = ( urllib.parse.unquote(filename_match.group(1)).strip() if filename_match else "招商银行企业交易明细.zip" ) return DownloadLink( url=url, archive_name=archive_name, date_start=dates.group("start") if dates else "", date_end=dates.group("end") if dates else "", ) return None def load_candidates( mail: dict[str, Any], target_date: date, ) -> list[dict[str, Any]]: connection = connect_mail(mail) candidates: list[dict[str, Any]] = [] since = target_date - timedelta(days=max(1, int(mail.get("search_grace_days", 2)))) sender_match = compact(mail.get("sender", DEFAULT_SENDER)).lower() subject_match = compact(mail.get("subject", DEFAULT_SUBJECT)) try: status, data = connection.uid("search", None, "SINCE", imap_date(since)) if status != "OK": raise CmbMailError(f"邮箱搜索失败:{data!r}") uids = data[0].split() if data and data[0] else [] for uid in uids: status, parts = connection.uid( "fetch", uid, "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])", ) if status != "OK": continue raw_header = b"".join(part[1] for part in parts if isinstance(part, tuple)) header = email.message_from_bytes(raw_header, policy=email.policy.default) sender = compact(header.get("From")).lower() subject = text(header.get("Subject")) if sender_match not in sender or subject_match not in compact(subject): continue status, parts = connection.uid("fetch", uid, "(BODY.PEEK[])") if status != "OK": continue raw = b"".join(part[1] for part in parts if isinstance(part, tuple)) message = email.message_from_bytes(raw, policy=email.policy.default) link = None for body in message_text_parts(message): link = download_link_from_body(body) if link is not None: break sent_at = message_date(message) if link is None or sent_at.date() != target_date + timedelta(days=1): continue candidates.append( { "uid": uid.decode(), "sent_at": sent_at, "subject": subject, "link": link, } ) finally: try: connection.logout() except imaplib.IMAP4.error: pass return sorted(candidates, key=lambda item: item["sent_at"], reverse=True) def download_archive(link: DownloadLink, target: Path) -> dict[str, Any]: request = urllib.request.Request( link.url, headers={ "User-Agent": "CaiWuXiTong/1.0", "Accept": "application/zip,application/octet-stream,*/*", }, ) digest = hashlib.sha256() total = 0 target.parent.mkdir(parents=True, exist_ok=True) temporary = target.with_suffix(target.suffix + ".tmp") try: with urllib.request.urlopen(request, timeout=120) as response: content_type = text(response.headers.get("Content-Type")).lower() if "zip" not in content_type and "octet-stream" not in content_type: raise CmbMailError(f"招商银行下载链接返回了非 ZIP 内容:{content_type or '未知'}") with temporary.open("wb") as stream: while True: chunk = response.read(1024 * 1024) if not chunk: break total += len(chunk) if total > MAX_DOWNLOAD_BYTES: raise CmbMailError("招商银行账单 ZIP 超过 300 MB,已停止下载。") digest.update(chunk) stream.write(chunk) os.replace(temporary, target) except Exception: temporary.unlink(missing_ok=True) raise if total == 0: target.unlink(missing_ok=True) raise CmbMailError("招商银行账单 ZIP 下载为空。") return { "size": total, "sha256": digest.hexdigest(), "content_type": content_type, } def safe_extract(archive_path: Path, destination: Path) -> list[dict[str, Any]]: destination.mkdir(parents=True, exist_ok=True) files: list[dict[str, Any]] = [] try: with zipfile.ZipFile(archive_path) as archive: members = [item for item in archive.infolist() if not item.is_dir()] if len(members) > MAX_ARCHIVE_MEMBERS: raise CmbMailError("招商银行 ZIP 文件数量异常。") if sum(max(0, item.file_size) for item in members) > MAX_EXTRACTED_BYTES: raise CmbMailError("招商银行 ZIP 解压后超过 600 MB,已停止处理。") for item in members: member = PurePosixPath(item.filename) if member.is_absolute() or ".." in member.parts: raise CmbMailError("招商银行 ZIP 包含不安全文件路径。") if any(part.startswith("__MACOSX") for part in member.parts): continue suffix = member.suffix.lower() if suffix not in SUPPORTED_FILES: continue target = destination.joinpath(*member.parts) target.parent.mkdir(parents=True, exist_ok=True) with archive.open(item) as source, target.open("wb") as output: while True: chunk = source.read(1024 * 1024) if not chunk: break output.write(chunk) file_digest = hashlib.sha256(target.read_bytes()).hexdigest() files.append( { "path": str(target), "name": target.name, "size": target.stat().st_size, "sha256": file_digest, } ) except zipfile.BadZipFile as exception: raise CmbMailError("招商银行下载内容不是有效 ZIP。") from exception if not files: raise CmbMailError("招商银行 ZIP 中没有可导入的 XLSX、XLS 或 CSV 文件。") return files def classify_failure(message: str) -> str: normalized = message.lower() if any( marker in normalized for marker in ( "authenticationfailed", "authentication failed", "login failed", "authorization failed", "无法打开邮箱收件箱", ) ): return "auth" if "未找到" in message and "邮件" in message: return "not_found" if "下载" in message: return "download" if any(marker in normalized for marker in ("zip", "解压", "archive")) or "归档" in message: return "archive" if "配置" in message: return "config" return "unknown" def safe_failure_reason(kind: str, target_date: date) -> str: return { "auth": "163 邮箱授权失效或邮箱登录失败。", "config": "招商银行邮件任务配置不完整。", "not_found": f"{target_date.isoformat()} 的招商银行账单邮件未找到。", "download": "招商银行账单下载失败。", "archive": "招商银行账单 ZIP 解压或安全校验失败。", "unknown": "服务器任务执行异常,具体错误已写入日志。", }[kind] def write_failure_state( state_file: Path, target_date: date, error_type: str, reason: str, ) -> None: write_json( state_file, { "ok": False, "target_date": target_date.isoformat(), "error_type": error_type, "reason": reason, "generated_at": datetime.now(SHANGHAI).isoformat(timespec="seconds"), }, ) def fetch(args: argparse.Namespace) -> int: config_file = Path(args.config).expanduser().resolve() target_date = parse_date( args.date or (datetime.now(SHANGHAI).date() - timedelta(days=1)).isoformat() ) output_root = Path( args.out or config_file.parent / "exports" / target_date.isoformat() ).expanduser().resolve() run_directory = ( Path(args.run_dir).expanduser().resolve() if args.run_dir else output_root / datetime.now(SHANGHAI).strftime("%Y%m%d-%H%M%S") ) run_directory.mkdir(parents=True, exist_ok=True) state_file = run_directory / "last-fetch.json" try: if not config_file.is_file(): raise CmbMailError("缺少招商银行邮件配置。") config = json.loads(config_file.read_text(encoding="utf-8")) mail = config.get("mail") if not isinstance(mail, dict): raise CmbMailError("招商银行邮件配置缺少 mail。") mail = dict(mail) mail["sender"] = text(config.get("sender", DEFAULT_SENDER)) mail["subject"] = text(config.get("subject", DEFAULT_SUBJECT)) candidates = load_candidates(mail, target_date) print(f"邮箱匹配到 {len(candidates)} 封招商银行账单邮件") if not candidates: raise CmbMailError(f"{target_date.isoformat()} 的招商银行账单邮件未找到。") selected = candidates[0] link: DownloadLink = selected["link"] archive_path = run_directory / "cmb-statement.zip" archive_info = download_archive(link, archive_path) extract_directory = run_directory / "contents" files = safe_extract(archive_path, extract_directory) state = { "ok": True, "target_date": target_date.isoformat(), "mail_uid": selected["uid"], "mail_sent_at": selected["sent_at"].isoformat(timespec="seconds"), "subject": selected["subject"], "archive_name": link.archive_name, "date_start": link.date_start, "date_end": link.date_end, "download_url_sha256": hashlib.sha256(link.url.encode("utf-8")).hexdigest(), "archive": str(archive_path), "archive_size": archive_info["size"], "archive_sha256": archive_info["sha256"], "files": files, "generated_at": datetime.now(SHANGHAI).isoformat(timespec="seconds"), } write_json(state_file, state) print(f"已下载并解压 {len(files)} 个招商银行账单文件") print(f"状态文件:{state_file}") return 0 except CmbMailError as exception: error_type = classify_failure(str(exception)) write_failure_state(state_file, target_date, error_type, str(exception)) raise except imaplib.IMAP4.error as exception: error_type = classify_failure(str(exception)) write_failure_state( state_file, target_date, error_type, safe_failure_reason(error_type, target_date), ) raise CmbMailError(safe_failure_reason(error_type, target_date)) from exception except Exception as exception: write_failure_state( state_file, target_date, "unknown", safe_failure_reason("unknown", target_date), ) raise CmbMailError( f"服务器任务执行异常:{type(exception).__name__}" ) from exception def parser() -> argparse.ArgumentParser: root = argparse.ArgumentParser(description="招商银行邮件账单自动获取") commands = root.add_subparsers(dest="command", required=True) fetch_command = commands.add_parser("fetch", help="从邮箱获取并解压招商银行账单") fetch_command.add_argument("--config", required=True) fetch_command.add_argument("--date", default="") fetch_command.add_argument("--out", default="") fetch_command.add_argument("--run-dir", default="") fetch_command.set_defaults(handler=fetch) return root def main() -> int: args = parser().parse_args() try: return int(args.handler(args)) except CmbMailError as exception: print(f"招商银行邮件任务失败:{exception}", file=sys.stderr) return 2 except Exception as exception: print(f"招商银行邮件任务异常:{type(exception).__name__}: {exception}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())