Spaces:
Sleeping
Sleeping
File size: 6,627 Bytes
bdc5888 6513205 bdc5888 6513205 bdc5888 16ab289 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 2db519a bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 7758833 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 bdc5888 6513205 7758833 bdc5888 6513205 bdc5888 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | 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"<li><b>Email:</b> {email}</li>"]
if display_name != "Valued Customer":
user_info_items.append(f"<li><b>Name:</b> {display_name}</li>")
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', '<br>')
user_info_items.append(f"<li><b>Conversation Context:</b> {formatted_notes}</li>")
user_info_html = "\n ".join(user_info_items)
user_content = f"""
<p>{greeting}</p>
<p>Thank you for your interest in Blue Bean Data! We're excited to connect with you.</p>
<p>Our team specializes in:</p>
<ul>
<li>Data Strategy & Consulting</li>
<li>BI & Dashboards</li>
<li>Data Pipeline Development</li>
<li>AI & Automation</li>
</ul>
<p>We've received your details and will be in touch shortly. For your records, here is the information you provided:</p>
<ul>
{user_info_html}
</ul>
<p>Best regards,<br>The Blue Bean Data Team</p>
"""
user_subject = "Thank You for Connecting with Blue Bean Data!"
button_html = '<a href="www.bluebeandata.com" class="button">Visit Our Website</a>'
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"""
<p><strong>The AI assistant was unable to answer the following question:</strong></p>
<div style="background-color: #f8f9fa; padding: 15px; border-left: 4px solid #3364D1; margin: 15px 0;">
<p style="font-style: italic; margin: 0;">"{question}"</p>
</div>
<p>This might be an opportunity to update the knowledge base or add new content to better serve future inquiries.</p>
<p><small><b>Timestamp:</b> {timestamp}</small></p>
<p>Best regards,<br>Blue Bean Data AI Assistant</p>
"""
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
|