{title}
{safe_message}
{action_button} {f'{footer_note}
' if footer_note else ''}""" Email Utility for Resend integration. Uses Resend for real-time delivery with a local forensic log fallback. """ import aiofiles import os import asyncio import resend from datetime import datetime from core.logging import get_logger from core.config import get_settings logger = get_logger(__name__) async def send_email(to_email: str, subject: str, body: str, html_body: str = None): """ Asynchronous email delivery using Resend. Always logs the payload to /logs/emails.log for forensic verification. """ settings = get_settings() log_dir = settings.effective_log_dir log_file = os.path.join(log_dir, "emails.log") if not os.path.exists(log_dir): os.makedirs(log_dir) html_log_part = f"BODY (HTML):\n{html_body}" if html_body else "" email_payload = f""" {"="*60} {"[LIVE]" if settings.RESEND_API_KEY else "[SIMULATED]"} TIMESTAMP: {datetime.utcnow().isoformat()} TO: {to_email} SUBJECT: {subject} BODY (TEXT): {body} {html_log_part} {"="*60} """ # 1. Forensic Logging (Always) try: async with aiofiles.open(log_file, mode="a", encoding="utf-8") as f: await f.write(email_payload) except Exception as e: logger.error(f"Failed to write to email forensic log: {str(e)}") # 2. Resend Delivery (Conditional) if not settings.RESEND_API_KEY: logger.info(f"SIMULATED EMAIL SENT TO: {to_email} | SUBJECT: {subject} (No Resend API Key)") return True try: resend.api_key = settings.RESEND_API_KEY params = { "from": settings.RESEND_FROM_EMAIL, "to": [to_email], "subject": subject, "text": body, } if html_body: params["html"] = html_body # Native thread-pool handoff (avoids deprecated get_event_loop) response = await asyncio.to_thread(resend.Emails.send, params) logger.info(f"RESEND EMAIL SENT TO: {to_email} | ID: {response.get('id', 'N/A')}") return True except Exception as e: logger.error(f"FAILED TO SEND RESEND EMAIL: {str(e)}") # We already have the forensic log as fallback return False def template_nexus_email(title: str, message: str, action_link: str = None, action_label: str = None, footer_note: str = None) -> str: """Returns a highly professional HTML template for Nexus emails.""" settings = get_settings() logo_url = settings.APP_LOGO_URL bg_color = "#0F172A" # Dark Navy (Nexus Theme) brand_color = "#6366F1" # Indigo 500 action_button = "" if action_link and action_label: action_button = f'''
''' safe_message = message.replace('\n', '{safe_message}
{action_button} {f'{footer_note}
' if footer_note else ''}