From eb4e895e4e9e6f8d7cb0277ddee1264c666d6c21 Mon Sep 17 00:00:00 2001 From: zhangshy <994452054@qq.com> Date: Sat, 12 Sep 2026 15:56:50 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=AB=98=E9=A3=8E=E9=99=A9?= =?UTF-8?q?=E9=A2=84=E8=AD=A6=E9=82=AE=E4=BB=B6=E9=80=9A=E7=9F=A5=E5=B9=B6?= =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 13 +- app/api/controllers/risk.py | 2 +- app/core/config.py | 3 + app/service/risk_daily_report_mail_service.py | 43 +++--- app/service/risk_notification_service.py | 16 +++ app/service/risk_scan_service.py | 84 +++++++++++- app/service/risk_smtp_mail_service.py | 117 ++++++++++++++++ app/worker/risk_scan_scheduler.py | 2 +- tests/unit/api/test_risk_controller.py | 4 + .../unit/service/test_risk_scan_alert_mail.py | 125 ++++++++++++++++++ .../service/test_risk_scan_notification.py | 18 +++ .../service/test_risk_smtp_mail_service.py | 71 ++++++++++ 12 files changed, 464 insertions(+), 34 deletions(-) create mode 100644 app/service/risk_smtp_mail_service.py create mode 100644 tests/unit/service/test_risk_scan_alert_mail.py create mode 100644 tests/unit/service/test_risk_smtp_mail_service.py diff --git a/.env.example b/.env.example index ba55b2c..360e066 100644 --- a/.env.example +++ b/.env.example @@ -57,13 +57,16 @@ RISK_SCAN_POLL_SECONDS=30 RISK_EVIDENCE_DIR=storage/risk_evidence RISK_EVIDENCE_MAX_FILE_SIZE_MB=10 -RISK_DAILY_REPORT_MAIL_ENABLED=false +RISK_ALERT_MAIL_ENABLED=true +RISK_ALERT_MAIL_DRY_RUN=false +RISK_ALERT_MAIL_RECIPIENTS=你的邮箱账号 +RISK_DAILY_REPORT_MAIL_ENABLED=true RISK_DAILY_REPORT_MAIL_DRY_RUN=true -RISK_SMTP_HOST= +RISK_SMTP_HOST=smtp.163.com RISK_SMTP_PORT=465 -RISK_SMTP_USERNAME= -RISK_SMTP_PASSWORD= -RISK_SMTP_SENDER= +RISK_SMTP_USERNAME=你的邮箱账号 +RISK_SMTP_PASSWORD=你的SMTP授权码 +RISK_SMTP_SENDER=你的邮箱账号 RISK_SMTP_USE_SSL=true RISK_SMTP_TIMEOUT_SECONDS=30 diff --git a/app/api/controllers/risk.py b/app/api/controllers/risk.py index d9f380e..b9637f0 100644 --- a/app/api/controllers/risk.py +++ b/app/api/controllers/risk.py @@ -98,7 +98,7 @@ async def scan_risk_alerts( async with mysql_scan_lock() as acquired: if not acquired: raise RiskScanBusyError("规则扫描正在执行,请稍后重试") - return await RiskScanService(inner).scan(context) + return await RiskScanService.from_settings(inner).scan(context) data = await _idempotent_write( session, context, key, "POST /api/v1/risk/alerts/scan", {}, run diff --git a/app/core/config.py b/app/core/config.py index e0b3e06..f80514f 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -117,6 +117,9 @@ class Settings(BaseSettings): risk_scan_run_immediately: bool = False risk_scan_retry_limit: int = Field(default=2, ge=0, le=5) risk_scan_poll_seconds: float = Field(default=30, gt=0) + risk_alert_mail_enabled: bool = False + risk_alert_mail_dry_run: bool = True + risk_alert_mail_recipients: str = "" # 投顾灰度默认关闭,只有显式开启并配置客户白名单后才限制客户流量。 # 管理员角色始终可进入,便于审核、发布和故障处置。 advisor_rollout_enabled: bool = False diff --git a/app/service/risk_daily_report_mail_service.py b/app/service/risk_daily_report_mail_service.py index 3bff8a0..024316d 100644 --- a/app/service/risk_daily_report_mail_service.py +++ b/app/service/risk_daily_report_mail_service.py @@ -3,18 +3,27 @@ from __future__ import annotations import os -import smtplib from collections.abc import Mapping -from email.message import EmailMessage -from email.utils import formatdate, make_msgid from app.core.contracts import RequestContext from app.service.authorization_service import AuthorizationService +from app.service.risk_smtp_mail_service import ( + RiskSmtpConfigurationError, + RiskSmtpMailService, +) class RiskDailyReportMailService: - def __init__(self, *, environment: Mapping[str, str] | None = None) -> None: - self.environment = environment or os.environ + def __init__( + self, + *, + environment: Mapping[str, str] | None = None, + smtp_service: RiskSmtpMailService | None = None, + ) -> None: + self.environment = environment if environment is not None else os.environ + self.smtp_service = smtp_service or RiskSmtpMailService( + environment=environment + ) async def send( self, @@ -36,28 +45,10 @@ class RiskDailyReportMailService: return {"status": "disabled", "recipient_count": len(recipients)} if _enabled(self.environment, "RISK_DAILY_REPORT_MAIL_DRY_RUN", default=True): return {"status": "dry_run", "recipient_count": len(recipients)} - host = self.environment.get("RISK_SMTP_HOST", "").strip() - sender = self.environment.get("RISK_SMTP_SENDER", "").strip() - if not host or not sender: + try: + return await self.smtp_service.send(recipients, subject, content) + except RiskSmtpConfigurationError: return {"status": "configuration_error", "recipient_count": len(recipients)} - message = EmailMessage() - message["From"] = sender - message["To"] = ", ".join(recipients) - message["Subject"] = subject - message["Date"] = formatdate(localtime=True) - message["Message-ID"] = make_msgid(domain="risk-report.local") - message.set_content(content) - port = int(self.environment.get("RISK_SMTP_PORT", "465")) - use_ssl = _enabled(self.environment, "RISK_SMTP_USE_SSL", default=True) - timeout = float(self.environment.get("RISK_SMTP_TIMEOUT_SECONDS", "30")) - smtp_class = smtplib.SMTP_SSL if use_ssl else smtplib.SMTP - with smtp_class(host, port, timeout=timeout) as connection: - username = self.environment.get("RISK_SMTP_USERNAME", "").strip() - password = self.environment.get("RISK_SMTP_PASSWORD", "") - if username: - connection.login(username, password) - connection.send_message(message) - return {"status": "sent", "recipient_count": len(recipients)} def _enabled(environment: Mapping[str, str], name: str, *, default: bool = False) -> bool: diff --git a/app/service/risk_notification_service.py b/app/service/risk_notification_service.py index 9cbddf3..c3eba08 100644 --- a/app/service/risk_notification_service.py +++ b/app/service/risk_notification_service.py @@ -93,6 +93,22 @@ class RiskNotificationService: self.session.add(notification) return notification + def mark_mail_sent(self, notification: FundRiskNotification) -> None: + """邮件发送成功后回写通知状态。""" + notification.send_status = "已发送" + notification.sent_at = _now() + notification.fail_reason = None + + def mark_mail_failed( + self, + notification: FundRiskNotification, + reason: str, + ) -> None: + """邮件发送失败后保留通知记录并记录安全失败原因。""" + notification.send_status = "发送失败" + notification.sent_at = None + notification.fail_reason = reason.strip()[:500] or "邮件发送失败" + def create_high_risk_records( self, alerts: list[FundRiskAlert], diff --git a/app/service/risk_scan_service.py b/app/service/risk_scan_service.py index 9a203da..555b2c7 100644 --- a/app/service/risk_scan_service.py +++ b/app/service/risk_scan_service.py @@ -16,6 +16,7 @@ from uuid import uuid4 from sqlalchemy import Select, func, select from sqlalchemy.ext.asyncio import AsyncSession +from app.core.config import get_settings from app.core.contracts import RequestContext from app.core.errors import AgentError, ConflictAgentError from app.core.timeutil import local_date, local_hour @@ -26,11 +27,17 @@ from app.model.fund import ( FundHolding, FundProduct, FundRiskAlert, + FundRiskNotification, FundTransaction, ) from app.model.risk import RiskLoginRecord, RiskUser, RiskWorkOrder from app.service.authorization_service import AuthorizationService from app.service.risk_notification_service import RiskNotificationService +from app.service.risk_smtp_mail_service import ( + RiskSmtpConfigurationError, + RiskSmtpMailService, + RiskSmtpSendError, +) HIGH_RISK = "高" MEDIUM_RISK = "中" @@ -510,6 +517,8 @@ class RiskScanService: notification_enabled: bool = True, notification_email: str | None = None, mail_enabled: bool = False, + mail_dry_run: bool = False, + smtp_mail_service: RiskSmtpMailService | None = None, ) -> None: self.session = session self.rule_engine = rule_engine or RiskRuleEngine(session) @@ -517,6 +526,31 @@ class RiskScanService: self.notification_enabled = notification_enabled self.notification_email = notification_email self.mail_enabled = mail_enabled + self.mail_dry_run = mail_dry_run + self.smtp_mail_service = smtp_mail_service or RiskSmtpMailService() + + @classmethod + def from_settings( + cls, + session: AsyncSession, + *, + rule_engine: RiskRuleEngine | None = None, + notification_service: RiskNotificationService | None = None, + ) -> RiskScanService: + """从环境配置创建扫描服务,供手工扫描和定时扫描共用。""" + settings = get_settings() + recipients = _parse_recipients(settings.risk_alert_mail_recipients) + notification_email = recipients[0] if recipients else None + if settings.risk_alert_mail_enabled and not notification_email: + logger.warning("高风险邮件通知已启用,但未配置收件人") + return cls( + session, + rule_engine=rule_engine, + notification_service=notification_service, + notification_email=notification_email, + mail_enabled=settings.risk_alert_mail_enabled and bool(notification_email), + mail_dry_run=settings.risk_alert_mail_dry_run, + ) async def scan(self, context: RequestContext) -> dict[str, int | str]: await AuthorizationService.require(context, "risk:alert:scan") @@ -572,7 +606,7 @@ class RiskScanService: ) count += 1 if self.notification_email: - self.notification_service.create_mail_record( + notification = self.notification_service.create_mail_record( alert, receiver_email=self.notification_email, title=title, @@ -580,11 +614,48 @@ class RiskScanService: mail_enabled=self.mail_enabled, ) count += 1 + if self.mail_enabled: + await self._deliver_mail( + alert, + notification, + title, + ) return count, "" except Exception as error: logger.exception("高风险通知记录创建失败,预警扫描继续提交") return 0, f"{type(error).__name__}: {error}"[:200] + async def _deliver_mail( + self, + alert: FundRiskAlert, + notification: FundRiskNotification, + title: str, + ) -> None: + """发送高风险通知邮件,失败只回写通知记录,不影响预警落库。""" + if self.mail_dry_run: + self.notification_service.mark_mail_failed( + notification, + "邮件发送处于 dry-run 模式", + ) + return + try: + result = await self.smtp_mail_service.send( + [self.notification_email or ""], + title, + f"预警编号:{alert.alert_no};{alert.evidence_summary}", + ) + except (RiskSmtpConfigurationError, RiskSmtpSendError) as error: + logger.warning("高风险预警邮件发送失败:alert_no=%s error=%s", alert.alert_no, error) + self.notification_service.mark_mail_failed(notification, str(error)) + except Exception: + logger.exception("高风险预警邮件发送发生未预期异常:alert_no=%s", alert.alert_no) + self.notification_service.mark_mail_failed(notification, "邮件发送发生未预期异常") + else: + if result.get("status") == "sent": + self.notification_service.mark_mail_sent(notification) + else: + self.notification_service.mark_mail_failed(notification, "邮件发送未完成") + def _new_alert_id() -> int: """生成非零 63 位正整数;预警表主键不自增。""" @@ -614,3 +685,14 @@ def _level_value(level: str, prefix: str) -> int | None: """ digits = level.strip().upper().removeprefix(prefix.upper()) return int(digits) if digits.isdigit() else None + + +def _parse_recipients(value: str | None) -> list[str]: + """解析逗号或分号分隔的邮件收件人配置。""" + if not value: + return [] + return [ + recipient.strip() + for recipient in value.replace(";", ",").split(",") + if recipient.strip() + ] diff --git a/app/service/risk_smtp_mail_service.py b/app/service/risk_smtp_mail_service.py new file mode 100644 index 0000000..3dbb13a --- /dev/null +++ b/app/service/risk_smtp_mail_service.py @@ -0,0 +1,117 @@ +"""风控模块共用的 SMTP 邮件发送服务。""" + +from __future__ import annotations + +import asyncio +import os +import smtplib +from collections.abc import Mapping +from email.message import EmailMessage +from email.utils import formatdate, make_msgid, parseaddr + + +class RiskSmtpConfigurationError(ValueError): + """SMTP 配置缺失或格式无效。""" + + +class RiskSmtpSendError(RuntimeError): + """SMTP 邮件发送失败。""" + + +class RiskSmtpMailService: + """使用 ``RISK_SMTP_*`` 配置发送风控邮件。""" + + def __init__(self, *, environment: Mapping[str, str] | None = None) -> None: + self.environment = environment if environment is not None else os.environ + + async def send( + self, + recipients: list[str], + subject: str, + content: str, + ) -> dict[str, object]: + return await asyncio.to_thread( + self._send_sync, + recipients, + subject, + content, + ) + + def _send_sync( + self, + recipients: list[str], + subject: str, + content: str, + ) -> dict[str, object]: + normalized = self._validated_recipients(recipients) + host = self.environment.get("RISK_SMTP_HOST", "").strip() + sender = self.environment.get("RISK_SMTP_SENDER", "").strip() + if not host or not sender: + raise RiskSmtpConfigurationError("SMTP 发件配置缺失") + if not _is_email(sender): + raise RiskSmtpConfigurationError("SMTP 发件地址格式无效") + if not subject.strip() or not content.strip(): + raise RiskSmtpConfigurationError("邮件主题和正文不能为空") + if "\r" in subject or "\n" in subject: + raise RiskSmtpConfigurationError("邮件主题包含非法换行") + + message = EmailMessage() + message["From"] = sender + message["To"] = ", ".join(normalized) + message["Subject"] = subject + message["Date"] = formatdate(localtime=True) + message["Message-ID"] = make_msgid(domain="risk-alert.local") + message.set_content(content) + + port = int(self.environment.get("RISK_SMTP_PORT", "465")) + use_ssl = _enabled(self.environment, "RISK_SMTP_USE_SSL", default=True) + timeout = float(self.environment.get("RISK_SMTP_TIMEOUT_SECONDS", "30")) + smtp_class = smtplib.SMTP_SSL if use_ssl else smtplib.SMTP + try: + with smtp_class(host, port, timeout=timeout) as connection: + username = self.environment.get("RISK_SMTP_USERNAME", "").strip() + password = self.environment.get("RISK_SMTP_PASSWORD", "") + if username: + connection.login(username, password) + connection.send_message(message) + except smtplib.SMTPAuthenticationError as error: + raise RiskSmtpSendError("SMTP 身份验证失败") from error + except smtplib.SMTPRecipientsRefused as error: + raise RiskSmtpSendError("收件人被邮件服务器拒绝") from error + except smtplib.SMTPSenderRefused as error: + raise RiskSmtpSendError("发件人被邮件服务器拒绝") from error + except TimeoutError as error: + raise RiskSmtpSendError("SMTP 连接超时") from error + except OSError as error: + raise RiskSmtpSendError(f"SMTP 连接失败:{error}") from error + except smtplib.SMTPException as error: + raise RiskSmtpSendError("SMTP 邮件发送失败") from error + return {"status": "sent", "recipient_count": len(normalized)} + + @staticmethod + def _validated_recipients(recipients: list[str]) -> list[str]: + normalized: list[str] = [] + seen: set[str] = set() + for value in recipients: + recipient = value.strip() + if not _is_email(recipient): + raise RiskSmtpConfigurationError("收件人地址格式无效") + lowered = recipient.lower() + if lowered not in seen: + normalized.append(recipient) + seen.add(lowered) + if not normalized: + raise RiskSmtpConfigurationError("收件人不能为空") + return normalized + + +def _enabled(environment: Mapping[str, str], name: str, *, default: bool = False) -> bool: + value = environment.get(name) + if value is None: + return default + return value.strip().lower() in {"1", "true", "yes", "on"} + + +def _is_email(value: str) -> bool: + _, parsed = parseaddr(value) + return bool(value and parsed == value and "@" in value and len(value) <= 254) diff --git a/app/worker/risk_scan_scheduler.py b/app/worker/risk_scan_scheduler.py index 9c5a4f1..4cd9e07 100644 --- a/app/worker/risk_scan_scheduler.py +++ b/app/worker/risk_scan_scheduler.py @@ -46,7 +46,7 @@ async def default_scan_executor() -> dict[str, int | str]: portal="worker", ) async with SessionFactory() as session: - return await RiskScanService(session).scan(context) + return await RiskScanService.from_settings(session).scan(context) async def default_audit_writer(status: str, detail: dict[str, Any]) -> None: diff --git a/tests/unit/api/test_risk_controller.py b/tests/unit/api/test_risk_controller.py index 995789e..840294c 100644 --- a/tests/unit/api/test_risk_controller.py +++ b/tests/unit/api/test_risk_controller.py @@ -56,6 +56,10 @@ class StubRiskScanService: def __init__(self, _session: Any) -> None: pass + @classmethod + def from_settings(cls, session: Any) -> "StubRiskScanService": + return cls(session) + async def scan(self, _context: RequestContext) -> dict[str, Any]: return {"message": "规则扫描完成", "created_count": 2, "high_risk_count": 1} diff --git a/tests/unit/service/test_risk_scan_alert_mail.py b/tests/unit/service/test_risk_scan_alert_mail.py new file mode 100644 index 0000000..15d7db1 --- /dev/null +++ b/tests/unit/service/test_risk_scan_alert_mail.py @@ -0,0 +1,125 @@ +"""验证高风险预警扫描会真实调用 SMTP,并正确回写通知状态。""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, cast + +import pytest + +from app.service.risk_scan_service import HIGH_RISK, RiskScanService +from app.service.risk_smtp_mail_service import RiskSmtpSendError + + +class FakeNested: + async def __aenter__(self) -> FakeNested: + return self + + async def __aexit__(self, *_args: object) -> bool: + return False + + +class FakeSession: + def begin_nested(self) -> FakeNested: + return FakeNested() + + +class FakeNotificationService: + def __init__(self) -> None: + self.mail_records: list[Any] = [] + self.mail_marks: list[tuple[str, str | None]] = [] + + def create_in_app(self, _alert: Any, **_kwargs: Any) -> None: + return None + + def create_mail_record(self, alert: Any, **_kwargs: Any) -> Any: + notification = SimpleNamespace( + alert=alert, + send_status="待发送", + sent_at=None, + fail_reason=None, + ) + self.mail_records.append(notification) + return notification + + def mark_mail_sent(self, notification: Any) -> None: + self.mail_marks.append(("sent", None)) + notification.send_status = "已发送" + + def mark_mail_failed(self, notification: Any, reason: str) -> None: + self.mail_marks.append(("failed", reason)) + notification.send_status = "发送失败" + + +def alert() -> Any: + return SimpleNamespace( + alert_level=HIGH_RISK, + alert_no="ALTEST", + alert_type="大额快进快出", + evidence_summary="3 日内入金后大额赎回", + handler_id=9002, + ) + + +def service() -> RiskScanService: + instance = object.__new__(RiskScanService) + instance.session = cast(Any, FakeSession()) + instance.notification_enabled = True + instance.notification_email = "risk@example.com" + instance.mail_enabled = True + instance.mail_dry_run = False + instance.notification_service = cast(Any, FakeNotificationService()) + return instance + + +@pytest.mark.asyncio +async def test_high_risk_mail_is_sent_and_marked_successful() -> None: + class SmtpStub: + def __init__(self) -> None: + self.calls: list[tuple[list[str], str, str]] = [] + + async def send( + self, + recipients: list[str], + subject: str, + content: str, + ) -> dict[str, object]: + self.calls.append((recipients, subject, content)) + return {"status": "sent", "recipient_count": len(recipients)} + + instance = service() + notifier = cast(FakeNotificationService, instance.notification_service) + smtp = SmtpStub() + instance.smtp_mail_service = cast(Any, smtp) + + count, failure = await instance._create_notifications([alert()]) + + assert count == 2 + assert failure == "" + assert smtp.calls[0][0] == ["risk@example.com"] + assert "预警编号:ALTEST" in smtp.calls[0][2] + assert notifier.mail_marks == [("sent", None)] + assert notifier.mail_records[0].send_status == "已发送" + + +@pytest.mark.asyncio +async def test_high_risk_mail_failure_does_not_abort_scan() -> None: + class FailingSmtp: + async def send( + self, + _recipients: list[str], + _subject: str, + _content: str, + ) -> dict[str, object]: + raise RiskSmtpSendError("SMTP 身份验证失败") + + instance = service() + notifier = cast(FakeNotificationService, instance.notification_service) + instance.smtp_mail_service = cast(Any, FailingSmtp()) + + count, failure = await instance._create_notifications([alert()]) + + assert count == 2 + assert failure == "" + assert notifier.mail_marks == [("failed", "SMTP 身份验证失败")] + assert notifier.mail_records[0].send_status == "发送失败" diff --git a/tests/unit/service/test_risk_scan_notification.py b/tests/unit/service/test_risk_scan_notification.py index ec3a1fe..3bcb32b 100644 --- a/tests/unit/service/test_risk_scan_notification.py +++ b/tests/unit/service/test_risk_scan_notification.py @@ -38,6 +38,8 @@ class _FakeNotificationService: def __init__(self, *, fail: bool = False) -> None: self.fail = fail self.in_app: list[str] = [] + self.mail_records: list[Any] = [] + self.mail_marks: list[tuple[str, str | None]] = [] def create_in_app(self, alert: Any, **kwargs: Any) -> None: if self.fail: @@ -47,6 +49,22 @@ class _FakeNotificationService: def create_mail_record(self, alert: Any, **kwargs: Any) -> None: if self.fail: raise RuntimeError("邮件记录写库失败") + notification = SimpleNamespace( + alert=alert, + send_status="待发送", + sent_at=None, + fail_reason=None, + ) + self.mail_records.append(notification) + return notification + + def mark_mail_sent(self, notification: Any) -> None: + self.mail_marks.append(("sent", None)) + notification.send_status = "已发送" + + def mark_mail_failed(self, notification: Any, reason: str) -> None: + self.mail_marks.append(("failed", reason)) + notification.send_status = "发送失败" def _alert(level: str, alert_no: str = "ALTEST") -> Any: diff --git a/tests/unit/service/test_risk_smtp_mail_service.py b/tests/unit/service/test_risk_smtp_mail_service.py new file mode 100644 index 0000000..e2d0145 --- /dev/null +++ b/tests/unit/service/test_risk_smtp_mail_service.py @@ -0,0 +1,71 @@ +"""验证风控共用 SMTP 服务的基础发送行为。""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from app.service import risk_smtp_mail_service +from app.service.risk_smtp_mail_service import ( + RiskSmtpConfigurationError, + RiskSmtpMailService, +) + + +class SmtpStub: + instances: list[SmtpStub] = [] + + def __init__(self, host: str, port: int, timeout: float) -> None: + self.host = host + self.port = port + self.timeout = timeout + self.login_args: tuple[str, str] | None = None + self.message: Any = None + self.__class__.instances.append(self) + + def __enter__(self) -> SmtpStub: + return self + + def __exit__(self, *_args: object) -> None: + return None + + def login(self, username: str, password: str) -> None: + self.login_args = (username, password) + + def send_message(self, message: Any) -> None: + self.message = message + + +@pytest.mark.asyncio +async def test_smtp_service_sends_message(monkeypatch: pytest.MonkeyPatch) -> None: + SmtpStub.instances = [] + monkeypatch.setattr(risk_smtp_mail_service.smtplib, "SMTP_SSL", SmtpStub) + + result = await RiskSmtpMailService( + environment={ + "RISK_SMTP_HOST": "smtp.example.com", + "RISK_SMTP_PORT": "465", + "RISK_SMTP_USERNAME": "sender@example.com", + "RISK_SMTP_PASSWORD": "secret", + "RISK_SMTP_SENDER": "sender@example.com", + "RISK_SMTP_USE_SSL": "true", + } + ).send(["risk@example.com"], "高风险预警", "请复核") + + assert result == {"status": "sent", "recipient_count": 1} + client = SmtpStub.instances[0] + assert (client.host, client.port) == ("smtp.example.com", 465) + assert client.login_args == ("sender@example.com", "secret") + assert client.message["To"] == "risk@example.com" + assert client.message["Subject"] == "高风险预警" + + +@pytest.mark.asyncio +async def test_smtp_service_rejects_missing_configuration() -> None: + with pytest.raises(RiskSmtpConfigurationError): + await RiskSmtpMailService(environment={}).send( + ["risk@example.com"], + "高风险预警", + "请复核", + )