import os import requests from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY") EMAIL_TO = os.getenv("EMAIL_TO") def _get_user_ip(): try: return requests.get("https://api.ipify.org", timeout=5).text except requests.RequestException: return "Unavailable" def _get_geo_from_ip(ip): try: response = requests.get(f"http://ip-api.com/json/{ip}", timeout=5) data = response.json() if data["status"] == "success": return { "city": data.get("city", "Unknown"), "region": data.get("regionName", "Unknown"), "country": data.get("country", "Unknown"), "error": "" } else: return {"error": "Lookup failed"} except Exception as e: return {"error": str(e)} def send_email_notification(user_message): if not SENDGRID_API_KEY or not EMAIL_TO: print("[Notifier] Missing SendGrid credentials.") return ip_address = _get_user_ip() geo_info = _get_geo_from_ip(ip_address) if geo_info.get("error"): location_str = f"IP: {ip_address} (location unavailable)" else: location_str = f"{geo_info['city']}, {geo_info['region']}, {geo_info['country']} (IP: {ip_address})" print("[Notifier] Sending email via SendGrid SDK...") html_content = f""" Someone interacted with RezAi!

Message:
{user_message}

Location:
{location_str} """ message = Mail( from_email=EMAIL_TO, to_emails=EMAIL_TO, subject="RezAi Interaction", html_content=html_content ) try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) if response.status_code == 202: print("[Notifier] ✅ Email sent successfully!") else: print(f"[Notifier] ❌ SendGrid SDK failed: {response.status_code} – {response.body}") except Exception as e: print(f"[Notifier] ❌ Exception: {e}")