""" email_service.py — PragatiVeer Transactional Email Service Uses SMTP credentials from environment variables. Falls back to console-log mode if SMTP is not configured. """ import os import smtplib import logging from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from typing import Optional logger = logging.getLogger("email_service") SMTP_HOST = os.getenv("SMTP_HOST", "") SMTP_PORT = int(os.getenv("SMTP_PORT", "587")) SMTP_USER = os.getenv("SMTP_USER", "") SMTP_PASS = os.getenv("SMTP_PASS", "") SMTP_FROM_NAME = os.getenv("SMTP_FROM_NAME", "PragatiVeer") SMTP_FROM_EMAIL = os.getenv("SMTP_FROM_EMAIL", SMTP_USER) _SMTP_CONFIGURED = bool(SMTP_HOST and SMTP_USER and SMTP_PASS) def send_email(to: str, subject: str, html_body: str, text_body: Optional[str] = None) -> bool: """ Send a transactional email. Returns True on success, False on failure. If SMTP is not configured, logs the email to console and returns True (no-op mode). """ if not _SMTP_CONFIGURED: logger.warning(f"[EMAIL NO-OP] SMTP not configured. Would send to={to}, subject={subject}") return True try: msg = MIMEMultipart("alternative") msg["Subject"] = subject msg["From"] = f"{SMTP_FROM_NAME} <{SMTP_FROM_EMAIL}>" msg["To"] = to if text_body: msg.attach(MIMEText(text_body, "plain")) msg.attach(MIMEText(html_body, "html")) with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server: server.ehlo() server.starttls() server.login(SMTP_USER, SMTP_PASS) server.sendmail(SMTP_FROM_EMAIL, to, msg.as_string()) logger.info(f"[EMAIL SENT] to={to}, subject={subject}") return True except Exception as e: logger.error(f"[EMAIL FAILED] to={to}, subject={subject}, error={e}") return False # --- Pre-built Email Templates --- def send_welcome_email(to: str, name: str) -> bool: subject = "🎉 Welcome to PragatiVeer — Your JEE/NEET Journey Starts Now!" html_body = f"""
AI-Powered Exam Preparation
Your account has been created successfully. You now have access to:
PragatiVeer Education Pvt. Ltd. | Jaipur, Rajasthan
Use this code to complete {purpose}:
This code expires in 10 minutes.
If you did not request this OTP, please ignore this email.
We received a request to reset the password for your PragatiVeer account. Click the button below to set a new password:
This link expires in 1 hour. If you did not request a password reset, you can safely ignore this email.
PragatiVeer Education Pvt. Ltd. | Jaipur, Rajasthan