LawBot / src /apps /email_utils.py
Vishwanath77's picture
Update src/apps/email_utils.py
1120d20 verified
import os
from dotenv import load_dotenv
import httpx
import asyncio
load_dotenv()
# Consistent URL usage for deployment
BASE_URL = os.getenv("APP_URL", "https://legal-assistant-lawbot.hf.space")
# Brevo (Sendinblue) Configuration
BREVO_API_KEY = os.getenv("BREVO_API_KEY", "")
# Must be your verified sender in Brevo
BREVO_SENDER_EMAIL = os.getenv("BREVO_SENDER_EMAIL", "vishwaroman04@gmail.com")
async def send_reset_email(email: str, token: str):
"""Send password reset email using Brevo (Sendinblue) API"""
if not BREVO_API_KEY:
raise ValueError("BREVO_API_KEY missing. Please add it to Secrets.")
reset_link = f"{BASE_URL}/reset-password?token={token}"
html_body = f"""
<html>
<body style="font-family: Arial, sans-serif; padding: 20px; background-color: #f4f4f4;">
<div style="max-width: 600px; margin: 0 auto; background-color: white; padding: 30px; border-radius: 10px;">
<h2 style="color: #9b87f5;">Password Reset Request</h2>
<p>Hello,</p>
<p>We received a request to reset your password for your Law Bot account.</p>
<p>Click the button below to reset your password:</p>
<a href="{reset_link}" style="display: inline-block; padding: 12px 24px; background-color: #9b87f5; color: white; text-decoration: none; border-radius: 6px; margin: 20px 0;">Reset Password</a>
<p>Or copy and paste this link into your browser:</p>
<p style="color: #666; word-break: break-all;">{reset_link}</p>
<p style="color: #999; font-size: 12px; margin-top: 30px;">If you didn't request this, you can safely ignore this email.</p>
<hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
<p style="color: #999; font-size: 11px; text-align: center;">
Law Bot India - AI Legal Assistant<br>
<a href="https://legal-assistant-lawbot.hf.space" style="color: #9b87f5;">https://legal-assistant-lawbot.hf.space</a>
</p>
</div>
</body>
</html>
"""
url = "https://api.brevo.com/v3/smtp/email"
payload = {
"sender": {"name": "Law Bot India", "email": BREVO_SENDER_EMAIL},
"to": [{"email": email}],
"subject": "Password Reset Request - Law Bot",
"htmlContent": html_body
}
headers = {
"accept": "application/json",
"api-key": BREVO_API_KEY,
"content-type": "application/json"
}
try:
async with httpx.AsyncClient() as client:
response = await client.post(url, json=payload, headers=headers, timeout=10.0)
if response.status_code in [200, 201, 202]:
print(f"βœ… Email sent successfully via Brevo to {email}")
return True
else:
error_msg = f"Brevo API Error: {response.status_code} - {response.text}"
print(f"❌ {error_msg}")
raise ValueError(error_msg)
except Exception as e:
print(f"❌ Failed to send via Brevo: {e}")
raise ValueError(f"Failed to send email: {str(e)}")