import os import base64 from datetime import datetime import pytz import sib_api_v3_sdk from sib_api_v3_sdk.rest import ApiException ### Email Utility Functions ### def load_email_template(): """Load the HTML email template""" try: template_path = 'src/email_template/email_template.html' with open(template_path, 'r', encoding='utf-8') as file: return file.read() except FileNotFoundError: print("Email template file not found.") return None def send_email(to_email, subject, html_content, to_name="Valued Customer", cc_list=None): """Send email using the Brevo (Sendinblue) API""" try: api_key = os.getenv("BREVO_API_KEY") if not api_key: raise Exception("BREVO_API_KEY environment variable not set.") configuration = sib_api_v3_sdk.Configuration() configuration.api_key["api-key"] = api_key api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration)) sender = {"name": "Blue Bean Data", "email": "info@bluebeandata.com"} to = [{"email": to_email, "name": to_name}] cc = [] if cc_list: for cc_email in cc_list: cc.append({"email": cc_email}) send_smtp_email = sib_api_v3_sdk.SendSmtpEmail( to=to, sender=sender, subject=subject, html_content=html_content, cc=cc if cc else None ) try: response = api_instance.send_transac_email(send_smtp_email) return True except ApiException as e: print(f"Brevo API Exception: {e}") return False except Exception as e: print(f"Error sending email with Brevo: {str(e)}") return False def _embed_logo_in_template(template): """Replaces the logo placeholder with a web-hosted image URL.""" logo_url = "https://huggingface.co/spaces/krinya/bluebeandatachatbot/resolve/main/src/email_template/bluebeanlogo.png" return template.replace("__LOGO_SRC__", logo_url) def send_user_welcome_email(email, name="Valued Customer", notes=""): """Send a welcome email to the user and a notification to the company.""" try: template = load_email_template() if not template: return False template_with_logo = _embed_logo_in_template(template) # Handle name display - use generic greeting if no name provided if not name or name.strip().lower() in ['name not provided', 'not provided', '']: greeting = "Greetings," display_name = "Valued Customer" else: greeting = f"Dear {name}," display_name = name # Build user info section dynamically user_info_items = [f"
  • Email: {email}
  • "] if display_name != "Valued Customer": user_info_items.append(f"
  • Name: {display_name}
  • ") if notes and notes.strip() and notes.strip().lower() not in ['not provided', 'none', '']: # Format notes nicely for email display formatted_notes = notes.replace('\n', '
    ') user_info_items.append(f"
  • Conversation Context: {formatted_notes}
  • ") user_info_html = "\n ".join(user_info_items) user_content = f"""

    {greeting}

    Thank you for your interest in Blue Bean Data! We're excited to connect with you.

    Our team specializes in:

    We've received your details and will be in touch shortly. For your records, here is the information you provided:

    Best regards,
    The Blue Bean Data Team

    """ user_subject = "Thank You for Connecting with Blue Bean Data!" button_html = 'Visit Our Website' user_html = template_with_logo.replace("__TITLE__", user_subject) \ .replace("__CONTENT__", user_content) \ .replace("__BUTTON_HTML__", button_html) company_email = os.getenv("COMPANY_EMAIL") cc_emails = [company_email] if company_email and company_email.lower() != email.lower() else [] return send_email(email, user_subject, user_html, to_name=display_name, cc_list=cc_emails) except Exception as e: print(f"Error in send_user_welcome_email: {str(e)}") return False def send_unknown_question_email(question): """Send an email to the company with a question the chatbot couldn't answer.""" try: company_email = 'menyhert.kristof@gmail.com' if not company_email: print("COMPANY_EMAIL environment variable not set. Cannot send unknown question email.") return False template = load_email_template() if not template: return False template_with_logo = _embed_logo_in_template(template) amsterdam_tz = pytz.timezone('Europe/Amsterdam') timestamp = datetime.now(amsterdam_tz).strftime('%Y-%m-%d %H:%M:%S %Z') subject = "Chatbot Alert: Unknown Question" content = f"""

    The AI assistant was unable to answer the following question:

    "{question}"

    This might be an opportunity to update the knowledge base or add new content to better serve future inquiries.

    Timestamp: {timestamp}

    Best regards,
    Blue Bean Data AI Assistant

    """ html_body = template_with_logo.replace("__TITLE__", subject) \ .replace("__CONTENT__", content) \ .replace("__BUTTON_HTML__", "") return send_email('menyhert.kristof@gmail.com', subject, html_body, to_name="Blue Bean Data Team", cc_list=[company_email]) except Exception as e: print(f"Error in send_unknown_question_email: {str(e)}") return False