#!/usr/bin/env python3 """ Simple SMTP email sender for echo@romfast.ro Usage: python3 email_send.py "recipient@email.com" "Subject" "Body text" """ import smtplib import ssl import sys import os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from email.utils import formataddr from pathlib import Path # Try keyring first, fall back to .env sys.path.insert(0, str(Path(__file__).parent.parent)) try: from src.credential_store import get_secret except ImportError: get_secret = lambda name: None def _get(keyring_name, env_name, default=''): """Get credential from keyring first, then env, then default.""" val = get_secret(keyring_name) if val: return val return os.environ.get(env_name, default) # Load .env file as fallback env_path = Path(__file__).parent.parent / '.env' if env_path.exists(): with open(env_path) as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, value = line.split('=', 1) os.environ.setdefault(key, value) # SMTP Configuration: keyring → env → defaults # Try Gmail first, fall back to romfast gmail_pass = _get('gmail_password', 'GMAIL_PASSWORD') if gmail_pass: SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 465 SMTP_USER = _get('gmail_user', 'GMAIL_USER', 'mmarius28@gmail.com') SMTP_PASS = gmail_pass else: SMTP_SERVER = _get('email_server', 'EMAIL_SERVER', 'mail.romfast.ro') SMTP_PORT = 465 SMTP_USER = _get('email_user', 'EMAIL_USER', 'echo@romfast.ro') SMTP_PASS = _get('email_password', 'EMAIL_PASSWORD') FROM_NAME = "Echo" def send_email(to_email: str, subject: str, body: str, html: bool = False) -> dict: """Send an email via SMTP SSL""" try: # Create message msg = MIMEMultipart("alternative") msg["Subject"] = Header(subject, 'utf-8') msg["From"] = formataddr((FROM_NAME, SMTP_USER)) msg["To"] = to_email msg["Reply-To"] = "echo@romfast.ro" # Attach body if html: msg.attach(MIMEText(body, "html", "utf-8")) else: msg.attach(MIMEText(body, "plain", "utf-8")) # Connect and send context = ssl.create_default_context() with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=context) as server: server.login(SMTP_USER, SMTP_PASS) server.sendmail(SMTP_USER, to_email, msg.as_string()) return {"ok": True, "to": to_email, "subject": subject} except Exception as e: return {"ok": False, "error": str(e)} if __name__ == "__main__": if len(sys.argv) < 4: print("Usage: python3 email_send.py [--html]") sys.exit(1) to = sys.argv[1] subject = sys.argv[2] body = sys.argv[3] # Auto-detect HTML or use --html flag # Check for common HTML patterns, not just doctype/html tags body_lower = body.strip().lower() has_html_tags = any(tag in body_lower for tag in ['', '