import os import smtplib import logging from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from threading import Thread logger = logging.getLogger(__name__) def _send_email_async(subject: str, body: str): """Internal function running on a background thread to send the email.""" smtp_host = os.environ.get('SMTP_HOST') smtp_port = os.environ.get('SMTP_PORT', '587') smtp_user = os.environ.get('SMTP_USER') smtp_pass = os.environ.get('SMTP_PASSWORD') to_email = 'sales@freshbeats.ai' # If credentials are not configured, print to logs/stdout and exit cleanly if not smtp_host or not smtp_user or not smtp_pass: logger.warning("Email notification skipped: SMTP environment variables (SMTP_HOST, SMTP_USER, SMTP_PASSWORD) are not fully configured.") logger.info(f"[Email Stub to {to_email}] Subject: {subject}\nBody:\n{body}") return try: # Create message msg = MIMEMultipart() msg['From'] = smtp_user msg['To'] = to_email msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) # Connect and send server = smtplib.SMTP(smtp_host, int(smtp_port), timeout=10) server.starttls() server.login(smtp_user, smtp_pass) server.sendmail(smtp_user, to_email, msg.as_string()) server.quit() logger.info(f"Notification email successfully sent to {to_email}") except Exception as e: logger.error(f"Failed to send SMTP notification email to {to_email}: {e}") def send_notification_email(subject: str, body: str): """ Sends a notification email to sales@freshbeats.ai. This runs asynchronously on a background thread to prevent blocking the request lifecycle. """ # Only execute if running in HuggingFace Spaces environment if os.environ.get('HF_SPACE', '0') == '1': thread = Thread(target=_send_email_async, args=(subject, body)) thread.daemon = True thread.start() else: logger.info(f"Local development mode - skipping HF email alert: {subject}")