"""Email service — send verification codes via SMTP (Timeweb)."""
import logging
import os
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
logger = logging.getLogger(__name__)
SMTP_HOST = os.environ.get("SMTP_HOST", "smtp.timeweb.ru")
SMTP_PORT = int(os.environ.get("SMTP_PORT", "465"))
SMTP_USER = os.environ.get("SMTP_USER", "")
SMTP_PASS = os.environ.get("SMTP_PASS", "")
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 = "Код подтверждения — Сметный ИИ-ассистент"
html = f"""
Сметный ИИ-ассистент
Ваш код подтверждения:
{code}
Код действителен 10 минут.
Если вы не регистрировались — проигнорируйте это письмо.
"""
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
def send_alert(subject: str, text: str, to_email: str | None = None) -> bool:
"""Send a plain-text operational alert to the operator. Returns True on success.
Recipient: explicit arg → ALERT_EMAIL env → SMTP_USER (self). Used by
scripts/agent_canary.sh when the Claude agent path goes down.
"""
to = to_email or os.environ.get("ALERT_EMAIL") or SMTP_USER
if not SMTP_USER or not SMTP_PASS or not to:
logger.warning("SMTP/ALERT not configured, skipping alert")
return False
from email.header import Header
msg = MIMEText(text, "plain", "utf-8")
msg["Subject"] = subject
msg["From"] = f"{Header('Сметный ассистент', 'utf-8').encode()} <{SMTP_USER}>"
msg["To"] = to
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, msg.as_string())
logger.info("Alert email sent to %s", to)
return True
except Exception as e:
logger.error("Failed to send alert to %s: %s", to, e)
return False