From 58560ed28c537f86b919404156a1b52fe68622ab Mon Sep 17 00:00:00 2001 From: anor Date: Tue, 8 Sep 2026 03:17:50 +1000 Subject: [PATCH] =?UTF-8?q?refactor(=D0=BF=D0=BE=D1=87=D1=82=D0=B0):=20?= =?UTF-8?q?=D0=B2=D1=81=D0=B5=20=D0=BF=D0=B8=D1=81=D1=8C=D0=BC=D0=B0=20?= =?UTF-8?q?=D0=B8=D0=B4=D1=83=D1=82=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20?= =?UTF-8?q?=D0=BE=D0=B4=D0=BD=D1=83=20=D1=82=D0=BE=D1=87=D0=BA=D1=83=20?= =?UTF-8?q?=D0=BE=D1=82=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Находка ревью: я вынес общую точку _send ради одного места для соединения, входа и обработки сбоя, но две старые функции продолжали держать свои копии — тогда вынос бессмысленен, и любая правка в _send их бы не касалась. Заодно чинится настоящий дефект: у письма оператору не было текстовой части, и в почтовых клиентах с отключённым HTML оно приходило пустым. Теперь текст собирается из разметки. Прогон: весь набор 977 зелёных; на боевом сервере после выката проверю живой отправкой, что письмо с кодом и письмо об открытии доступа уходят. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01RuEU1u9Rz24zmoy9TuvWc2 --- email_service.py | 56 +++++++++--------------------------------------- main.py | 2 +- 2 files changed, 11 insertions(+), 47 deletions(-) diff --git a/email_service.py b/email_service.py index ed67842..418a263 100644 --- a/email_service.py +++ b/email_service.py @@ -2,6 +2,7 @@ import logging import os +import re import smtplib import ssl from email.mime.multipart import MIMEMultipart @@ -36,37 +37,18 @@ def smtp_healthcheck() -> bool: def send_operator_digest(to_email: str, subject: str, html: str) -> bool: - """Дайджест оператору о новостях внешних источников (чекер ext_check). True при успехе.""" - if not SMTP_USER or not SMTP_PASS: - logger.warning("SMTP not configured, skipping operator digest to %s", to_email) - return False - if not to_email: - return False - msg = MIMEMultipart("alternative") - from email.header import Header - msg["Subject"] = subject - msg["From"] = f"{Header('Сметный ассистент', 'utf-8').encode()} <{SMTP_USER}>" - msg["To"] = to_email - msg.attach(MIMEText(html, "html", "utf-8")) - try: - context = ssl.create_default_context() - with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=context, timeout=10) as server: - server.login(SMTP_USER, SMTP_PASS) - server.sendmail(SMTP_USER, to_email, msg.as_string()) - logger.info("Operator digest sent to %s", to_email) - return True - except Exception as e: # noqa: BLE001 - logger.error("Failed to send operator digest to %s: %s", to_email, e) - return False + """Сводка оператору о новостях внешних источников (чекер ext_check).""" + # Текстовая часть обязательна: без неё в клиентах с отключённым HTML письмо приходит + # пустым, и оператор не видит содержимого (находка ревью 08.09.2026). + text = re.sub(r"<[^>]+>", " ", html) + text = re.sub(r"\s+", " ", text).strip() or subject + return _send(to_email, subject, text, html) def send_verification_code(to_email: str, code: str) -> bool: - """Send 6-digit verification code to email. Returns True on success.""" - if not SMTP_USER or not SMTP_PASS: - logger.warning("SMTP not configured, skipping email to %s", to_email) - return False - + """Код подтверждения при регистрации.""" subject = "Код подтверждения — Сметный ИИ-ассистент" + text = f"Ваш код подтверждения: {code}\nДействителен 10 минут." html = f"""

Сметный ИИ-ассистент

@@ -78,25 +60,7 @@ def send_verification_code(to_email: str, code: str) -> bool:

Если вы не регистрировались — проигнорируйте это письмо.

""" - - msg = MIMEMultipart("alternative") - msg["Subject"] = subject - from email.header import Header - msg["From"] = f"{Header('Сметный ассистент', 'utf-8').encode()} <{SMTP_USER}>" - msg["To"] = to_email - msg.attach(MIMEText(f"Ваш код подтверждения: {code}\nДействителен 10 минут.", "plain", "utf-8")) - msg.attach(MIMEText(html, "html", "utf-8")) - - try: - context = ssl.create_default_context() - with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=context, timeout=10) as server: - server.login(SMTP_USER, SMTP_PASS) - server.sendmail(SMTP_USER, to_email, msg.as_string()) - logger.info("Verification email sent to %s", to_email) - return True - except Exception as e: - logger.error("Failed to send email to %s: %s", to_email, e) - return False + return _send(to_email, subject, text, html) def _send(to_email: str, subject: str, text: str, html: str) -> bool: diff --git a/main.py b/main.py index c970b7b..7eb3518 100644 --- a/main.py +++ b/main.py @@ -214,7 +214,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-09-08c" +APP_VERSION = "2026-09-08d" # Audit: path → action name mapping _AUDIT_MAP = [