"""
PolicyEye — Email Service (Resend)
Uses the Resend HTTP API instead of SMTP, which works on Hugging Face Spaces
(HF blocks all outbound SMTP ports 25/465/587).
"""
import logging
import os
import base64
from typing import Optional
import resend
from core.config import RESEND_API_KEY, MAIL_FROM
logger = logging.getLogger(__name__)
# Initialize Resend
if RESEND_API_KEY:
resend.api_key = RESEND_API_KEY
logger.info("[Mailer] Resend API configured successfully.")
else:
logger.warning("[Mailer] RESEND_API_KEY not set. Emails will be mocked in logs.")
def _build_welcome_html(to_email: str) -> str:
"""Build a professional, spam-filter-friendly welcome email."""
return f"""\
Welcome to PolicyEye
PolicyEye
AI-Powered Insurance Eligibility Engine
|
Welcome aboard! 🎉
Your PolicyEye account has been successfully verified.
You can now upload your health insurance policy documents and check claim eligibility using our AI-powered engine with zero-hallucination verdicts.
Our system uses 5 specialized agents and 18 custom tools, all compliant with IRDAI 2024 regulations.
|
|
This email was sent by PolicyEye because you created an account at
policyeye.app.
If you did not create this account, please ignore this email.
© 2026 PolicyEye. Built with transparency in mind.
|
|
"""
def _build_grievance_html() -> str:
"""Build a professional grievance notification email."""
return """\
Your Grievance Report — PolicyEye
PolicyEye
AI-Powered Insurance Eligibility Engine
|
Your Grievance Report is Ready 📋
The PolicyEye Grievance Agent has completed its analysis of your claim and generated an official grievance report.
The attached PDF includes:
- Detailed breakdown of your policy rules
- IRDAI regulatory compliance analysis
- Precedent rulings from the Insurance Ombudsman
- A formal grievance letter addressed to your insurer
Please find the PDF report attached to this email.
You may forward this email directly to your insurer's Grievance Redressal Officer.
|
|
This grievance report was generated by PolicyEye's AI Grievance Agent.
It is provided for informational purposes and does not constitute legal advice.
© 2026 PolicyEye. Built with transparency in mind.
|
|
"""
def _build_thank_you_html() -> str:
"""Build a professional thank you email for app feedback."""
return """\
Thank You for Your Feedback
PolicyEye
|
Thank you for your feedback! 🙏
We have received your rating and comments. Your insights directly shape the future of PolicyEye and help us build a smarter, more accurate AI engine.
If you reported a bug or a pain point, our development team is reviewing it immediately.
|
|
© 2026 PolicyEye. All rights reserved.
|
|
"""
async def send_welcome_email(to_email: str):
"""Send a welcome email to new users after signup."""
if not RESEND_API_KEY:
logger.info(f"[Mailer Mock] Welcome email → {to_email}")
return
try:
params: resend.Emails.SendParams = {
"from": MAIL_FROM,
"to": [to_email],
"subject": "Welcome to PolicyEye — Account Verified ✓",
"html": _build_welcome_html(to_email),
"headers": {
"X-Entity-Ref-ID": f"welcome-{to_email}",
},
"tags": [
{"name": "category", "value": "welcome"},
{"name": "app", "value": "policyeye"},
],
}
email_resp = resend.Emails.send(params)
logger.info(f"[Mailer] Welcome email sent to {to_email} (id: {email_resp.get('id', 'n/a')})")
except Exception as e:
logger.error(f"[Mailer] Failed to send welcome email: {e}")
async def send_grievance_email(to_email: str, pdf_path: str, cc_email: str = None):
"""Send the generated grievance PDF to the user and optionally CC the insurer."""
if not RESEND_API_KEY:
logger.info(f"[Mailer Mock] Grievance email → {to_email} (attachment: {pdf_path})")
return
try:
# Read and encode the PDF attachment
attachments = []
if os.path.exists(pdf_path):
with open(pdf_path, "rb") as f:
pdf_data = f.read()
attachments.append({
"filename": os.path.basename(pdf_path),
"content": list(pdf_data),
})
params: resend.Emails.SendParams = {
"from": MAIL_FROM,
"to": [cc_email] if cc_email else [to_email],
"subject": "PolicyEye Grievance Report 📋",
"html": _build_grievance_html(),
"headers": {
"X-Entity-Ref-ID": f"grievance-{to_email}",
},
"tags": [
{"name": "category", "value": "grievance"},
{"name": "app", "value": "policyeye"},
],
}
# The user's email becomes the CC, and the officer is the TO.
if cc_email:
params["cc"] = [to_email]
if attachments:
params["attachments"] = attachments
email_resp = resend.Emails.send(params)
logger.info(f"[Mailer] Grievance package sent to {cc_email or to_email} (id: {email_resp.get('id', 'n/a')})")
except Exception as e:
logger.error(f"[Mailer] Failed to send grievance package: {e}")
async def send_thank_you_email(to_email: str):
"""Send a thank you email for submitting app feedback."""
if not RESEND_API_KEY:
logger.info(f"[Mailer Mock] Thank you email → {to_email}")
return
try:
params: resend.Emails.SendParams = {
"from": MAIL_FROM,
"to": [to_email],
"subject": "Thank you for your feedback! 🙏",
"html": _build_thank_you_html(),
"tags": [
{"name": "category", "value": "feedback"},
],
}
resend.Emails.send(params)
except Exception as e:
logger.error(f"[Mailer] Failed to send thank you email: {e}")