"""Email delivery tool — send files as attachments via Gmail SMTP.""" from __future__ import annotations import logging from pathlib import Path from ..docx_export import text_to_docx from ..email import EmailClient from . import tool log = logging.getLogger(__name__) @tool( "email_file", description=( "Email a file as an attachment. If the file is .txt it is auto-converted " "to .docx before sending. Defaults to the configured recipient address." ), category="delivery", ) def email_file( file_path: str, to: str = "", subject: str = "", ctx: dict | None = None, ) -> str: """Send a file by email, auto-converting .txt to .docx.""" if not ctx or "config" not in ctx: return "Error: email tool requires agent context." email_cfg = ctx["config"].email if not email_cfg.enabled: return "Error: email not configured. Set GMAIL_USERNAME and GMAIL_APP_PASSWORD in .env." src = Path(file_path) if not src.exists(): return f"Error: file not found: {file_path}" # Auto-convert .txt → .docx if src.suffix.lower() == ".txt": docx_path = src.with_suffix(".docx") text_to_docx(src.read_text(encoding="utf-8"), docx_path) attachment = docx_path else: attachment = src recipient = to or email_cfg.default_to if not recipient: return "Error: no recipient specified and EMAIL_DEFAULT_TO not set." mail_subject = subject or f"CheddahBot: {attachment.stem}" client = EmailClient( smtp_host=email_cfg.smtp_host, smtp_port=email_cfg.smtp_port, username=email_cfg.username, password=email_cfg.password, ) try: client.send( to=recipient, subject=mail_subject, body=f"Attached: {attachment.name}", attachments=[attachment], ) except Exception as e: log.error("Email send failed: %s", e) return f"Error sending email: {e}" return f"Sent {attachment.name} to {recipient}."