{"id":"6368b0ef-ccff-4297-aed8-1c71187359df","entityType":"agent","slug":"clawhub-briansmith80-zoho-email-integration","name":"Zoho Email Integration","canonicalUrl":"https://www.xpersona.co/agent/clawhub-briansmith80-zoho-email-integration","canonicalPath":"/agent/clawhub-briansmith80-zoho-email-integration","generatedAt":"2026-10-09T18:31:06.479Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-09T10:07:38.187Z","emptyReason":null},"description":"Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-harde... Skill: Zoho Email Integration Owner: briansmith80 Summary: Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-harde... Tags: latest:2.2.9, security-fix:2.2.7 Version history: v2.2.9 | 2026-02-27T11:10:56.598Z | user Docs: Fix clawhub/clawdhub naming inconsistencies — correct CLI name, slug, badge URL, and version refe","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 3K downloads reported by the source. Last updated 10/9/2026.","installCommand":"clawhub skill install s17ba8phpw0znq9w0nsfn6870s884whw:zoho-email-integration","sourceUrl":"https://clawhub.ai/briansmith80/zoho-email-integration","homepage":"https://clawhub.ai/briansmith80/skills/zoho-email-integration","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/briansmith80/zoho-email-integration","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/briansmith80/skills/zoho-email-integration","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":70,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-harde..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-09T10:07:38.187Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T10:07:38.187Z","emptyReason":null},"stars":null,"forks":null,"downloads":3037,"packageName":null,"latestVersion":"2.2.9","tractionLabel":"3K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T10:07:38.187Z","emptyReason":null},"lastUpdatedAt":"2026-10-09T10:07:38.187Z","lastCrawledAt":"2026-10-09T10:07:38.187Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-10T10:07:38.187Z","lastVerifiedAt":null,"highlights":[{"version":"2.2.9","createdAt":"2026-02-27T11:10:56.598Z","changelog":"Docs: Fix clawhub/clawdhub naming inconsistencies — correct CLI name, slug, badge URL, and version references throughout README and SKILL.md","fileCount":33,"zipByteSize":93474},{"version":"2.2.8","createdAt":"2026-02-27T10:58:45.869Z","changelog":"Fix: Correct UnicodeDecodeError patch for Zoho JP regional IMAP servers — override open() instead of unbound standalone function","fileCount":33,"zipByteSize":93472},{"version":"2.2.7","createdAt":"2026-02-18T09:13:33.733Z","changelog":"Version bump to resolve VirusTotal pending scan. Security hardened: fixed path traversal and command injection vulnerabilities, OAuth2 support, REST API backend (5-10x faster than IMAP)","fileCount":33,"zipByteSize":92326},{"version":"2.2.6","createdAt":"2026-02-14T07:26:11.137Z","changelog":"Added update command and security notice to top of SKILL.md","fileCount":33,"zipByteSize":92325},{"version":"2.2.5","createdAt":"2026-02-14T07:23:29.044Z","changelog":"CRITICAL SECURITY FIX: Removed vulnerable email-command.js. Secure version using spawn with argument arrays is now the default.","fileCount":33,"zipByteSize":92049},{"version":"2.2.4","createdAt":"2026-02-12T17:39:57.387Z","changelog":"- Updated metadata fields in SKILL.md: added `ZOHO_PASSWORD` to required environment variables. - Changed metadata field names for consistency: `credentials` → `primaryEnv` and `token_file` → `tokenFile`. - No feature or command changes; documentation and metadata improvements only.","fileCount":34,"zipByteSize":94205},{"version":"2.2.3","createdAt":"2026-02-12T17:18:59.463Z","changelog":"- Added metadata section with requirements and credential details for Openclaw compatibility. - Specified required binaries (`python3`) and environment variables (`ZOHO_EMAIL`). - Documented OAuth2 as the primary authentication method, with app password as alternatives. - Noted the default token file location for OAuth2 (`~/.clawdbot/zoho-mail-tokens.json`).","fileCount":34,"zipByteSize":94223},{"version":"2.2.2","createdAt":"2026-02-12T17:12:44.051Z","changelog":"- Skill renamed from \"zoho-email\" to \"zoho-email-integration\". - Security improvements: hardened against path traversal and command injection. - Documentation updated to reflect new name and enhanced security. - Minor file and metadata adjustments for clarity and safety.","fileCount":34,"zipByteSize":94136}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17ba8phpw0znq9w0nsfn6870s884whw:zoho-email-integration","setupComplexity":"low","setupSteps":["Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T18:31:06.475Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-briansmith80-zoho-email-integration/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-09T10:07:38.187Z","emptyReason":null},"readme":"Skill: Zoho Email Integration\n\nOwner: briansmith80\n\nSummary: Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-harde...\n\nTags: latest:2.2.9, security-fix:2.2.7\n\nVersion history:\n\nv2.2.9 | 2026-02-27T11:10:56.598Z | user\n\nDocs: Fix clawhub/clawdhub naming inconsistencies — correct CLI name, slug, badge URL, and version references throughout README and SKILL.md\n\nv2.2.8 | 2026-02-27T10:58:45.869Z | user\n\nFix: Correct UnicodeDecodeError patch for Zoho JP regional IMAP servers — override open() instead of unbound standalone function\n\nv2.2.7 | 2026-02-18T09:13:33.733Z | user\n\nVersion bump to resolve VirusTotal pending scan. Security hardened: fixed path traversal and command injection vulnerabilities, OAuth2 support, REST API backend (5-10x faster than IMAP)\n\nv2.2.6 | 2026-02-14T07:26:11.137Z | user\n\nAdded update command and security notice to top of SKILL.md\n\nv2.2.5 | 2026-02-14T07:23:29.044Z | user\n\nCRITICAL SECURITY FIX: Removed vulnerable email-command.js. Secure version using spawn with argument arrays is now the default.\n\nv2.2.4 | 2026-02-12T17:39:57.387Z | auto\n\n- Updated metadata fields in SKILL.md: added `ZOHO_PASSWORD` to required environment variables.\n- Changed metadata field names for consistency: `credentials` → `primaryEnv` and `token_file` → `tokenFile`.\n- No feature or command changes; documentation and metadata improvements only.\n\nv2.2.3 | 2026-02-12T17:18:59.463Z | auto\n\n- Added metadata section with requirements and credential details for Openclaw compatibility.\n- Specified required binaries (`python3`) and environment variables (`ZOHO_EMAIL`).\n- Documented OAuth2 as the primary authentication method, with app password as alternatives.\n- Noted the default token file location for OAuth2 (`~/.clawdbot/zoho-mail-tokens.json`).\n\nv2.2.2 | 2026-02-12T17:12:44.051Z | auto\n\n- Skill renamed from \"zoho-email\" to \"zoho-email-integration\".\n- Security improvements: hardened against path traversal and command injection.\n- Documentation updated to reflect new name and enhanced security.\n- Minor file and metadata adjustments for clarity and safety.\n\nv2.2.1 | 2026-02-12T16:47:54.737Z | user\n\nSECURITY UPDATE: Fixed critical command injection vulnerability, added input validation, enforced token permissions. Upgrade recommended for all users. See SECURITY.md for details.\n\nv2.2.0 | 2026-02-12T16:47:22.809Z | auto\n\n- Added SECURITY.md and SECURITY-AUDIT-SUMMARY.md for improved security documentation.\n- Included a secure Clawdbot email command example: examples/clawdbot-extension/email-command-SECURE.js.\n- Updated CHANGELOG.md and README.md to reflect recent enhancements and best practices.\n\nv2.1.0 | 2026-02-06T10:44:10.096Z | user\n\nv2.1.0: Added Clawdbot extension with /email commands for Telegram/Discord\n\nv2.0.6 | 2026-02-01T13:11:52.500Z | user\n\nUpdated to v2.0.6\n\nv2.0.2 | 2026-01-29T17:08:13.723Z | user\n\nUpdated SKILL.md intro to highlight v2.0 features: OAuth2, REST API (5-10x faster), HTML emails, batch operations\n\nv2.0.1 | 2026-01-29T17:05:45.259Z | user\n\nUpdated roadmap to reflect all completed v2.0.0 features\n\nv2.0.0 | 2026-01-29T16:57:41.764Z | auto\n\nMajor upgrade delivering full Zoho API, OAuth2, HTML email support, and much faster performance.\n\n- Adds REST API and OAuth2 support for secure, robust integration (up to 10x faster).\n- Supports full HTML email sending with CSS, embedded templates, and preview mode.\n- Enables batch operations, CC/BCC, searching, attachment handling, and folder access.\n- CLI and Python API both improved and expanded for automation workflows.\n- Much simpler setup: no Zoho API setup needed, just app-specific password.\n- Extensive documentation with usage examples, templates, and workflow automation.\n\nArchive index:\n\nArchive v2.2.9: 33 files, 93474 bytes\n\nFiles: CHANGELOG.md (21410b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command.js (10065b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9745b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (98123b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (18631b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nFile v2.2.9:SKILL.md\n\n---\nname: zoho-email-integration\ndescription: Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-hardened against path traversal and command injection. Perfect for email automation and workflows.\nhomepage: https://github.com/briansmith80/clawdbot-zoho-email\nmetadata:\n  openclaw:\n    requires:\n      bins:\n        - python3\n      env:\n        - ZOHO_EMAIL\n        - ZOHO_PASSWORD\n    primaryEnv: ZOHO_EMAIL\n    tokenFile: \"~/.clawdbot/zoho-mail-tokens.json\"\n---\n\n# Zoho Email Integration\n\n**v2.2.8** - Complete Zoho Mail integration with OAuth2 authentication, REST API backend (5-10x faster than IMAP/SMTP), and **Clawdbot extension with /email commands for Telegram/Discord**. **Security-hardened** against path traversal and command injection. Supports HTML emails, attachments, batch operations, and advanced automation workflows.\n\nChoose your authentication: OAuth2 (recommended, secure) or app password (simple setup).\n\n## 🔄 Update to Latest Version\n\n```bash\nclawhub install zoho-email-integration --force\n```\n\nOr update all skills:\n```bash\nclawhub update\n```\n\n## 🔒 Security Notice (v2.2.5+)\n\n**CRITICAL FIX:** Removed vulnerable JavaScript command handler. If you deployed `email-command.js` from the examples folder, update immediately:\n\n```bash\n# Re-download the secure handler\nclawhub install zoho-email-integration --force\ncp ~/.openclaw/skills/zoho-email-integration/examples/clawdbot-extension/email-command.js /your/deployment/path/\n```\n\nThe vulnerable version used `execSync` with shell interpolation. The new version uses `spawn` with argument arrays to prevent command injection.\n\n## ✨ Features\n\n### 🔐 Authentication & Performance\n- **OAuth2 authentication** - Secure token-based auth with automatic refresh\n- **REST API backend** - 5-10x faster operations than IMAP/SMTP\n- **Graceful fallback** - Automatically falls back to IMAP if REST API unavailable\n- **App password support** - Simple alternative to OAuth2\n\n### 📧 Email Operations\n- **📥 Read emails** - Fetch from any folder (Inbox, Sent, Drafts, etc.)\n- **🔍 Smart search** - Search by subject, sender, keywords with REST API speed\n- **📊 Monitor inbox** - Real-time unread count for notifications\n- **📤 Send emails** - Plain text or HTML with CC/BCC support\n- **🎨 HTML emails** - Rich formatting with professional templates included\n- **📎 Attachments** - Send and download file attachments\n\n### ⚡ Batch & Bulk Operations\n- **Batch operations** - Mark, delete, or move multiple emails efficiently\n- **Bulk actions** - Search and act on hundreds of emails at once\n- **Dry-run mode** - Preview actions before executing for safety\n\n### 🔒 Security\n- **No hardcoded credentials** - OAuth2 tokens or environment variables only\n- **Automatic token refresh** - Seamless token renewal\n- **Encrypted connections** - SSL/TLS for all operations\n\n## 📦 Installation\n\n```bash\nclawhub install zoho-email-integration\n```\n\n**Requirements:**\n- Python 3.x\n- `requests` library (install: `pip3 install requests`)\n- Zoho Mail account\n\n## ⚙️ Setup\n\n### 1. Get an App-Specific Password\n\n**Important:** Don't use your main Zoho password!\n\n1. Log in to Zoho Mail\n2. Go to **Settings** → **Security** → **App Passwords**\n3. Generate a new app password for \"Clawdbot\" or \"IMAP/SMTP Access\"\n4. Copy the password (you'll need it next)\n\n### 2. Configure Credentials\n\n**Option A: Environment Variables**\n\nExport your Zoho credentials:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\"\n```\n\n**Option B: Credentials File**\n\nCreate `~/.clawdbot/zoho-credentials.sh`:\n\n```bash\n#!/bin/bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\"\n```\n\nMake it executable and secure:\n```bash\nchmod 600 ~/.clawdbot/zoho-credentials.sh\n```\n\nThen source it before running:\n```bash\nsource ~/.clawdbot/zoho-credentials.sh\n```\n\n### 3. Test Connection\n\n```bash\npython3 scripts/zoho-email.py unread\n```\n\nExpected output:\n```json\n{\"unread_count\": 5}\n```\n\n## 🚀 Usage\n\nAll commands require credentials set via environment variables.\n\n### Quick commands (common tasks)\n\n```bash\n# Diagnose setup (recommended first step)\npython3 scripts/zoho-email.py doctor\n\n# Unread count (great for briefings)\npython3 scripts/zoho-email.py unread\n\n# Search inbox\npython3 scripts/zoho-email.py search \"invoice\"\n\n# Get a specific email (folder + id)\npython3 scripts/zoho-email.py get INBOX <id>\n\n# Send a simple email\npython3 scripts/zoho-email.py send recipient@example.com \"Subject\" \"Body text\"\n\n# Empty Spam (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-spam\n# Execute for real\npython3 scripts/zoho-email.py empty-spam --execute\n\n# Empty Trash (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-trash\n# Execute for real\npython3 scripts/zoho-email.py empty-trash --execute\n```\n\n### Send HTML Emails\n\nSend rich, formatted HTML emails with multipart/alternative support (both HTML and plain text versions):\n\n**CLI Command:**\n```bash\n# Send HTML from a file\npython3 scripts/zoho-email.py send-html recipient@example.com \"Newsletter\" examples/templates/newsletter.html\n\n# Send HTML from inline text\npython3 scripts/zoho-email.py send-html recipient@example.com \"Welcome\" \"<h1>Hello!</h1><p>Welcome to our service.</p>\"\n\n# Preview HTML email before sending\npython3 scripts/zoho-email.py preview-html examples/templates/newsletter.html\n```\n\n**Python API:**\n```python\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Method 1: Send HTML with auto-generated plain text fallback\nzoho.send_html_email(\n    to=\"recipient@example.com\",\n    subject=\"Newsletter\",\n    html_body=\"<h1>Hello!</h1><p>Welcome!</p>\"\n)\n\n# Method 2: Send HTML with custom plain text version\nzoho.send_email(\n    to=\"recipient@example.com\",\n    subject=\"Newsletter\",\n    body=\"Plain text version of your email\",\n    html_body=\"<h1>Hello!</h1><p>HTML version of your email</p>\"\n)\n\n# Load HTML from template file\nwith open('examples/templates/newsletter.html', 'r') as f:\n    html_content = f.read()\n\nzoho.send_html_email(\n    to=\"recipient@example.com\",\n    subject=\"Monthly Newsletter\",\n    html_body=html_content\n)\n```\n\n**Features:**\n- ✅ Multipart/alternative emails (HTML + plain text)\n- ✅ Auto-generated plain text fallback\n- ✅ Load HTML from files or inline strings\n- ✅ Preview mode to test before sending\n- ✅ Full CSS styling support\n- ✅ Works with all email clients\n\n**Templates:**\nPre-built templates available in `examples/templates/`:\n- `newsletter.html` - Professional newsletter layout\n- `announcement.html` - Important announcements with banners\n- `welcome.html` - Onboarding welcome email\n- `simple.html` - Basic HTML template for quick customization\n\n### Check Unread Count\n\n```bash\npython3 scripts/zoho-email.py unread\n```\n\nPerfect for morning briefings or notification systems.\n\n### Search Inbox\n\n```bash\npython3 scripts/zoho-email.py search \"invoice\"\n```\n\nReturns last 10 matching emails with subject, sender, date, and body preview.\n\n### Search Sent Emails\n\n```bash\npython3 scripts/zoho-email.py search-sent \"client name\"\n```\n\nReturns last 5 matching sent emails.\n\n### Get Specific Email\n\n```bash\npython3 scripts/zoho-email.py get Inbox 4590\npython3 scripts/zoho-email.py get Sent 1234\n```\n\nReturns full email content including complete body.\n\n### Send Email\n\n```bash\npython3 scripts/zoho-email.py send \"client@example.com\" \"Subject\" \"Email body here\"\n```\n\n### Send Email with Attachments\n\n```bash\npython3 scripts/zoho-email.py send \"client@example.com\" \"Invoice\" \"Please find the invoice attached\" --attach invoice.pdf --attach receipt.jpg\n```\n\nSupports multiple attachments with `--attach` flag.\n\n### List Email Attachments\n\n```bash\npython3 scripts/zoho-email.py list-attachments Inbox 4590\n```\n\nReturns JSON with attachment details:\n```json\n[\n  {\n    \"index\": 0,\n    \"filename\": \"invoice.pdf\",\n    \"content_type\": \"application/pdf\",\n    \"size\": 52341\n  },\n  {\n    \"index\": 1,\n    \"filename\": \"receipt.jpg\",\n    \"content_type\": \"image/jpeg\",\n    \"size\": 128973\n  }\n]\n```\n\n### Download Attachment\n\n```bash\n# Download first attachment (index 0) with original filename\npython3 scripts/zoho-email.py download-attachment Inbox 4590 0\n\n# Download second attachment (index 1) with custom filename\npython3 scripts/zoho-email.py download-attachment Inbox 4590 1 my-receipt.jpg\n```\n\nReturns JSON with download details:\n```json\n{\n  \"filename\": \"invoice.pdf\",\n  \"output_path\": \"invoice.pdf\",\n  \"size\": 52341,\n  \"content_type\": \"application/pdf\"\n}\n```\n\n## 🤖 Clawdbot Integration Examples\n\n### Morning Briefing\n\nCheck unread emails and report:\n\n```bash\nUNREAD=$(python3 scripts/zoho-email.py unread | jq -r '.unread_count')\necho \"📧 You have $UNREAD unread emails\"\n```\n\n### Email Monitoring\n\nWatch for VIP emails:\n\n```bash\nRESULTS=$(python3 scripts/zoho-email.py search \"Important Client\")\nCOUNT=$(echo \"$RESULTS\" | jq '. | length')\n\nif [ $COUNT -gt 0 ]; then\n  echo \"⚠️ New email from Important Client!\"\nfi\n```\n\n### Automated Responses\n\nSearch and reply workflow:\n\n```bash\n# Find latest invoice inquiry\nEMAIL=$(python3 scripts/zoho-email.py search \"invoice\" | jq -r '.[0]')\nFROM=$(echo \"$EMAIL\" | jq -r '.from')\n\n# Send reply\npython3 scripts/zoho-email.py send \"$FROM\" \"Re: Invoice\" \"Thanks for your inquiry...\"\n```\n\n### Attachment Workflows\n\nDownload invoice attachments automatically:\n\n```bash\n# Search for invoice emails\nEMAILS=$(python3 scripts/zoho-email.py search \"invoice\")\n\n# Get latest email ID\nEMAIL_ID=$(echo \"$EMAILS\" | jq -r '.[0].id')\n\n# List attachments\nATTACHMENTS=$(python3 scripts/zoho-email.py list-attachments Inbox \"$EMAIL_ID\")\n\n# Download all PDF attachments\necho \"$ATTACHMENTS\" | jq -r '.[] | select(.content_type == \"application/pdf\") | .index' | while read INDEX; do\n  python3 scripts/zoho-email.py download-attachment Inbox \"$EMAIL_ID\" \"$INDEX\" \"invoice_${INDEX}.pdf\"\n  echo \"Downloaded invoice_${INDEX}.pdf\"\ndone\n```\n\nSend report with attachments:\n\n```bash\n# Generate report\npython3 generate_report.py > report.txt\n\n# Send with attachment\npython3 scripts/zoho-email.py send \"manager@example.com\" \"Weekly Report\" \"Please see attached report\" --attach report.txt --attach chart.png\n```\n\n## 📚 Python API\n\nImport the module for programmatic use:\n\n```python\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Search emails\nresults = zoho.search_emails(folder=\"INBOX\", query='SUBJECT \"invoice\"', limit=10)\n\n# Get specific email\nemail = zoho.get_email(folder=\"Sent\", email_id=\"4590\")\n\n# Send plain text email\nzoho.send_email(\n    to=\"client@example.com\",\n    subject=\"Hello\",\n    body=\"Message text\",\n    cc=\"manager@example.com\"  # optional\n)\n\n# Send HTML email (auto-generated plain text fallback)\nzoho.send_html_email(\n    to=\"client@example.com\",\n    subject=\"Newsletter\",\n    html_body=\"<h1>Welcome!</h1><p>Rich HTML content here</p>\",\n    text_body=\"Welcome! Plain text version here\"  # optional, auto-generated if not provided\n)\n\n# Send multipart email (HTML + custom plain text)\nzoho.send_email(\n    to=\"client@example.com\",\n    subject=\"Update\",\n    body=\"Plain text version\",\n    html_body=\"<h1>HTML version</h1>\",\n    cc=\"manager@example.com\"\n)\n\n# Send email with attachments\nzoho.send_email_with_attachment(\n    to=\"client@example.com\",\n    subject=\"Invoice\",\n    body=\"Please find the invoice attached\",\n    attachments=[\"invoice.pdf\", \"receipt.jpg\"],\n    cc=\"manager@example.com\"  # optional\n)\n\n# List attachments\nattachments = zoho.get_attachments(folder=\"INBOX\", email_id=\"4590\")\nfor att in attachments:\n    print(f\"{att['index']}: {att['filename']} ({att['size']} bytes)\")\n\n# Download attachment\nresult = zoho.download_attachment(\n    folder=\"INBOX\",\n    email_id=\"4590\",\n    attachment_index=0,\n    output_path=\"downloaded_file.pdf\"  # optional, uses original filename if not provided\n)\n\n# Check unread count\ncount = zoho.get_unread_count()\n```\n\n## 📖 HTML Email Examples\n\nCheck out the complete example in `examples/send-html-newsletter.py`:\n\n```bash\n# Run the HTML email examples\npython3 examples/send-html-newsletter.py\n```\n\nThis demonstrates:\n- Sending simple inline HTML\n- Loading and sending HTML templates\n- Custom plain text fallbacks\n- Professional email layouts\n\n**Quick Start:**\n```python\n#!/usr/bin/env python3\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Load a template\nwith open('examples/templates/welcome.html', 'r') as f:\n    html = f.read()\n\n# Send to recipient\nzoho.send_html_email(\n    to=\"newuser@example.com\",\n    subject=\"🎉 Welcome to Our Platform!\",\n    html_body=html\n)\n```\n\n## 📁 Folder Reference\n\nCommon Zoho Mail folders:\n\n- `INBOX` - Main inbox\n- `Sent` - Sent emails\n- `Drafts` - Draft emails\n- `Spam` - Spam folder\n- `Trash` - Deleted emails\n- Custom folders (e.g., `INBOX/ClientName`)\n\n## 🔧 Advanced Configuration\n\nOverride default IMAP/SMTP servers (if using Zoho Mail self-hosted):\n\n```bash\nexport ZOHO_IMAP=\"imap.yourdomain.com\"\nexport ZOHO_SMTP=\"smtp.yourdomain.com\"\nexport ZOHO_IMAP_PORT=\"993\"\nexport ZOHO_SMTP_PORT=\"465\"\n```\n\n## ❓ Troubleshooting\n\n### Authentication Failed\n\n- Ensure IMAP is enabled in Zoho Mail settings\n- Use an **app-specific password**, not your main password\n- Verify credentials are properly exported\n\n### Connection Timeout\n\n- Check firewall allows port 993 (IMAP) and 465 (SMTP)\n- Verify Zoho Mail server status\n- Try with a different network (corporate firewalls may block IMAP)\n\n### Search Returns No Results\n\n- IMAP search is case-insensitive\n- Try broader keywords\n- Verify folder name is correct (case-sensitive)\n\n### \"ZOHO_EMAIL and ZOHO_PASSWORD must be set\"\n\nYou forgot to export credentials! Run:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-password\"\n```\n\n## 🛣️ Roadmap\n\n### ✅ Completed (v2.0.0)\n\n- [x] **OAuth2 authentication** - Secure token-based auth with auto-refresh\n- [x] **Zoho Mail REST API** - 5-10x faster than IMAP/SMTP\n- [x] **Attachment support** - Download and send attachments\n- [x] **HTML email composition** - Rich formatting with templates\n- [x] **Batch operations** - Mark, delete, move multiple emails\n- [x] **Bulk actions** - Search and act on many emails at once\n\n### 🔮 Future Enhancements\n\n- [ ] **Email threading/conversations** - Group related emails together\n- [ ] **Label management** - Create and manage Zoho Mail labels\n- [ ] **Draft email management** - Create, edit, and send drafts\n- [ ] **Scheduled sends** - Schedule emails to send later\n- [ ] **Email templates** - Reusable email templates with variables\n- [ ] **Webhooks** - Real-time notifications for new emails\n- [ ] **Advanced search** - Filter by size, has-attachment, date ranges\n- [ ] **Zoho Calendar integration** - Create events from emails\n- [ ] **Zoho CRM integration** - Sync contacts and activities\n\n## 📝 Notes\n\n- **Search limit:** Returns last 5-10 emails by default (configurable in code)\n- **Body truncation:** Search results show first 500 characters\n- **Encoding:** Handles UTF-8 and various email encodings\n- **Security:** Credentials never leave your system except to Zoho servers\n\n## 🤝 Contributing\n\nFound a bug or want to contribute? Submit issues or PRs on GitHub!\n\n## 📄 License\n\nMIT License - free to use, modify, and distribute.\n\n---\n\n**Created:** 2026-01-29  \n**Status:** Production-ready ✅  \n**Requires:** Python 3.x. For REST API mode: `pip install -r requirements.txt` (includes `requests`).\n\n## 🔄 Batch Operations\n\nNew in v1.1! Process multiple emails efficiently with batch commands.\n\n### Mark Multiple Emails as Read\n\n```bash\npython3 scripts/zoho-email.py mark-read INBOX 1001 1002 1003\n```\n\nMark several emails as read in one command. Perfect for clearing notifications.\n\n### Mark Multiple Emails as Unread\n\n```bash\npython3 scripts/zoho-email.py mark-unread INBOX 1004 1005\n```\n\nFlag important emails to revisit later.\n\n### Delete Multiple Emails\n\n```bash\npython3 scripts/zoho-email.py delete INBOX 2001 2002 2003\n```\n\n**Safety:** Asks for confirmation before deleting. Emails are moved to Trash (not permanently deleted).\n\n### Move Emails Between Folders\n\n```bash\npython3 scripts/zoho-email.py move INBOX \"Archive/2024\" 3001 3002 3003\n```\n\nOrganize emails by moving them to custom folders.\n\n### Bulk Actions with Search\n\nPerform actions on all emails matching a search query:\n\n```bash\n# Dry run first - see what would be affected\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action mark-read \\\n  --dry-run\n\n# Execute the action\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action mark-read\n```\n\n**Available actions:**\n- `mark-read` - Mark all matching emails as read\n- `mark-unread` - Mark all matching emails as unread\n- `delete` - Move all matching emails to Trash\n\n**Search query examples:**\n```bash\n# By subject\n--search 'SUBJECT \"invoice\"'\n\n# By sender\n--search 'FROM \"sender@example.com\"'\n\n# Unread emails\n--search 'UNSEEN'\n\n# Combine criteria (AND)\n--search '(SUBJECT \"urgent\" FROM \"boss@company.com\")'\n\n# Date range\n--search 'SINCE 01-Jan-2024'\n```\n\n### Batch Operations in Python\n\n```python\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Mark multiple emails as read\nresult = zoho.mark_as_read(['1001', '1002', '1003'], folder=\"INBOX\")\nprint(f\"Success: {len(result['success'])}, Failed: {len(result['failed'])}\")\n\n# Delete multiple emails\nresult = zoho.delete_emails(['2001', '2002'], folder=\"INBOX\")\n\n# Move emails to another folder\nresult = zoho.move_emails(\n    email_ids=['3001', '3002'],\n    target_folder=\"Archive/2024\",\n    source_folder=\"INBOX\"\n)\n\n# Bulk action with search\nresult = zoho.bulk_action(\n    query='SUBJECT \"newsletter\"',\n    action='mark-read',\n    folder=\"INBOX\",\n    dry_run=True  # Preview first\n)\n\nprint(f\"Found {result['total_found']} emails\")\nprint(f\"Will process {result['to_process']} emails\")\n\n# Execute for real\nresult = zoho.bulk_action(\n    query='SUBJECT \"newsletter\"',\n    action='mark-read',\n    folder=\"INBOX\",\n    dry_run=False\n)\n```\n\n### Batch Cleanup Example\n\nClean up old newsletters automatically:\n\n```bash\n# 1. Preview what will be deleted\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action delete \\\n  --dry-run\n\n# 2. Review the preview output\n\n# 3. Execute if satisfied\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action delete\n```\n\nSee `examples/batch-cleanup.py` for a complete automated cleanup script.\n\nFile v2.2.9:examples/templates/README.md\n\n# HTML Email Templates\n\nProfessional, ready-to-use HTML email templates for the Zoho Email skill.\n\n## Available Templates\n\n### 📰 newsletter.html\n**Best for:** Monthly updates, company news, content roundups\n\n**Features:**\n- Modern gradient header\n- Multiple article sections\n- Call-to-action buttons\n- Professional footer\n- Social media links\n\n**Use case:** Send monthly newsletters, product updates, or content digests to subscribers.\n\n### 📢 announcement.html\n**Best for:** Important notifications, system updates, maintenance alerts\n\n**Features:**\n- Bold banner design\n- Highlight boxes for key information\n- Multiple content sections\n- Professional corporate style\n- Clear visual hierarchy\n\n**Use case:** Announce system maintenance, policy changes, or important company news.\n\n### 🎉 welcome.html\n**Best for:** New user onboarding, welcome emails\n\n**Features:**\n- Friendly, welcoming design\n- Step-by-step getting started guide\n- Emoji support\n- Social media integration\n- Engaging call-to-action\n\n**Use case:** Welcome new users, guide them through setup, or introduce your service.\n\n### 📝 simple.html\n**Best for:** Quick, straightforward communications\n\n**Features:**\n- Clean, minimal design\n- Easy to customize\n- Professional signature\n- Good typography\n- Fast to load\n\n**Use case:** General-purpose template for any email, great starting point for custom designs.\n\n## How to Use\n\n### CLI Usage\n\n```bash\n# Send a template\npython3 scripts/zoho-email.py send-html recipient@example.com \"Subject\" examples/templates/newsletter.html\n\n# Preview before sending\npython3 scripts/zoho-email.py preview-html examples/templates/welcome.html\n```\n\n### Python Usage\n\n```python\nfrom scripts.zoho_email import ZohoEmail\n\n# Load template\nwith open('examples/templates/newsletter.html', 'r') as f:\n    html = f.read()\n\n# Send email\nzoho = ZohoEmail()\nzoho.send_html_email(\n    to=\"recipient@example.com\",\n    subject=\"Your Monthly Newsletter\",\n    html_body=html\n)\n```\n\n## Customization Tips\n\n### 1. Replace Placeholder Content\nAll templates contain example text. Simply edit the HTML to replace:\n- Titles and headings\n- Body text and descriptions\n- Links and URLs\n- Footer information\n\n### 2. Change Colors\nEach template uses CSS variables or direct color codes. Search for color codes like:\n- `#667eea` (primary purple)\n- `#764ba2` (secondary purple)\n- `#f5576c` (red accent)\n\nReplace with your brand colors.\n\n### 3. Add Your Logo\nReplace the emoji or text in the header with your logo:\n```html\n<img src=\"https://your-site.com/logo.png\" alt=\"Logo\" style=\"max-width: 200px;\">\n```\n\n### 4. Update Links\nReplace all `href=\"#\"` with actual URLs:\n```html\n<a href=\"https://your-site.com/pricing\">View Pricing</a>\n```\n\n### 5. Modify Layout\nEach template uses inline CSS and modern layout techniques. Feel free to:\n- Add/remove sections\n- Adjust padding and margins\n- Change font sizes\n- Modify button styles\n\n## Email Client Compatibility\n\nAll templates are designed with maximum compatibility:\n- ✅ Gmail (Web, Mobile, App)\n- ✅ Outlook (Desktop, Web, Mobile)\n- ✅ Apple Mail (macOS, iOS)\n- ✅ Yahoo Mail\n- ✅ Proton Mail\n- ✅ Other modern email clients\n\n**Features used:**\n- Inline CSS (best compatibility)\n- Table-based layouts where needed\n- Web-safe fonts with fallbacks\n- Tested color schemes\n- Mobile-responsive design\n\n## Best Practices\n\n### DO ✅\n- Keep HTML under 100KB for best deliverability\n- Use inline CSS instead of `<style>` tags when possible\n- Test with multiple email clients\n- Include plain text fallback (automatic with this skill)\n- Use web-safe fonts (Arial, Helvetica, Georgia, etc.)\n- Optimize images before including\n\n### DON'T ❌\n- Use JavaScript (not supported in emails)\n- Rely solely on external stylesheets\n- Use video or audio embeds\n- Include forms (limited support)\n- Use complex CSS animations\n- Forget to test on mobile devices\n\n## Creating Your Own Templates\n\nStart with `simple.html` and customize:\n\n1. **Copy the template:**\n   ```bash\n   cp examples/templates/simple.html examples/templates/my-template.html\n   ```\n\n2. **Edit the content:**\n   - Update title and headings\n   - Add your content sections\n   - Customize colors and styles\n\n3. **Test it:**\n   ```bash\n   python3 scripts/zoho-email.py preview-html examples/templates/my-template.html\n   ```\n\n4. **Send it:**\n   ```bash\n   python3 scripts/zoho-email.py send-html test@example.com \"Test\" examples/templates/my-template.html\n   ```\n\n## Template Structure\n\nAll templates follow this structure:\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Email Title</title>\n    <style>\n        /* Inline styles for compatibility */\n    </style>\n</head>\n<body>\n    <!-- Email content -->\n</body>\n</html>\n```\n\n## Resources\n\n- **Email on Acid:** Test rendering across clients\n- **Litmus:** Professional email testing\n- **Can I Email:** Check CSS support in email clients\n- **HTML Email Template Generator:** Create custom templates\n\n## Support\n\nFor questions or issues with templates:\n1. Check `SKILL.md` for general documentation\n2. Review `HTML_FEATURE.md` for implementation details\n3. Run preview mode to debug: `preview-html <template>`\n4. Check MIME structure with `--verbose` flag\n\n---\n\n**Templates Created:** January 29, 2026  \n**Compatible With:** Zoho Email Skill v1.0+  \n**License:** MIT (Free to use and customize)\n\nFile v2.2.9:README.md\n\n# Zoho Email Integration for Clawdbot\n\n[![GitHub](https://img.shields.io/badge/GitHub-clawdbot--zoho--email-blue?logo=github)](https://github.com/briansmith80/clawdbot-zoho-email)\n[![ClawHub](https://img.shields.io/badge/ClawHub-Install-green)](https://clawhub.com)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Version](https://img.shields.io/badge/version-2.2.9-blue)](https://github.com/briansmith80/clawdbot-zoho-email/releases)\n[![Security](https://img.shields.io/badge/security-hardened-brightgreen)](SECURITY.md)\n\n**v2.2.9** - Complete Zoho Mail integration with OAuth2, REST API backend (5-10x faster), **Clawdbot extension with /email commands**, and advanced email automation features. Perfect for email workflows, monitoring, and bulk operations in your Clawdbot projects.\n\n## 🔒 Security Notice (v2.2.0)\n\n**SECURITY UPDATE:** This version fixes critical vulnerabilities identified in security audit. **Upgrade recommended for all users.**\n\n**Fixed vulnerabilities:**\n- ✅ **CRITICAL:** Command injection in JavaScript handler\n- ✅ **HIGH:** Metadata mismatch (credential requirements)\n- ✅ **MEDIUM:** Insufficient input validation\n- ✅ **LOW:** Token file permission enforcement\n\n**See [SECURITY.md](SECURITY.md) for details and migration guide.**\n\n## 🚀 Quick Start (recommended path)\n\n```bash\n# 1) Install\nclawhub install zoho-email-integration\ncd zoho-email-integration  # (or wherever ClawHub installed it)\n\n# 2) Install Python deps (needed for REST API mode)\npip3 install -r requirements.txt\n\n# 3) Set your mailbox (required for both OAuth + app-password modes)\nexport ZOHO_EMAIL=\"your-email@domain.com\"\n\n# 4) OAuth2 setup (recommended: enables REST API + auto token refresh)\npython3 scripts/oauth-setup.py\n\n# 5) Sanity-check everything\npython3 scripts/zoho-email.py doctor\n\n# 6) Test\npython3 scripts/zoho-email.py unread\n```\n\n### Quick Start (app-password mode)\nIf you don't want OAuth2 yet:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\"\npython3 scripts/zoho-email.py doctor\npython3 scripts/zoho-email.py unread --api-mode imap\n```\n\n**OAuth token location (default):** `~/.clawdbot/zoho-mail-tokens.json`\n\n\n## ✨ Features\n\n### Core Features\n✅ **OAuth2 Authentication** - Secure authentication with automatic token refresh\n✅ **REST API Backend** - 5-10x faster than IMAP/SMTP (auto-enabled with OAuth2)\n✅ **Read & Search** - Search emails with advanced filters\n✅ **Send Emails** - Plain text, HTML, CC/BCC support\n✅ **Attachments** - Send and download attachments\n✅ **HTML Emails** - Send rich-formatted emails with templates\n✅ **Batch Operations** - Mark, delete, move multiple emails efficiently\n✅ **Folder Management** - Access all folders (Inbox, Sent, Drafts, etc.)\n\n### Performance\n⚡ **5-10x faster** operations with REST API mode\n⚡ **Connection pooling** for persistent HTTP connections\n⚡ **Server-side filtering** reduces data transfer\n⚡ **Automatic fallback** to IMAP if REST API unavailable\n\n## 📚 Documentation\n\n- **[SKILL.md](SKILL.md)** - Complete guide with examples\n- **[OAUTH2_SETUP.md](OAUTH2_SETUP.md)** - OAuth2 setup instructions\n- **[SECURITY.md](SECURITY.md)** - Security best practices and audit results\n- **[CHANGELOG.md](CHANGELOG.md)** - Version history\n\n## 🔒 Security & Best Practices\n\n**Credential Management:**\n- ✅ Use OAuth2 (recommended) or app-specific passwords only\n- ✅ Never use your main Zoho password\n- ✅ Token files automatically secured with 0600 permissions\n- ✅ Never commit credentials to version control\n\n**Command Handler Security (if exposing /email commands):**\n- ✅ Use `email-command-SECURE.js` (prevents command injection)\n- ✅ Restrict command access to authorized users only\n- ✅ Add rate limiting at bot level\n- ✅ Enable audit logging for sensitive operations\n\n**Verification:**\n```bash\n# Check token file permissions (should be 600)\nls -la ~/.clawdbot/zoho-mail-tokens.json\n\n# Fix if needed\nchmod 600 ~/.clawdbot/zoho-mail-tokens.json\n```\n\n**See [SECURITY.md](SECURITY.md) for complete security guide.**\n\n## 📖 Quick Examples\n\n### Most common Clawdbot-style actions\n```bash\n# Unread count (fast, good for briefings)\npython3 scripts/zoho-email.py unread\n\n# Search inbox\npython3 scripts/zoho-email.py search \"invoice\"\n\n# Read a specific email (folder + id)\npython3 scripts/zoho-email.py get INBOX <id>\n\n# Send a simple email\npython3 scripts/zoho-email.py send recipient@example.com \"Subject\" \"Body text\"\n\n# Empty Spam (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-spam\n# Execute for real\npython3 scripts/zoho-email.py empty-spam --execute\n\n# Empty Trash (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-trash\n# Execute for real\npython3 scripts/zoho-email.py empty-trash --execute\n```\n\n\n### Basic Operations\n```bash\n# Get unread count\npython3 scripts/zoho-email.py unread\n\n# Search emails\npython3 scripts/zoho-email.py search \"important meeting\"\n\n# Send email\npython3 scripts/zoho-email.py send recipient@example.com \"Subject\" \"Message body\"\n```\n\n### HTML Emails (v1.1.0+)\n```bash\n# Send HTML email from template\npython3 scripts/zoho-email.py send-html user@example.com \"Newsletter\" templates/newsletter.html\n\n# Preview HTML before sending\npython3 scripts/zoho-email.py preview-html templates/welcome.html\n```\n\n### Attachments (v1.1.0+)\n```bash\n# Send with attachments\npython3 scripts/zoho-email.py send user@example.com \"Report\" \"See attached\" --attach report.pdf --attach data.xlsx\n\n# List attachments in an email\npython3 scripts/zoho-email.py list-attachments Inbox 4590\n\n# Download attachment\npython3 scripts/zoho-email.py download-attachment Inbox 4590 0 ./report.pdf\n```\n\n### Batch Operations (v1.1.0+)\n```bash\n# Mark multiple emails as read\npython3 scripts/zoho-email.py mark-read INBOX 1001 1002 1003\n\n# Delete multiple emails (with confirmation)\npython3 scripts/zoho-email.py delete INBOX 2001 2002 2003\n\n# Move emails to folder\npython3 scripts/zoho-email.py move INBOX \"Archive/2024\" 3001 3002\n\n# Bulk action with search\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action mark-read \\\n  --dry-run\n```\n\n### OAuth2 & REST API (v1.2.0+, v2.0.0+)\n```bash\n# Set up OAuth2 (one-time)\npython3 scripts/oauth-setup.py\n\n# Check OAuth2 status\npython3 scripts/zoho-email.py oauth-status\n\n# Force REST API mode (5-10x faster)\npython3 scripts/zoho-email.py unread --api-mode rest --verbose\n\n# Force IMAP mode (compatibility)\npython3 scripts/zoho-email.py unread --api-mode imap\n```\n\n## 🧩 Clawdbot Integration (NEW!)\n\n### /email Commands (Telegram, Discord, etc.)\n\nUse email directly in Clawdbot messaging platforms via `/email` commands:\n\n```bash\n# Check unread count\n/email unread\n\n# Search your inbox\n/email search invoice\n\n# Send an email\n/email send john@example.com \"Hello\" \"Hi John\"\n\n# Brief summary (for briefings)\n/email summary\n\n# Diagnostics\n/email doctor\n\n# Get help\n/email help\n```\n\n**Setup:**\n1. Copy `examples/clawdbot-extension/clawdbot_extension.py` to your scripts directory\n2. Set `ZOHO_EMAIL` environment variable\n3. Run OAuth2 setup: `python3 scripts/oauth-setup.py`\n4. Test: `python3 scripts/clawdbot_extension.py unread`\n\n### Heartbeat/Cron Integration\n\nAdd email summary to morning briefings or scheduled tasks:\n\n```bash\n# In your heartbeat/cron script\npython3 scripts/clawdbot_extension.py summary\n\n# Output: 📭 No unread emails\n#     OR: 📧 3 unread emails\n```\n\n**Examples:**\n- `examples/clawdbot-extension/heartbeat-example.md` - Complete integration guide\n- `examples/clawdbot-commands/emails.sh` - Simple wrapper script\n\n### Use Cases\n✅ **Morning briefings** - Add email summary to daily briefing  \n✅ **Slack/Discord alerts** - Notify on unread emails  \n✅ **Interactive commands** - `/email search invoice` in chat  \n✅ **Automated workflows** - Cron + Clawdbot integration\n\n## 💡 Use Cases\n\n- **Morning briefings** - Automated unread email summaries\n- **Email monitoring** - Watch for VIP senders or keywords\n- **Newsletter cleanup** - Bulk-mark newsletters as read\n- **Automated responses** - Search and reply to specific emails\n- **Email archiving** - Move old emails to archive folders\n- **Notifications** - Alert when important emails arrive\n- **HTML campaigns** - Send rich-formatted newsletters\n- **Attachment workflows** - Download invoices, reports automatically\n\n## 🔧 Requirements\n\n**Minimum:**\n- Python 3.x\n- Zoho Mail account\n- App-specific password OR OAuth2 setup\n\n**Optional (for REST API mode):**\n- `requests>=2.31.0` (install: `pip3 install -r requirements.txt`)\n- OAuth2 credentials (automatic 5-10x performance boost)\n\n## 📦 Version History\n\n- **v2.0.0** (2025-01-29) - REST API backend with 5-10x performance boost\n- **v1.2.0** (2025-01-29) - OAuth2 authentication with automatic token refresh\n- **v1.1.0** (2025-01-29) - HTML emails, attachments, batch operations\n- **v1.0.0** (2025-01-29) - Initial IMAP/SMTP implementation\n\nSee [CHANGELOG.md](CHANGELOG.md) for complete version history.\n\n## 🤝 Contributing\n\nContributions are welcome! Here's how you can help:\n\n- 🐛 **Report bugs:** [Open an issue](https://github.com/briansmith80/clawdbot-zoho-email/issues)\n- 💡 **Request features:** [Open an issue](https://github.com/briansmith80/clawdbot-zoho-email/issues)\n- 🔧 **Submit PRs:** [Pull requests](https://github.com/briansmith80/clawdbot-zoho-email/pulls)\n- ⭐ **Star the repo:** Show your support!\n\nThis is an open-source Clawdbot skill maintained by the community.\n\n## 📄 License\n\nMIT License - see [LICENSE](LICENSE) for details.\n\n---\n\n**Part of the Clawdbot ecosystem** | [ClawHub](https://clawhub.com) | [Documentation](SKILL.md)\n\nFile v2.2.9:_meta.json\n\n{\n  \"ownerId\": \"kn780decc8bavz0r6qen0513xh804z45\",\n  \"slug\": \"zoho-email-integration\",\n  \"version\": \"2.2.9\",\n  \"publishedAt\": 1772190656598\n}\n\nFile v2.2.9:CHANGELOG.md\n\n# Changelog\n\nAll notable changes to the Zoho Email Integration skill will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [2.2.8] - 2026-02-27\n\n### Fixed\n\n- **Zoho JP regional IMAP compatibility** — Fixed `UnicodeDecodeError` when connecting to `imap.zoho.jp` and other regional servers that return non-ASCII bytes (NBSP `\\xc2\\xa0`) in their CAPABILITY response during the initial TLS handshake.\n\n  **Root cause:** Python's `imaplib` uses ASCII decoding by default. Regional Zoho servers send a non-breaking space character in the CAPABILITY greeting, which crashes the ASCII decoder before authentication can begin.\n\n  **Fix:** `PatchedIMAP4_SSL` now overrides `open()` to set UTF-8 encoding before the server greeting is read. UTF-8 is a strict superset of ASCII, so this is fully backwards-compatible with all servers.\n\n  **Note:** v2.2.7 included a community contribution (thanks @SenorToru) that identified and described this bug correctly, but had an implementation error — `_get_capabilities` was defined as a standalone function and never bound to the class, making the fix a no-op. This release corrects that.\n\n---\n\n## [2.2.5] - 2026-02-14\n\n### 🔒 CRITICAL SECURITY FIX\n\n**Vulnerable JavaScript handler removed from distribution.**\n\n#### Fixed\n\n- **CRITICAL: Removed vulnerable email-command.js** - The examples/clawdbot-extension/ directory contained both a vulnerable (`email-command.js`) and secure (`email-command-SECURE.js`) version of the JavaScript command handler. The vulnerable file used `execSync` with shell interpolation, allowing command injection. The secure version using `spawn` with argument arrays is now the default `email-command.js`.\n\n  **Impact:** Remote code execution if the vulnerable handler was deployed and user input was processed through /email commands.\n  \n  **Fix:** \n  - Deleted vulnerable `email-command.js` \n  - Renamed `email-command-SECURE.js` to `email-command.js`\n  - Only the secure handler (using `spawn` with argument arrays) now ships\n\n#### Upgrade Urgency\n**IMMEDIATE** - If you deployed the JavaScript handler from examples/, replace it with the new secure version.\n\n---\n\n## [2.2.1] - 2026-02-12\n\n### 🔒 CRITICAL SECURITY FIXES\n\n**Three additional security vulnerabilities discovered and fixed:**\n\n#### Fixed\n\n- **CRITICAL: Path traversal in attachment download** - The `download_attachment()` function in `scripts/zoho-email.py` used untrusted email attachment filenames directly for file writes. An attacker could send a malicious email with attachment name `../../../../etc/cron.d/backdoor` to write arbitrary files anywhere on the system, leading to remote code execution or privilege escalation.\n  \n  **Fix:** Implemented `_sanitize_filename()` function that:\n  - Strips all directory path components\n  - Removes null bytes and dangerous characters\n  - Prevents hidden files (leading dots)\n  - Limits filename length to 200 characters\n  - Only uses safe basenames for file writes\n\n- **HIGH: Command injection in test script** - The `test-app-password.sh` script used `eval` with environment variables (`TEST_EMAIL`), allowing command injection via malicious email addresses like `user@example.com'; rm -rf /; echo '`.\n  \n  **Fix:** \n  - Added email format validation with regex before any execution\n  - Replaced `eval` with safer `bash -c` for command execution\n  - Test script now exits immediately on invalid email format\n\n- **All v2.2.0 fixes included** (see v2.2.0 below)\n\n#### Security Impact\n- **Path traversal** → Remote code execution, privilege escalation, data exfiltration\n- **Test script injection** → Arbitrary command execution during testing\n- **JavaScript handler injection** → Same as v2.2.0\n\n#### Upgrade Urgency\n**IMMEDIATE** - All users should upgrade to v2.2.1, especially if:\n- Downloading email attachments from untrusted senders\n- Running test scripts in automated environments\n- Exposing `/email` commands to users\n\n#### Migration\n```bash\n# Upgrade skill\nclawdhub install zoho-email-integration@2.2.1\n\n# No configuration changes required\n# Existing code fully backward compatible\n```\n\n#### Disclosure\n- Vulnerabilities reported by ClawHub security scanner\n- Fixed within 2 hours of disclosure\n- No known exploitation in the wild\n- Coordinated disclosure: SECURITY.md published with fix\n\n---\n\n## [2.2.0] - 2026-02-12\n\n### 🔒 SECURITY FIXES\n\n**Critical security vulnerabilities addressed based on ClawHub security audit:**\n\n#### Fixed\n- **CRITICAL: Command injection in JavaScript handler** - Original `email-command.js` used shell command interpolation with user-supplied arguments, allowing potential command injection attacks. Replaced with `spawn()` using argument arrays (no shell interpretation).\n  \n- **HIGH: Metadata mismatch** - Registry metadata incorrectly claimed \"no credentials required\" when ZOHO_EMAIL + authentication is actually required. Updated `clawhub.json` with accurate credential declarations.\n\n- **MEDIUM: Insufficient input validation** - Added comprehensive input sanitization:\n  - Email address format validation\n  - Shell metacharacter filtering\n  - Length limits (1000 char max)\n  - Newline/carriage return removal\n\n- **LOW: Token file permission enforcement** - Added automatic permission checks and correction to enforce 0600 on token files (owner read/write only).\n\n#### Added\n- **`email-command-SECURE.js`** - Hardened version of JavaScript handler with security fixes\n- **`SECURITY.md`** - Comprehensive security advisory and best practices guide\n- **`clawhub.json`** - Proper ClawHub metadata with credential declarations\n- Automatic token file permission verification on handler initialization\n- Input sanitization for all user-provided arguments\n- Email address validation\n- Security checklist and deployment guidelines\n\n#### Changed\n- JavaScript handler now uses `spawn()` instead of `execSync()` to prevent shell injection\n- All user inputs are sanitized before processing\n- Token file permissions automatically enforced\n- Enhanced error messages with security context\n\n#### Security Notes\n- **Upgrade recommended for all users, especially if exposing /email commands to untrusted users**\n- No data migration required - drop-in replacement\n- See SECURITY.md for detailed vulnerability descriptions and mitigation steps\n\n#### Migration\n```bash\n# Update to secure handler\ncp examples/clawdbot-extension/email-command-SECURE.js \\\n   examples/clawdbot-extension/email-command.js\n\n# Verify token permissions\nchmod 600 ~/.clawdbot/zoho-mail-tokens.json\n```\n\n---\n\n## [2.1.0] - 2026-02-06\n\n### ✨ NEW - Clawdbot Extension & Commands\n\n**First-class Clawdbot integration with `/email` commands:**\n\n#### Added\n- **`clawdbot_extension.py`** - New extension module for Clawdbot integration\n  - `/email unread` - Check unread email count\n  - `/email summary` - Brief summary for briefings\n  - `/email search <query>` - Search emails from chat\n  - `/email send <to> <subject> <body>` - Send emails from chat\n  - `/email doctor` - Check setup/connectivity\n  - `/email help` - Command help\n  \n- **Clawdbot command handlers** - Ready-to-use implementations\n  - `email_command.py` - Python handler for Clawdbot CLI\n  - `email-command.js` - JavaScript handler (Node.js)\n  \n- **Heartbeat integration examples** - `heartbeat-example.md`\n  - Morning briefing integration\n  - Email monitoring (alert on new unread)\n  - Cron job examples\n  - Complete walkthrough with shell scripts\n\n#### Features\n- Formatted output for Telegram/Discord/Slack (emoji, bold text, etc.)\n- Graceful error handling with helpful messages\n- Direct messaging platform integration\n- Works with OAuth2 and app-password auth\n- No external dependencies (uses existing `zoho_email.py`)\n\n#### Documentation\n- Updated README with Clawdbot integration section\n- New heartbeat/cron integration guide\n- Examples for morning briefings, monitoring, bulk actions\n\n#### Use Cases\n- ✅ `/email unread` in Telegram chat\n- ✅ Discord bot commands\n- ✅ Slack integration\n- ✅ Morning briefing summaries\n- ✅ Alert on important emails\n- ✅ Scheduled cleanups\n\n### Impact\n**User Experience: 8.5/10 → 9.5/10**\n- Email commands now work directly in messaging (Telegram/Discord)\n- No longer need to remember Python commands\n- Integrated with existing Clawdbot workflows\n- Better error messages with context\n\n## [2.0.3] - 2026-01-31\n\n### ✅ UX / Quality of Life\n- **ClawdHub-friendly naming**: aligned docs + skill metadata to `clawdhub install zoho-email`\n- **`--help` without configuration**: help no longer requires credentials/tokens\n- **`doctor` command**: first-run diagnostics (env vars, token file, REST reachability, IMAP/SMTP reachability)\n- **Standardised token location**: default is now `~/.clawdbot/zoho-mail-tokens.json`\n- **Convenience cleanup commands**:\n  - `empty-spam` (dry-run by default, `--execute` to run)\n  - `empty-trash` (dry-run by default, `--execute` to run)\n- **Docs cleanup**: removed broken README links, added practical quick start + common task commands\n- **Clawdbot wrapper example**: added `examples/clawdbot-commands/emails.sh`\n\n## [2.0.2] - 2026-01-29\n\n### 📝 Documentation - Updated SKILL.md Introduction\n\n**Updated skill description to accurately reflect v2.0 capabilities:**\n\n#### Changed\n- **Updated intro** - Changed outdated \"IMAP/SMTP only\" description to highlight OAuth2 and REST API features\n- **Reorganized features** - Grouped into Authentication & Performance, Email Operations, Batch & Bulk Operations, Security\n- **Emphasized performance** - Highlighted 5-10x speed improvement with REST API mode\n- **Corrected installation** - Fixed package name references (current install slug: `zoho-email`)\n- **Added requirements** - Listed Python 3.x, requests library, and Zoho Mail account\n\nThis ensures users immediately see the modern features (OAuth2, REST API, HTML, batch ops) instead of the old v1.0 IMAP/SMTP-only description.\n\n## [2.0.1] - 2026-01-29\n\n### 🐛 Fixed - REST API Batch Operations\n\n**Critical bug fixes for REST API mode + updated documentation:**\n\n#### Fixed\n- **Mark as read/unread operations** - Fixed 404 errors by using correct `/updatemessage` endpoint with `mode` parameter\n- **HTML email NameError** - Removed orphaned code that caused \"name 'email_id' is not defined\" error\n- **Delete operation** - Added missing folder ID parameter required by API\n- **Move operation** - Fixed endpoint to use `/updatemessage` with proper mode and folder lookup\n- **Batch operations** - All operations now batch multiple messages in single API calls (90% reduction in API usage)\n\n#### Changed\n- REST API methods now use folder name-to-ID lookup for consistency with IMAP mode\n- Batch operations consolidated into single API requests instead of individual calls\n- Improved error messages for folder not found cases\n\n#### Technical Details\n- Endpoint changed from `PUT /accounts/{id}/messages/{id}` to `PUT /accounts/{id}/updatemessage`\n- Delete endpoint now uses `DELETE /accounts/{id}/folders/{folderId}/messages/{id}`\n- All message IDs converted to integers for API compatibility\n- Added folder caching via `list_folders()` for efficient lookups\n\n#### Documentation\n- **Updated roadmap** - Marked OAuth2, REST API, attachments, HTML emails, and batch operations as completed\n- **Added future enhancements** - Listed realistic future features (threading, labels, webhooks, scheduled sends, etc.)\n- **Cleaned up repository** - Removed 29 internal development docs, keeping only essential user-facing files\n\nSee [FIXES_COMPLETE.md](FIXES_COMPLETE.md) for detailed technical documentation.\n\n## [2.0.0] - 2026-01-29\n\n### 🚀 Added - REST API Backend Implementation\n\n**Major performance upgrade: 5-10x faster operations with REST API support!**\n\n### Added - REST API Features\n- **ZohoRestAPIClient class** - Complete REST API client with OAuth2 authentication\n- **Connection pooling** - Persistent HTTP connections using requests.Session\n- **Automatic token refresh** - Seamless token refresh on expiration\n- **Rate limiting** - Built-in rate limiting with exponential backoff\n- **Retry logic** - Automatic retry on 429/5xx errors\n- **API mode auto-detection** - Automatically uses REST API when OAuth2 is available\n- **Graceful fallback** - Falls back to IMAP/SMTP if REST API fails\n- **100% backward compatibility** - All existing code works unchanged\n\n### Added - REST API Client Methods\n- `list_messages()` - List emails with server-side filtering\n- `get_message()` - Get specific message by ID\n- `send_message()` - Send emails via REST API\n- `mark_as_read()` - Mark messages as read\n- `mark_as_unread()` - Mark messages as unread\n- `delete_messages()` - Delete messages (move to trash)\n- `move_messages()` - Move messages between folders\n- `list_folders()` - List all folders\n- `get_account_id()` - Get Zoho Mail account ID\n\n### Added - API Mode Support\n- `--api-mode <mode>` CLI flag - Force 'auto', 'rest', or 'imap' mode\n- `api_mode` parameter in `ZohoEmail.__init__()`\n- Auto-detection: Uses REST API if OAuth2 + requests library available\n- Force REST: `--api-mode rest` (requires OAuth2)\n- Force IMAP: `--api-mode imap` (works with any auth)\n\n### Modified - Updated Methods with REST API Support\n- `get_unread_count()` - Uses REST API when available\n- `search_emails()` - Uses REST API list_messages with query conversion\n- `send_email()` - Uses REST API send_message when available\n- `mark_as_read()` - Uses REST API batch operations\n- `mark_as_unread()` - Uses REST API batch operations\n- `delete_emails()` - Uses REST API delete operations\n- `move_emails()` - Uses REST API move operations\n\n### Added - Dependencies\n- `requests>=2.31.0` - Required for REST API mode\n\n### Added - Environment Variables\n- `ZOHO_API_BASE_URL` - REST API base URL (default: https://mail.zoho.com/api)\n- `ZOHO_API_TIMEOUT` - REST API timeout in seconds (default: 30)\n- `ZOHO_API_RATE_DELAY` - Delay between requests in seconds (default: 0.5)\n- `ZOHO_MAX_RETRIES` - Maximum retry attempts (default: 3)\n\n### Added - Documentation\n- `REST_API_IMPLEMENTATION.md` - Implementation details and code summary\n\n### Performance Improvements\n- **5-10x faster** operations with REST API\n- **Connection pooling** - Reuses HTTP connections\n- **Server-side filtering** - Reduces data transfer\n- **Batch operations** - More efficient than IMAP\n\n### Technical Details\n- Added `has_requests_library()` helper function\n- REST API client uses requests.Session for connection pooling\n- Automatic OAuth2 bearer token injection\n- Rate limiting with configurable delay\n- Exponential backoff on failures\n- Token refresh before expiration (5-minute buffer)\n- Graceful error handling with IMAP fallback\n\n## [1.2.0] - 2026-01-29\n\n### 🔐 Added - OAuth2 Authentication Support\n\n**Secure OAuth2 authentication with automatic token management!**\n\n### Added - OAuth2 Features\n- **OAuth2 authorization code flow** - Interactive browser-based login\n- **Automatic token refresh** - Access tokens refresh automatically when expired\n- **Secure token storage** - Tokens stored in `~/.clawdbot/zoho-mail-tokens.json` with 600 permissions\n- **Token management CLI** - Commands to check status, refresh, and revoke tokens\n- **IMAP XOAUTH2 support** - OAuth2 authentication for IMAP connections\n- **SMTP XOAUTH2 support** - OAuth2 authentication for SMTP connections\n- **Backward compatibility** - App passwords still work, auto-detection of auth method\n- **No external dependencies** - Uses Python standard library only\n\n### Added - New Commands\n- `oauth-status` - Check OAuth2 token validity and expiration\n- `oauth-login` - Manually refresh OAuth2 tokens\n- `oauth-revoke` - Revoke OAuth2 access (delete token file)\n\n### Added - New CLI Flags\n- `--auth <method>` - Specify authentication method: 'auto' (default), 'password', or 'oauth2'\n- `--token-file <path>` - Custom OAuth2 token file path (default: ~/.clawdbot/zoho-mail-tokens.json)\n\n### Added - OAuth2 Setup Tool\n- `scripts/oauth-setup.py` - Interactive OAuth2 setup wizard\n  - Browser-based authorization flow\n  - Automatic callback handling\n  - Secure token storage\n  - Token refresh support\n  - Status checking\n\n### Added - Python API Methods\n- `ZohoEmail(auth_method='oauth2')` - OAuth2 authentication mode\n- `refresh_token()` - Manually refresh OAuth2 access token\n- `revoke_token()` - Revoke and delete OAuth2 tokens\n- `get_token_status()` - Check token validity and expiration\n\n### Added - Documentation\n- `OAUTH2_SETUP.md` - Complete OAuth2 setup guide with troubleshooting\n- `OAUTH2_FEATURE.md` - Comprehensive feature documentation\n- `OAUTH2_COMPLETE.md` - Implementation summary\n- Updated `SKILL.md` with OAuth2 section\n- Updated `README.md` with OAuth2 information\n\n### Security Improvements\n- **No password storage** - OAuth2 eliminates password storage\n- **Token-based auth** - Short-lived access tokens (1 hour)\n- **Auto-refresh** - Seamless token renewal\n- **Revocable access** - Easy to revoke without changing passwords\n- **Secure file permissions** - Token files enforced to 600\n- **Zoho-recommended** - Official authentication method\n\n### Changed\n- Auto-detection now prefers OAuth2 if token file exists\n- IMAP/SMTP connection methods updated to support XOAUTH2\n- Help text updated with OAuth2 commands and options\n- Error messages now mention both auth methods\n\n### Backward Compatibility\n- ✅ App passwords still fully supported\n- ✅ All existing commands work unchanged\n- ✅ No breaking changes to CLI or Python API\n- ✅ Auto-detection fallsback to app password if no OAuth2 tokens\n- ✅ Existing scripts require no modifications\n\n### Migration Path\n1. Run `python3 scripts/oauth-setup.py` to configure OAuth2\n2. Test with `--auth oauth2` flag\n3. Once working, auto-mode uses OAuth2 automatically\n4. Optionally remove app password: `unset ZOHO_PASSWORD`\n\n### Performance\n- Negligible runtime overhead (<100ms for token check)\n- Automatic token refresh only when needed\n- No impact on IMAP/SMTP performance\n\n### Known Limitations\n- Initial setup requires a browser for authorization\n- Token file must be stored locally (default: `~/.clawdbot/zoho-mail-tokens.json`)\n- Tokens stored in plaintext (with 600 permissions - encryption recommended for high-security environments)\n- Zoho-specific OAuth2 implementation\n\n## [1.1.0] - 2026-01-29\n\n### Added - Batch Operations\n- **Batch methods**: `mark_as_read()`, `mark_as_unread()`, `delete_emails()`, `move_emails()`\n- **Bulk action method**: `bulk_action()` for search-and-action workflows with dry-run support\n- **CLI commands**: `mark-read`, `mark-unread`, `delete`, `move`, `bulk-action`\n- **Safety features**: Interactive confirmation for deletions, dry-run mode for bulk actions\n- **Example script**: `examples/batch-cleanup.py` for automated email cleanup\n- **Documentation**: Comprehensive batch operations section in SKILL.md and BATCH_FEATURE.md\n\n### Enhanced\n- CLI help text now includes batch operations\n- Result tracking with success/failed lists for all batch operations\n- Progress reporting and error handling in batch operations\n\n## [1.0.0] - 2026-01-29\n\n### Added\n- Initial release\n- IMAP email reading and searching\n- SMTP email sending with CC/BCC\n- Unread count monitoring\n- Support for all IMAP folders (Inbox, Sent, Drafts, etc.)\n- Environment variable configuration\n- CLI interface with comprehensive help\n- Python API for programmatic use\n- Example scripts:\n  - `morning-briefing.sh` - Daily email report\n  - `vip-monitor.sh` - Monitor important senders\n  - `auto-reply.py` - Automated email responses\n- Verbose debug mode (`--verbose` flag)\n- Configurable timeouts (`ZOHO_TIMEOUT` env var)\n- Date-limited search for performance (`ZOHO_SEARCH_DAYS` env var)\n- Automated test suite (`test.sh`)\n- Complete documentation (README.md, SKILL.md, IMPROVEMENTS.md)\n- HTML email support with `send-html` command\n- Email attachment support (list, download, send)\n\n### Performance\n- **10x faster searches** - Date filtering limits search to recent emails (default: 30 days)\n- **2x faster unread checks** - Readonly IMAP mode\n- **Connection timeouts** - Prevents hanging on slow connections (default: 30s)\n- **Graceful degradation** - Continues on malformed emails\n\n### Security\n- Removed hardcoded credentials from code\n- Environment variable support for all credentials\n- Secure credentials file instructions\n- .gitignore to prevent credential commits\n- Error messages never expose credentials\n\n### Documentation\n- Complete SKILL.md with usage examples\n- Quick start README.md\n- MIT License\n- requirements.txt (standard library only in v1.x)\n- Example scripts with inline documentation\n- Comprehensive help text in CLI\n- IMPROVEMENTS.md with test results\n\n### Fixed\n- Proper connection cleanup in error cases\n- Better handling of malformed email subjects\n- Improved multipart email body extraction\n- Keyboard interrupt handling (Ctrl+C)\n- Socket timeout configuration\n\n## [Unreleased]\n\n### Planned Features (v2.1.0+)\n- ✅ Attachment upload via REST API\n- ✅ Webhook support for real-time notifications\n- ✅ Advanced search syntax (by attachment, size, date)\n- ✅ Label and tag management\n- ✅ Bulk batch API for multiple operations\n- ✅ Email templates and scheduled sends\n- ✅ Zoho Calendar integration\n- ✅ Zoho CRM integration\n\n---\n\n**Legend:**\n- 🚀 Major feature\n- ✅ Completed\n- 🔧 In progress\n- 📋 Planned\n\nFile v2.2.9:examples/clawdbot-extension/heartbeat-example.md\n\n# Zoho Email Integration with Clawdbot Heartbeat\n\nThis guide shows how to integrate the zoho-email skill with Clawdbot's heartbeat/cron system for automated email briefings.\n\n## Quick Start: Morning Email Summary\n\nAdd this to your Clawdbot heartbeat configuration:\n\n```bash\n# In your Clawdbot config or cron job (every day at 7:00 AM)\npython3 /path/to/zoho-email/scripts/clawdbot_extension.py summary\n```\n\nThis will output something like:\n```\n📭 No unread emails\n```\n\nOr if you have unread messages:\n```\n📧 3 unread emails\n```\n\n## Integration Example 1: Morning Briefing (Cron)\n\nCreate a cron job that includes email status in your morning briefing:\n\n```bash\n#!/bin/bash\n# morning-briefing.sh - Add to your cron scheduler\n\n# Get email summary\nEMAIL_SUMMARY=$(python3 /path/to/zoho-email/scripts/clawdbot_extension.py summary)\n\n# Build briefing\nBRIEFING=\"🌅 Good Morning!\n\n$EMAIL_SUMMARY\n\n🌤️ Weather: [your weather command here]\n✅ Tasks: [your tasks command here]\n\"\n\n# Send to Clawdbot messaging system\n# (adjust based on your Clawdbot configuration)\necho \"$BRIEFING\" | clawdbot send-to-telegram\n```\n\nThen schedule with cron:\n```bash\n0 7 * * * /path/to/morning-briefing.sh\n```\n\n## Integration Example 2: Email Monitoring (Heartbeat Loop)\n\nCreate a script that runs every 5 minutes and alerts on new unread emails:\n\n```bash\n#!/bin/bash\n# email-monitor.sh\n\nSTATE_FILE=\"/tmp/email-unread-count\"\nCURRENT=$(python3 /path/to/zoho-email/scripts/clawdbot_extension.py unread | grep -oP '\\d+(?= message)')\n\nif [ -f \"$STATE_FILE\" ]; then\n  PREVIOUS=$(cat \"$STATE_FILE\")\n  if [ \"$CURRENT\" -gt \"$PREVIOUS\" ]; then\n    NEW_COUNT=$((CURRENT - PREVIOUS))\n    echo \"🔔 $NEW_COUNT new email(s)\" | clawdbot send-to-telegram\n  fi\nfi\n\necho \"$CURRENT\" > \"$STATE_FILE\"\n```\n\nSchedule with cron:\n```bash\n*/5 * * * * /path/to/email-monitor.sh\n```\n\n## Integration Example 3: Clawdbot Cron Job (Native)\n\nIf you're using Clawdbot's native cron system:\n\n```yaml\n# In your Clawdbot cron config\njobs:\n  - name: morning-email-summary\n    schedule:\n      kind: cron\n      expr: \"0 7 * * *\"  # 7 AM daily\n      tz: UTC\n    payload:\n      kind: systemEvent\n      text: \"📧 Email status: \"  # Triggered message\n```\n\nThen in your Clawdbot session, add a handler:\n```python\nimport subprocess\n\ndef handle_email_check(message):\n    result = subprocess.run(\n        ['python3', '/path/to/scripts/clawdbot_extension.py', 'summary'],\n        capture_output=True,\n        text=True\n    )\n    return result.stdout.strip()\n```\n\n## Integration Example 4: Search Monitoring\n\nMonitor for specific keywords and alert when found:\n\n```bash\n#!/bin/bash\n# alert-on-invoice.sh\n\nSEARCH_QUERY=\"invoice\"\nLAST_CHECK=\"/tmp/email-invoice-check\"\n\npython3 /path/to/zoho-email/scripts/clawdbot_extension.py search \"$SEARCH_QUERY\" > /tmp/invoice-search.txt\n\n# Compare with previous result\nif [ -f \"$LAST_CHECK\" ]; then\n  if ! diff -q \"$LAST_CHECK\" /tmp/invoice-search.txt > /dev/null; then\n    echo \"📬 New invoice email found!\" | clawdbot send-to-telegram\n  fi\nfi\n\ncp /tmp/invoice-search.txt \"$LAST_CHECK\"\n```\n\n## Integration Example 5: Bulk Action (Cleanup)\n\nCombine with Clawdbot for scheduled email cleanup:\n\n```bash\n#!/bin/bash\n# weekly-cleanup.sh - Run every Sunday\n\necho \"🧹 Email cleanup starting...\"\n\n# Mark old newsletters as read\npython3 /path/to/zoho-email/scripts/zoho_email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action mark-read \\\n  --dry-run\n\necho \"✅ Cleanup complete\"\n```\n\n## Environment Setup\n\nMake sure these are set before any command:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\n\n# Option A: OAuth2 (recommended)\nexport ZOHO_TOKEN_FILE=\"~/.clawdbot/zoho-mail-tokens.json\"\n\n# Option B: App password\nexport ZOHO_PASSWORD=\"your-app-password\"\n```\n\n## Clawdbot Command Handler Integration\n\nIf you want `/email` commands to work directly in Telegram/Discord:\n\n1. **Copy the extension handler to your Clawdbot skills:**\n   ```bash\n   cp examples/clawdbot-extension/email_command.py \\\n      ~/.clawdbot/skills/email_command.py\n   ```\n\n2. **Register in Clawdbot config:**\n   ```yaml\n   skills:\n     email:\n       enabled: true\n       handler: email_command.handle_email_command\n   ```\n\n3. **Now use in Telegram/Discord:**\n   ```\n   /email unread\n   /email search invoice\n   /email send user@example.com \"Subject\" \"Body\"\n   ```\n\n## Testing\n\nTest the extension without Clawdbot:\n\n```bash\n# Check unread count\npython3 scripts/clawdbot_extension.py unread\n\n# Search emails\npython3 scripts/clawdbot_extension.py search \"invoice\"\n\n# Verify setup\npython3 scripts/clawdbot_extension.py doctor\n\n# Get help\npython3 scripts/clawdbot_extension.py help\n```\n\n## Troubleshooting\n\n### Command times out\n- Check if ZOHO_EMAIL is set correctly\n- Verify OAuth2 tokens are fresh: `python3 scripts/oauth-setup.py`\n- Check connectivity: `python3 scripts/zoho_email.py doctor`\n\n### Permission denied\n- Make scripts executable: `chmod +x scripts/*.py`\n- Check file permissions in heartbeat scripts\n\n### Output format issues\n- The extension outputs plain text by default\n- For structured data, use JSON output from the main script\n\n## Real-World Example: Complete Morning Briefing\n\n```bash\n#!/bin/bash\n# morning-briefing.sh\n\nset -e\ncd /path/to/zoho-email\n\n# Export credentials\nsource ~/.clawdbot/credentials.sh\n\n# Build briefing\ncat << EOF\n🌅 **Morning Briefing** — $(date '+%A, %B %d')\n\n📧 **Email Status**\n$(python3 scripts/clawdbot_extension.py summary)\n\n🌤️ **Weather**\n$(curl -s \"wttr.in/London?format=3\")\n\n✅ **To-Do List**\n- Build Morning Briefing System\n- Update GitHub documentation\n\n🖥️ **Server Health**\nDisk: $(df -h / | tail -1 | awk '{print $5}' $1)\n\n---\nGenerated at $(date '+%H:%M %Z')\nEOF\n```\n\nThen schedule:\n```bash\n0 7 * * * /path/to/morning-briefing.sh | clawdbot send-to-telegram\n```\n\n## Next Steps\n\n- ✅ [Set up OAuth2](../OAUTH2_SETUP.md) for REST API mode\n- 📚 [Full SKILL.md documentation](../SKILL.md)\n- 🚀 [Additional examples](.)\n\nFile v2.2.9:OAUTH2_SETUP.md\n\n# OAuth2 Setup Guide for Zoho Mail\n\nThis guide will help you set up OAuth2 authentication for the Zoho Email skill. OAuth2 is more secure and recommended over app passwords.\n\n## Why OAuth2?\n\n✅ **More secure** - No need to store passwords  \n✅ **Better access control** - Granular permissions  \n✅ **Auto-refresh** - Tokens refresh automatically  \n✅ **Revocable** - Easy to revoke access without changing passwords  \n✅ **Zoho-recommended** - Official authentication method  \n\n## Prerequisites\n\n- A Zoho Mail account\n- Access to Zoho API Console (https://api-console.zoho.com/)\n- Python 3.6+ (standard library only - no external dependencies!)\n\n## Step 1: Create OAuth2 Credentials\n\n1. **Go to Zoho API Console:**  \n   Visit: https://api-console.zoho.com/\n\n2. **Click \"Add Client\"**\n\n3. **Select \"Server-based Applications\"**\n\n4. **Fill in the details:**\n   ```\n   Client Name:      Clawdbot Zoho Mail\n   Homepage URL:     http://localhost\n   Authorized Redirect URIs:  http://localhost:8080/callback\n   ```\n   \n   > 💡 **Note:** If port 8080 is already in use, the setup script will automatically use the next available port (8081, 8082, etc.)\n\n5. **Click \"Create\"**\n\n6. **Copy your credentials:**\n   - **Client ID** (e.g., `1000.XXXXXXXXXXXXXXXXXXXXXX`)\n   - **Client Secret** (e.g., `xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)\n   \n   ⚠️ **Important:** Keep these credentials secure! Never commit them to version control.\n\n## Step 2: Run OAuth2 Setup Script\n\n```bash\ncd /path/to/zoho-email-integration\npython3 scripts/oauth-setup.py\n```\n\nThe script will:\n1. Prompt for your Client ID and Client Secret\n2. Ask where to store tokens (default: `~/.clawdbot/zoho-mail-tokens.json`)\n3. Open your browser for authorization\n4. Wait for you to log in and authorize the application\n5. Save tokens securely (permissions: 600)\n\n### Interactive Setup Example\n\n```\n==========================================================================\nZoho Mail OAuth2 Setup\n==========================================================================\n\nFirst, you need to create OAuth2 credentials in Zoho:\n1. Go to: https://api-console.zoho.com/\n2. Click 'Add Client' → 'Server-based Applications'\n3. Enter:\n   - Client Name: Clawdbot Zoho Mail\n   - Homepage URL: http://localhost\n   - Redirect URI: http://localhost:8080/callback\n4. Copy the Client ID and Client Secret\n\nEnter your Client ID: 1000.XXXXXXXXXXXXXXXXXXXXXX\nEnter your Client Secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nToken storage path [/root/.zoho-mail-tokens.json]: \n\n----------------------------------------------------------------------\nStarting OAuth2 authorization flow...\n----------------------------------------------------------------------\n\n🌐 Opening browser for authorization...\nIf browser doesn't open, visit this URL:\n\nhttps://accounts.zoho.com/oauth/v2/auth?scope=...\n\n✓ Listening for callback on http://localhost:8080\nPlease log in and authorize the application in your browser...\n\n✓ Authorization code received\nExchanging authorization code for tokens...\n✓ Tokens received successfully\n\n✓ Tokens saved to: /root/.zoho-mail-tokens.json\n✓ File permissions: 600 (owner read/write only)\n\n==========================================================================\n✓ OAuth2 Setup Complete!\n==========================================================================\n\nNext steps:\n1. Your tokens are stored in: /root/.zoho-mail-tokens.json\n2. Test the connection:\n   python3 scripts/zoho-email.py oauth-status\n3. Use OAuth2 in your scripts:\n   python3 scripts/zoho-email.py unread --auth oauth2\n\n⚠️  Security notes:\n- Keep your token file secure (permissions: 600)\n- Never commit tokens to version control\n- Tokens will auto-refresh when expired\n```\n\n## Step 3: Verify Setup\n\nCheck token status:\n\n```bash\npython3 scripts/zoho-email.py oauth-status\n```\n\nExpected output:\n```json\n{\n  \"auth_method\": \"oauth2\",\n  \"status\": \"valid\",\n  \"token_file\": \"/root/.zoho-mail-tokens.json\",\n  \"email\": \"your-email@zohomail.com\",\n  \"created_at\": 1706534400,\n  \"expires_at\": 1706538000,\n  \"expires_in_seconds\": 3600\n}\n\n✓ Token is valid (expires in 3600s)\n```\n\n## Step 4: Use OAuth2\n\nOAuth2 is now set up! The skill will automatically use OAuth2 if the token file exists.\n\n**Auto-detection** (recommended):\n```bash\npython3 scripts/zoho-email.py unread\n```\n\n**Explicit OAuth2:**\n```bash\npython3 scripts/zoho-email.py unread --auth oauth2\n```\n\n**Custom token path:**\n```bash\npython3 scripts/zoho-email.py unread --auth oauth2 --token-file /path/to/tokens.json\n```\n\n## OAuth2 Commands\n\n### Check Token Status\n\n```bash\npython3 scripts/zoho-email.py oauth-status\n```\n\nShows token validity, expiration time, and authentication method.\n\n### Refresh Tokens\n\nTokens auto-refresh when needed, but you can manually refresh:\n\n```bash\npython3 scripts/zoho-email.py oauth-login\n```\n\nOr using the setup script:\n\n```bash\npython3 scripts/oauth-setup.py refresh\n```\n\n### Revoke Tokens\n\nTo revoke OAuth2 access (deletes local token file):\n\n```bash\npython3 scripts/zoho-email.py oauth-revoke\n```\n\nTo fully revoke access from Zoho's side:\n1. Go to: https://accounts.zoho.com/home#security/connectedapps\n2. Find \"Clawdbot Zoho Mail\"\n3. Click \"Remove\"\n\n## Token Storage\n\n### Location\n\nDefault: `~/.clawdbot/zoho-mail-tokens.json`\n\nCustom:\n```bash\npython3 scripts/oauth-setup.py  # Will prompt for path\n```\n\n### Security\n\n- **Permissions:** 600 (owner read/write only)\n- **Contents:** Client ID, Client Secret, Access Token, Refresh Token\n- **Encryption:** Not encrypted (store in secure location)\n- **Version control:** Add to `.gitignore`\n\n### Token File Structure\n\n```json\n{\n  \"client_id\": \"1000.XXXXX\",\n  \"client_secret\": \"xxxxx\",\n  \"access_token\": \"1000.xxxxx.xxxxx\",\n  \"refresh_token\": \"1000.xxxxx.xxxxx\",\n  \"expires_in\": 3600,\n  \"token_type\": \"Bearer\",\n  \"created_at\": 1706534400\n}\n```\n\n## Troubleshooting\n\n### \"Port already in use\"\n\nThe setup script automatically finds an available port. If you see this error, try:\n```bash\n# Check what's using port 8080\nlsof -i :8080\n\n# Kill the process or use a different port manually by editing oauth-setup.py\n```\n\n### \"Authorization failed\"\n\n**Common causes:**\n- Incorrect Client ID or Client Secret\n- Redirect URI mismatch (must be exactly `http://localhost:8080/callback`)\n- Zoho account issues\n\n**Solutions:**\n1. Verify credentials in Zoho API Console\n2. Check redirect URI matches exactly\n3. Try creating a new OAuth client\n\n### \"Token expired\" or \"AUTHENTICATE failed\"\n\n**Automatic fix:**\n```bash\npython3 scripts/zoho-email.py oauth-login\n```\n\n**Manual fix:**\n```bash\npython3 scripts/oauth-setup.py refresh\n```\n\n**If refresh fails:**\n```bash\n# Delete old tokens and set up again\nrm ~/.clawdbot/zoho-mail-tokens.json\npython3 scripts/oauth-setup.py\n```\n\n### \"Token file not found\"\n\nYou haven't set up OAuth2 yet:\n```bash\npython3 scripts/oauth-setup.py\n```\n\n### Browser doesn't open\n\nCopy the authorization URL from the terminal output and paste it in your browser manually.\n\n### \"Invalid scope\" error\n\nThis means the Zoho Mail API scopes have changed. Update `ZOHO_SCOPES` in `scripts/oauth-setup.py`:\n\n```python\nZOHO_SCOPES = [\n    'ZohoMail.messages.READ',\n    'ZohoMail.messages.CREATE',\n    'ZohoMail.messages.UPDATE',\n    'ZohoMail.folders.READ',\n    'ZohoMail.accounts.READ'\n]\n```\n\n## Security Best Practices\n\n### DO:\n✅ Store tokens in your home directory (`~/.clawdbot/zoho-mail-tokens.json`)  \n✅ Use file permissions 600 (owner read/write only)  \n✅ Add token files to `.gitignore`  \n✅ Regularly review authorized apps in Zoho settings  \n✅ Use environment variables for `ZOHO_EMAIL`  \n✅ Revoke old tokens when no longer needed  \n\n### DON'T:\n❌ Commit token files to version control  \n❌ Share token files or credentials  \n❌ Use world-readable permissions  \n❌ Store tokens in web-accessible directories  \n❌ Hardcode Client ID/Secret in scripts  \n\n### Additional Security\n\n#### Encrypt Token File (Optional)\n\n```bash\n# Encrypt token file with GPG\ngpg -c ~/.clawdbot/zoho-mail-tokens.json\nrm ~/.clawdbot/zoho-mail-tokens.json\n\n# Decrypt when needed\ngpg -d ~/.clawdbot/zoho-mail-tokens.json.gpg > ~/.clawdbot/zoho-mail-tokens.json\n# Use the skill\npython3 scripts/zoho-email.py unread\n# Remove decrypted file\nshred -u ~/.clawdbot/zoho-mail-tokens.json\n```\n\n#### Use Separate OAuth Client per Environment\n\nCreate different OAuth clients for:\n- Development\n- Production\n- Testing\n\nThis allows you to revoke specific environments without affecting others.\n\n## Backward Compatibility\n\nOAuth2 is fully backward compatible with app passwords:\n\n**App password** (still works):\n```bash\nexport ZOHO_EMAIL=\"your-email@zohomail.com\"\nexport ZOHO_PASSWORD=\"your-app-password\"\npython3 scripts/zoho-email.py unread\n```\n\n**OAuth2** (recommended):\n```bash\nexport ZOHO_EMAIL=\"your-email@zohomail.com\"  # Still needed\npython3 scripts/zoho-email.py unread --auth oauth2\n```\n\n**Auto-detect** (uses OAuth2 if available):\n```bash\nexport ZOHO_EMAIL=\"your-email@zohomail.com\"\npython3 scripts/zoho-email.py unread\n```\n\n## Migration from App Passwords\n\nAlready using app passwords? Migrate to OAuth2:\n\n1. **Set up OAuth2** (keeps app password working):\n   ```bash\n   python3 scripts/oauth-setup.py\n   ```\n\n2. **Test OAuth2**:\n   ```bash\n   python3 scripts/zoho-email.py unread --auth oauth2\n   ```\n\n3. **Switch to OAuth2** (auto-detect):\n   ```bash\n   # No changes needed! Just use the skill as normal\n   python3 scripts/zoho-email.py unread\n   ```\n\n4. **Optional: Remove app password**:\n   ```bash\n   unset ZOHO_PASSWORD\n   ```\n\n## Advanced Configuration\n\n### Multiple Zoho Accounts\n\nUse separate token files:\n\n```bash\n# Account 1\npython3 scripts/oauth-setup.py\n# Save to: ~/.zoho-mail-tokens-account1.json\n\n# Account 2\npython3 scripts/oauth-setup.py\n# Save to: ~/.zoho-mail-tokens-account2.json\n\n# Use specific account\npython3 scripts/zoho-email.py unread --token-file ~/.zoho-mail-tokens-account1.json\npython3 scripts/zoho-email.py unread --token-file ~/.zoho-mail-tokens-account2.json\n```\n\n### CI/CD Integration\n\nFor automated environments:\n\n```bash\n# Option 1: Use app password in CI/CD\nexport ZOHO_EMAIL=\"ci-bot@company.com\"\nexport ZOHO_PASSWORD=\"app-password\"\n\n# Option 2: Store token file as secret\n# Upload ~/.clawdbot/zoho-mail-tokens.json as CI/CD secret\n# Restore in build:\necho \"$ZOHO_TOKENS_JSON\" > ~/.clawdbot/zoho-mail-tokens.json\nchmod 600 ~/.clawdbot/zoho-mail-tokens.json\n```\n\n## Additional Resources\n\n- **Zoho API Console:** https://api-console.zoho.com/\n- **Zoho Mail API Docs:** https://www.zoho.com/mail/help/api/\n- **OAuth2 RFC:** https://tools.ietf.org/html/rfc6749\n- **Zoho Account Security:** https://accounts.zoho.com/home#security\n\n## Need Help?\n\n- Check [Troubleshooting](#troubleshooting) section\n- Run with `--verbose` flag for debug output:\n  ```bash\n  python3 scripts/zoho-email.py oauth-status --verbose\n  ```\n- Check token file permissions: `ls -l ~/.clawdbot/zoho-mail-tokens.json`\n- Verify ZOHO_EMAIL is set: `echo $ZOHO_EMAIL`\n\n---\n\n**Last updated:** 2025-01-29  \n**Version:** 1.2.0  \n**Status:** Production Ready ✅\n\nFile v2.2.9:SECURITY-AUDIT-SUMMARY.md\n\n# Security Audit Summary - Zoho Email Integration\n\n**Date:** 2026-02-12  \n**Auditor:** ClawHub Security Team + Jarvis (AI Assistant)  \n**Skill Version:** v2.1.0 → v2.2.0  \n\n---\n\n## Executive Summary\n\nSecurity audit of the Zoho Email Integration skill identified **4 security issues** ranging from CRITICAL to LOW severity. All issues have been addressed in v2.2.0 with comprehensive fixes and security enhancements.\n\n**Recommendation:** All users should upgrade to v2.2.0, especially those exposing `/email` commands to untrusted users.\n\n---\n\n## Vulnerabilities Found & Fixed\n\n### 1. Command Injection (CRITICAL) ✅ FIXED\n\n**Vulnerability:**\n- Original JavaScript handler (`email-command.js`) used shell command interpolation\n- User-supplied arguments inserted into command string with inadequate escaping\n- Allowed potential command injection via shell metacharacters\n\n**Attack Vector:**\n```bash\n/email search \"; rm -rf /; echo \"\n/email search `whoami`\n/email search $(cat /etc/passwd)\n```\n\n**Fix:**\n- Created `email-command-SECURE.js` with `spawn()` instead of `execSync()`\n- Arguments passed as array (no shell interpretation)\n- Added input sanitization (shell metacharacter filtering)\n- Length limits enforced (1000 char max)\n\n**Code Comparison:**\n\n**VULNERABLE (v2.1.0):**\n```javascript\nconst cmd = `python3 \"${scriptPath}\" ${cmdArgs.map(arg => `\"${arg}\"`).join(' ')}`;\nconst output = execSync(cmd);  // ❌ Shell interpolation\n```\n\n**SECURE (v2.2.0):**\n```javascript\nconst spawnArgs = [scriptPath, sanitizedCommand, ...sanitizedArgs];\nconst process = spawn('python3', spawnArgs);  // ✅ No shell\n```\n\n**Impact:** CRITICAL - Remote code execution possible if exposed to untrusted users  \n**Status:** ✅ FIXED in v2.2.0\n\n---\n\n### 2. Metadata Mismatch (HIGH) ✅ FIXED\n\n**Vulnerability:**\n- Registry metadata claimed: \"Required env vars: none\"\n- Registry metadata claimed: \"Primary credential: none\"\n- SKILL.md and scripts actually require ZOHO_EMAIL + authentication\n- Could mislead administrators about security requirements\n\n**Fix:**\n- Created `clawhub.json` with accurate credential declarations\n- Documented required environment variables: `ZOHO_EMAIL`\n- Documented authentication options: OAuth2 (primary), app-password (alternative)\n- Listed sensitive token files and required permissions\n\n**New Metadata:**\n```json\n{\n  \"credentials\": {\n    \"primary\": \"oauth2\",\n    \"alternatives\": [\"app-password\"],\n    \"required_env_vars\": [\"ZOHO_EMAIL\"],\n    \"optional_env_vars\": [\"ZOHO_PASSWORD\"],\n    \"token_files\": [\n      {\n        \"path\": \"~/.clawdbot/zoho-mail-tokens.json\",\n        \"permissions\": \"0600\",\n        \"sensitive\": true\n      }\n    ]\n  }\n}\n```\n\n**Impact:** HIGH - Security requirements not transparent to administrators  \n**Status:** ✅ FIXED in v2.2.0\n\n---\n\n### 3. Insufficient Input Validation (MEDIUM) ✅ FIXED\n\n**Vulnerability:**\n- No validation of email addresses\n- No sanitization of search queries\n- No length limits on user inputs\n- Could lead to unexpected behavior or log injection\n\n**Fix:**\n- Added email address format validation (regex)\n- Input sanitization function:\n  - Removes shell metacharacters: `;`, `&`, `|`, `` ` ``, `$`, `()`, `{}`, `[]`, `<>`, `\\`\n  - Removes newlines and carriage returns\n  - Enforces length limit (1000 characters)\n- Validates minimum search query length (2 chars)\n\n**Sanitization Function:**\n```javascript\nsanitizeInput(input) {\n  return input\n    .replace(/[;&|`$(){}[\\]<>\\\\]/g, '')  // Remove shell metacharacters\n    .replace(/\\n|\\r/g, '')                // Remove newlines\n    .trim()\n    .slice(0, 1000);                      // Limit length\n}\n```\n\n**Impact:** MEDIUM - Input validation bypass, potential for log injection  \n**Status:** ✅ FIXED in v2.2.0\n\n---\n\n### 4. Token File Permission Enforcement (LOW) ✅ FIXED\n\n**Vulnerability:**\n- OAuth token file permissions recommended (0600) but not verified\n- Existing token files could have insecure permissions (644, 664, etc.)\n- Sensitive data (client_secret, refresh_token) potentially readable by other users\n\n**Fix:**\n- Added automatic permission check on handler initialization\n- Automatically corrects insecure permissions to 0600\n- Logs security warnings for visibility\n- OAuth setup script already set 0600 (no change needed)\n\n**Permission Check:**\n```javascript\ncheckTokenPermissions(filePath) {\n  const stats = fs.statSync(filePath);\n  const mode = stats.mode & parseInt('777', 8);\n  \n  if (mode !== parseInt('600', 8)) {\n    console.warn(`[SECURITY] Token file has insecure permissions, changing to 0600`);\n    fs.chmodSync(filePath, 0o600);\n  }\n}\n```\n\n**Impact:** LOW - Token file exposure on multi-user systems  \n**Status:** ✅ FIXED in v2.2.0\n\n---\n\n## Additional Security Enhancements\n\n### Documentation\n- **SECURITY.md** - Comprehensive security advisory\n- **SECURITY-AUDIT-SUMMARY.md** - This document\n- **clawhub.json** - Proper metadata declarations\n- Updated CHANGELOG.md with security fixes\n\n### Best Practices Guide\n- OAuth2 vs app-password security comparison\n- Token file permission management\n- Credential rotation recommendations\n- Secure deployment checklist\n- Vulnerability disclosure process\n\n---\n\n## Testing & Verification\n\n### Tests Performed\n1. ✅ Command injection attempts blocked\n2. ✅ Input sanitization working correctly\n3. ✅ Email validation rejecting invalid addresses\n4. ✅ Token file permissions automatically corrected\n5. ✅ Python scripts still using safe subprocess calls\n\n### Test Commands\n```bash\n# Test input sanitization\n/email search \"; echo hacked\"          # ✅ Sanitized, no execution\n/email search `whoami`                 # ✅ Backticks removed\n/email send $(whoami) \"test\" \"body\"    # ✅ Sanitized, no expansion\n\n# Test email validation\n/email send invalid-email \"test\" \"body\"  # ✅ Rejected\n\n# Test token permissions\nchmod 644 ~/.clawdbot/zoho-mail-tokens.json  # ✅ Auto-corrected to 600\n```\n\n---\n\n## Deployment Recommendations\n\n### Immediate Actions\n1. **Update to v2.2.0**\n   ```bash\n   cd /root/clawd/molthub-skills/zoho-email-integration\n   git pull origin main\n   ```\n\n2. **Replace vulnerable handler**\n   ```bash\n   cp examples/clawdbot-extension/email-command-SECURE.js \\\n      examples/clawdbot-extension/email-command.js\n   ```\n\n3. **Verify token permissions**\n   ```bash\n   chmod 600 ~/.clawdbot/zoho-mail-tokens.json\n   ls -la ~/.clawdbot/zoho-mail-tokens.json  # Verify: -rw-------\n   ```\n\n### Long-term Recommendations\n1. **Implement rate limiting** (bot-level)\n2. **Restrict command access** to authorized users\n3. **Enable audit logging** for sensitive operations\n4. **Regular credential rotation** (quarterly)\n5. **Monitor for abuse patterns**\n\n---\n\n## Risk Assessment\n\n### Before v2.2.0\n- **Command Injection:** CRITICAL risk if exposed to untrusted users\n- **Metadata Mismatch:** HIGH risk of misconfiguration\n- **Input Validation:** MEDIUM risk of unexpected behavior\n- **Token Permissions:** LOW risk on single-user systems\n\n### After v2.2.0\n- **Command Injection:** ✅ MITIGATED (spawn with argument arrays)\n- **Metadata Mismatch:** ✅ RESOLVED (accurate declarations)\n- **Input Validation:** ✅ MITIGATED (comprehensive sanitization)\n- **Token Permissions:** ✅ RESOLVED (automatic enforcement)\n\n**Overall Risk:** CRITICAL → LOW (after upgrade)\n\n---\n\n## Files Changed\n\n### New Files\n- `examples/clawdbot-extension/email-command-SECURE.js` (hardened handler)\n- `SECURITY.md` (security advisory)\n- `SECURITY-AUDIT-SUMMARY.md` (this document)\n- `clawhub.json` (metadata)\n\n### Modified Files\n- `CHANGELOG.md` (v2.2.0 release notes)\n\n### Unchanged (Already Secure)\n- `scripts/zoho_email.py` (uses safe subprocess calls)\n- `scripts/clawdbot_extension.py` (uses safe subprocess calls)\n- `scripts/oauth-setup.py` (already sets 0600 permissions)\n\n---\n\n## Conclusion\n\nAll identified security vulnerabilities have been addressed in v2.2.0. The skill now implements industry-standard security practices including input sanitization, command injection prevention, and proper permission enforcement.\n\n**Upgrade to v2.2.0 is highly recommended for all users.**\n\n---\n\n## Questions?\n\nFor security questions or to report new vulnerabilities:\n- Email: brian@creativestudio.co.za\n- GitHub: https://github.com/briansmith80/clawdbot-zoho-email (private disclosure)\n\n**Please report responsibly - do not open public issues for security vulnerabilities.**\n\nFile v2.2.9:SECURITY.md\n\n# Security Advisory - Zoho Email Integration\n\n## Security Fixes in v2.2.1 (2026-02-12)\n\nThis release addresses **three critical security vulnerabilities** identified in ClawHub security audits.\n\n### Fixed Vulnerabilities\n\n#### 1. Command Injection in JavaScript Handler (CRITICAL)\n\n**Issue:** The original `email-command.js` used shell command interpolation with user-supplied arguments, allowing potential command injection attacks.\n\n**Attack Example:**\n```javascript\n/email search \"; rm -rf ~; echo \"\n```\n\n**Fix:** New `email-command-SECURE.js` uses `spawn()` with argument arrays instead of shell interpolation. No shell metacharacters are processed.\n\n**Migration:**\n```bash\n# Replace vulnerable handler\ncp examples/clawdbot-extension/email-command-SECURE.js \\\n   examples/clawdbot-extension/email-command.js\n```\n\n#### 2. Metadata Mismatch (HIGH)\n\n**Issue:** Registry metadata claimed \"Required env vars: none\" and \"Primary credential: none\" when ZOHO_EMAIL + ZOHO_PASSWORD or OAuth tokens are actually required.\n\n**Fix:** Updated `clawhub.json` metadata to accurately declare:\n- Required environment variables: `ZOHO_EMAIL`\n- Primary credential: `oauth2` (with app-password fallback)\n\n#### 3. Insufficient Input Validation (MEDIUM)\n\n**Issue:** No validation of email addresses or search queries.\n\n**Fix:** Added input sanitization:\n- Email address format validation\n- Shell metacharacter filtering\n- Length limits (1000 char max)\n- Newline/carriage return removal\n\n#### 4. Token File Permission Enforcement (LOW)\n\n**Issue:** Permissions recommended but not verified on existing token files.\n\n**Fix:** Added automatic permission check and enforcement:\n- Checks token file permissions on handler initialization\n- Automatically corrects insecure permissions to 0600\n- Logs security warnings for visibility\n\n#### 5. Path Traversal in Attachment Download (CRITICAL)\n\n**Issue:** The `download_attachment()` function in `scripts/zoho-email.py` used untrusted attachment filenames directly for file writes, allowing arbitrary file write via malicious attachment names.\n\n**Attack Example:**\nAn attacker could send an email with an attachment named:\n- `../../../../etc/cron.d/backdoor` - Write to system cron\n- `~/.ssh/authorized_keys` - Add SSH keys for persistence  \n- `../../.bashrc` - Execute code on shell login\n\n**Fix:** Implemented `_sanitize_filename()` function that:\n- Strips all directory path components (Windows and Unix)\n- Removes null bytes and dangerous characters\n- Prevents hidden files (leading dots)\n- Limits filename length to 200 characters\n- Returns safe basename only\n\n**Impact:** Prevents arbitrary file write, remote code execution, and privilege escalation through malicious email attachments.\n\n**Code Change:**\n```python\n# Before (VULNERABLE)\nif not output_path:\n    output_path = filename  # filename from email header - UNSAFE!\nwith open(output_path, 'wb') as f:\n    f.write(payload)\n\n# After (SECURE)\nif not output_path:\n    safe_filename = self._sanitize_filename(raw_filename)\n    safe_output_path = safe_filename\nwith open(safe_output_path, 'wb') as f:\n    f.write(payload)\n```\n\n#### 6. Command Injection in Test Script (HIGH)\n\n**Issue:** The `test-app-password.sh` script used `eval` to execute test commands with environment variables (`TEST_EMAIL`), allowing command injection if a malicious email address was provided.\n\n**Attack Example:**\n```bash\nTEST_EMAIL=\"user@example.com' ; rm -rf / ; echo '\" ./test-app-password.sh\n```\n\n**Fix:** \n1. Replaced `eval` with `bash -c` for safer command execution\n2. Added regex validation of `TEST_RECIPIENT` email format before any command execution\n3. Validation regex: `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$`\n\n**Impact:** Prevents arbitrary command execution during testing. Script now exits immediately if an invalid email address is detected.\n\n---\n\n## Security Best Practices\n\n### 1. Credential Management\n\n**OAuth2 (Recommended):**\n```bash\n# Run interactive setup\npython3 scripts/oauth-setup.py\n\n# Verify token file permissions\nls -la ~/.clawdbot/zoho-mail-tokens.json  # Should show -rw------- (600)\n```\n\n**App Password (Simple):**\n```bash\n# Use app-specific password, NOT your main Zoho password\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"app-specific-password-here\"\n```\n\n### 2. File Permissions\n\n**Critical files must be secured:**\n```bash\n# Token file (OAuth2)\nchmod 600 ~/.clawdbot/zoho-mail-tokens.json\n\n# Credentials file (app password)\nchmod 600 ~/.clawdbot/zoho-credentials.sh\n```\n\n**Verify:**\n```bash\nstat -c \"%a %n\" ~/.clawdbot/zoho-*\n# Output should be: 600 filename\n```\n\n### 3. Command Handler Security\n\n**If exposing /email commands to untrusted users:**\n\n1. **Use the secure handler:**\n   ```bash\n   cp examples/clawdbot-extension/email-command-SECURE.js YOUR_SKILL_PATH/\n   ```\n\n2. **Add rate limiting** (not included - implement at bot level)\n\n3. **Restrict command access** to authorized users only\n\n4. **Monitor for abuse:**\n   ```javascript\n   // Add logging to handler\n   console.log(`[AUDIT] User ${userId} executed: /email ${command}`);\n   ```\n\n### 4. Network Security\n\n**OAuth setup opens localhost callback:**\n- Port: 8080 (or next available)\n- Listens only on 127.0.0.1 (not externally accessible)\n- Automatically closes after authorization\n- Safe on single-user systems\n\n**If running on shared/multi-user server:**\n- Use SSH tunnel for OAuth setup\n- Or run setup on local machine, then copy token file\n\n---\n\n## Vulnerability Disclosure\n\nFound a security issue? Please report responsibly:\n\n1. **DO NOT** open a public GitHub issue\n2. Email: brian@creativestudio.co.za\n3. Include: description, impact, proof-of-concept (if applicable)\n4. Allow reasonable time for fix before public disclosure\n\n---\n\n## Security Checklist\n\nBefore deploying this skill:\n\n- [ ] Using OAuth2 or app-specific password (not main password)\n- [ ] Token/credential files have 0600 permissions\n- [ ] Using secure command handler (email-command-SECURE.js)\n- [ ] Command access restricted to authorized users\n- [ ] Audit logging enabled for sensitive operations\n- [ ] No hardcoded credentials in code or version control\n- [ ] Regular credential rotation policy established\n\n---\n\n## Changelog\n\n**v2.2.1 (2026-02-12)**\n- **[CRITICAL]** Fixed path traversal vulnerability in attachment download\n- **[CRITICAL]** Fixed command injection in JavaScript handler\n- **[HIGH]** Fixed command injection in test script (eval with untrusted input)\n- **[MEDIUM]** Added input sanitization and validation for all user inputs\n- **[LOW]** Added automatic token file permission enforcement\n- Updated metadata to accurately declare credential requirements\n- Added comprehensive security documentation (SECURITY.md)\n\n**v2.2.0 (2026-02-12)**\n- Initial security hardening (incomplete - use v2.2.1)\n\n**v2.1.0**\n- Original release with multiple critical security vulnerabilities\n\n---\n\n## References\n\n- [OWASP Command Injection](https://owasp.org/www-community/attacks/Command_Injection)\n- [Node.js Security Best Practices](https://nodejs.org/en/docs/guides/security/)\n- [OAuth2 Security Best Practices](https://datatracker.ietf.org/doc/html/rfc6819)\n\nFile v2.2.9:requirements.txt\n\n# Zoho Email Integration - Python Requirements\n\n# REST API support (v2.0.0+)\nrequests>=2.31.0\n\n# OAuth2 uses Python standard library for IMAP/SMTP mode\n# REST API mode requires requests library for HTTP operations\n\n# Standard library modules (documented for reference):\n\n# Email operations:\n# - imaplib (email reading via IMAP)\n# - smtplib (email sending via SMTP)\n# - email (email parsing and composition)\n\n# OAuth2 authentication (v1.2.0+):\n# - urllib.request (HTTP requests for token exchange)\n# - urllib.parse (URL encoding)\n# - http.server (OAuth2 callback server)\n# - webbrowser (browser automation for OAuth2 flow)\n# - base64 (XOAUTH2 encoding)\n\n# Utilities:\n# - json (JSON output formatting and token storage)\n# - socket (timeout handling)\n# - datetime (date filtering)\n# - time (timestamp handling for OAuth2)\n# - re (HTML to text conversion)\n# - os (file operations)\n# - sys (command-line interface)\n\nArchive v2.2.8: 33 files, 93472 bytes\n\nFiles: CHANGELOG.md (21410b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command.js (10065b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (98123b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (18620b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nFile v2.2.8:SKILL.md\n\n---\nname: zoho-email-integration\ndescription: Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-hardened against path traversal and command injection. Perfect for email automation and workflows.\nhomepage: https://github.com/briansmith80/clawdbot-zoho-email\nmetadata:\n  openclaw:\n    requires:\n      bins:\n        - python3\n      env:\n        - ZOHO_EMAIL\n        - ZOHO_PASSWORD\n    primaryEnv: ZOHO_EMAIL\n    tokenFile: \"~/.clawdbot/zoho-mail-tokens.json\"\n---\n\n# Zoho Email Integration\n\n**v2.2.6** - Complete Zoho Mail integration with OAuth2 authentication, REST API backend (5-10x faster than IMAP/SMTP), and **Clawdbot extension with /email commands for Telegram/Discord**. **Security-hardened** against path traversal and command injection. Supports HTML emails, attachments, batch operations, and advanced automation workflows.\n\nChoose your authentication: OAuth2 (recommended, secure) or app password (simple setup).\n\n## 🔄 Update to Latest Version\n\n```bash\nclawhub install zoho-email-integration --force\n```\n\nOr update all skills:\n```bash\nclawhub update\n```\n\n## 🔒 Security Notice (v2.2.5+)\n\n**CRITICAL FIX:** Removed vulnerable JavaScript command handler. If you deployed `email-command.js` from the examples folder, update immediately:\n\n```bash\n# Re-download the secure handler\nclawhub install zoho-email-integration --force\ncp ~/.openclaw/skills/zoho-email-integration/examples/clawdbot-extension/email-command.js /your/deployment/path/\n```\n\nThe vulnerable version used `execSync` with shell interpolation. The new version uses `spawn` with argument arrays to prevent command injection.\n\n## ✨ Features\n\n### 🔐 Authentication & Performance\n- **OAuth2 authentication** - Secure token-based auth with automatic refresh\n- **REST API backend** - 5-10x faster operations than IMAP/SMTP\n- **Graceful fallback** - Automatically falls back to IMAP if REST API unavailable\n- **App password support** - Simple alternative to OAuth2\n\n### 📧 Email Operations\n- **📥 Read emails** - Fetch from any folder (Inbox, Sent, Drafts, etc.)\n- **🔍 Smart search** - Search by subject, sender, keywords with REST API speed\n- **📊 Monitor inbox** - Real-time unread count for notifications\n- **📤 Send emails** - Plain text or HTML with CC/BCC support\n- **🎨 HTML emails** - Rich formatting with professional templates included\n- **📎 Attachments** - Send and download file attachments\n\n### ⚡ Batch & Bulk Operations\n- **Batch operations** - Mark, delete, or move multiple emails efficiently\n- **Bulk actions** - Search and act on hundreds of emails at once\n- **Dry-run mode** - Preview actions before executing for safety\n\n### 🔒 Security\n- **No hardcoded credentials** - OAuth2 tokens or environment variables only\n- **Automatic token refresh** - Seamless token renewal\n- **Encrypted connections** - SSL/TLS for all operations\n\n## 📦 Installation\n\n```bash\nclawdhub install zoho-email\n```\n\n**Requirements:**\n- Python 3.x\n- `requests` library (install: `pip3 install requests`)\n- Zoho Mail account\n\n## ⚙️ Setup\n\n### 1. Get an App-Specific Password\n\n**Important:** Don't use your main Zoho password!\n\n1. Log in to Zoho Mail\n2. Go to **Settings** → **Security** → **App Passwords**\n3. Generate a new app password for \"Clawdbot\" or \"IMAP/SMTP Access\"\n4. Copy the password (you'll need it next)\n\n### 2. Configure Credentials\n\n**Option A: Environment Variables**\n\nExport your Zoho credentials:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\"\n```\n\n**Option B: Credentials File**\n\nCreate `~/.clawdbot/zoho-credentials.sh`:\n\n```bash\n#!/bin/bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\"\n```\n\nMake it executable and secure:\n```bash\nchmod 600 ~/.clawdbot/zoho-credentials.sh\n```\n\nThen source it before running:\n```bash\nsource ~/.clawdbot/zoho-credentials.sh\n```\n\n### 3. Test Connection\n\n```bash\npython3 scripts/zoho-email.py unread\n```\n\nExpected output:\n```json\n{\"unread_count\": 5}\n```\n\n## 🚀 Usage\n\nAll commands require credentials set via environment variables.\n\n### Quick commands (common tasks)\n\n```bash\n# Diagnose setup (recommended first step)\npython3 scripts/zoho-email.py doctor\n\n# Unread count (great for briefings)\npython3 scripts/zoho-email.py unread\n\n# Search inbox\npython3 scripts/zoho-email.py search \"invoice\"\n\n# Get a specific email (folder + id)\npython3 scripts/zoho-email.py get INBOX <id>\n\n# Send a simple email\npython3 scripts/zoho-email.py send recipient@example.com \"Subject\" \"Body text\"\n\n# Empty Spam (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-spam\n# Execute for real\npython3 scripts/zoho-email.py empty-spam --execute\n\n# Empty Trash (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-trash\n# Execute for real\npython3 scripts/zoho-email.py empty-trash --execute\n```\n\n### Send HTML Emails\n\nSend rich, formatted HTML emails with multipart/alternative support (both HTML and plain text versions):\n\n**CLI Command:**\n```bash\n# Send HTML from a file\npython3 scripts/zoho-email.py send-html recipient@example.com \"Newsletter\" examples/templates/newsletter.html\n\n# Send HTML from inline text\npython3 scripts/zoho-email.py send-html recipient@example.com \"Welcome\" \"<h1>Hello!</h1><p>Welcome to our service.</p>\"\n\n# Preview HTML email before sending\npython3 scripts/zoho-email.py preview-html examples/templates/newsletter.html\n```\n\n**Python API:**\n```python\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Method 1: Send HTML with auto-generated plain text fallback\nzoho.send_html_email(\n    to=\"recipient@example.com\",\n    subject=\"Newsletter\",\n    html_body=\"<h1>Hello!</h1><p>Welcome!</p>\"\n)\n\n# Method 2: Send HTML with custom plain text version\nzoho.send_email(\n    to=\"recipient@example.com\",\n    subject=\"Newsletter\",\n    body=\"Plain text version of your email\",\n    html_body=\"<h1>Hello!</h1><p>HTML version of your email</p>\"\n)\n\n# Load HTML from template file\nwith open('examples/templates/newsletter.html', 'r') as f:\n    html_content = f.read()\n\nzoho.send_html_email(\n    to=\"recipient@example.com\",\n    subject=\"Monthly Newsletter\",\n    html_body=html_content\n)\n```\n\n**Features:**\n- ✅ Multipart/alternative emails (HTML + plain text)\n- ✅ Auto-generated plain text fallback\n- ✅ Load HTML from files or inline strings\n- ✅ Preview mode to test before sending\n- ✅ Full CSS styling support\n- ✅ Works with all email clients\n\n**Templates:**\nPre-built templates available in `examples/templates/`:\n- `newsletter.html` - Professional newsletter layout\n- `announcement.html` - Important announcements with banners\n- `welcome.html` - Onboarding welcome email\n- `simple.html` - Basic HTML template for quick customization\n\n### Check Unread Count\n\n```bash\npython3 scripts/zoho-email.py unread\n```\n\nPerfect for morning briefings or notification systems.\n\n### Search Inbox\n\n```bash\npython3 scripts/zoho-email.py search \"invoice\"\n```\n\nReturns last 10 matching emails with subject, sender, date, and body preview.\n\n### Search Sent Emails\n\n```bash\npython3 scripts/zoho-email.py search-sent \"client name\"\n```\n\nReturns last 5 matching sent emails.\n\n### Get Specific Email\n\n```bash\npython3 scripts/zoho-email.py get Inbox 4590\npython3 scripts/zoho-email.py get Sent 1234\n```\n\nReturns full email content including complete body.\n\n### Send Email\n\n```bash\npython3 scripts/zoho-email.py send \"client@example.com\" \"Subject\" \"Email body here\"\n```\n\n### Send Email with Attachments\n\n```bash\npython3 scripts/zoho-email.py send \"client@example.com\" \"Invoice\" \"Please find the invoice attached\" --attach invoice.pdf --attach receipt.jpg\n```\n\nSupports multiple attachments with `--attach` flag.\n\n### List Email Attachments\n\n```bash\npython3 scripts/zoho-email.py list-attachments Inbox 4590\n```\n\nReturns JSON with attachment details:\n```json\n[\n  {\n    \"index\": 0,\n    \"filename\": \"invoice.pdf\",\n    \"content_type\": \"application/pdf\",\n    \"size\": 52341\n  },\n  {\n    \"index\": 1,\n    \"filename\": \"receipt.jpg\",\n    \"content_type\": \"image/jpeg\",\n    \"size\": 128973\n  }\n]\n```\n\n### Download Attachment\n\n```bash\n# Download first attachment (index 0) with original filename\npython3 scripts/zoho-email.py download-attachment Inbox 4590 0\n\n# Download second attachment (index 1) with custom filename\npython3 scripts/zoho-email.py download-attachment Inbox 4590 1 my-receipt.jpg\n```\n\nReturns JSON with download details:\n```json\n{\n  \"filename\": \"invoice.pdf\",\n  \"output_path\": \"invoice.pdf\",\n  \"size\": 52341,\n  \"content_type\": \"application/pdf\"\n}\n```\n\n## 🤖 Clawdbot Integration Examples\n\n### Morning Briefing\n\nCheck unread emails and report:\n\n```bash\nUNREAD=$(python3 scripts/zoho-email.py unread | jq -r '.unread_count')\necho \"📧 You have $UNREAD unread emails\"\n```\n\n### Email Monitoring\n\nWatch for VIP emails:\n\n```bash\nRESULTS=$(python3 scripts/zoho-email.py search \"Important Client\")\nCOUNT=$(echo \"$RESULTS\" | jq '. | length')\n\nif [ $COUNT -gt 0 ]; then\n  echo \"⚠️ New email from Important Client!\"\nfi\n```\n\n### Automated Responses\n\nSearch and reply workflow:\n\n```bash\n# Find latest invoice inquiry\nEMAIL=$(python3 scripts/zoho-email.py search \"invoice\" | jq -r '.[0]')\nFROM=$(echo \"$EMAIL\" | jq -r '.from')\n\n# Send reply\npython3 scripts/zoho-email.py send \"$FROM\" \"Re: Invoice\" \"Thanks for your inquiry...\"\n```\n\n### Attachment Workflows\n\nDownload invoice attachments automatically:\n\n```bash\n# Search for invoice emails\nEMAILS=$(python3 scripts/zoho-email.py search \"invoice\")\n\n# Get latest email ID\nEMAIL_ID=$(echo \"$EMAILS\" | jq -r '.[0].id')\n\n# List attachments\nATTACHMENTS=$(python3 scripts/zoho-email.py list-attachments Inbox \"$EMAIL_ID\")\n\n# Download all PDF attachments\necho \"$ATTACHMENTS\" | jq -r '.[] | select(.content_type == \"application/pdf\") | .index' | while read INDEX; do\n  python3 scripts/zoho-email.py download-attachment Inbox \"$EMAIL_ID\" \"$INDEX\" \"invoice_${INDEX}.pdf\"\n  echo \"Downloaded invoice_${INDEX}.pdf\"\ndone\n```\n\nSend report with attachments:\n\n```bash\n# Generate report\npython3 generate_report.py > report.txt\n\n# Send with attachment\npython3 scripts/zoho-email.py send \"manager@example.com\" \"Weekly Report\" \"Please see attached report\" --attach report.txt --attach chart.png\n```\n\n## 📚 Python API\n\nImport the module for programmatic use:\n\n```python\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Search emails\nresults = zoho.search_emails(folder=\"INBOX\", query='SUBJECT \"invoice\"', limit=10)\n\n# Get specific email\nemail = zoho.get_email(folder=\"Sent\", email_id=\"4590\")\n\n# Send plain text email\nzoho.send_email(\n    to=\"client@example.com\",\n    subject=\"Hello\",\n    body=\"Message text\",\n    cc=\"manager@example.com\"  # optional\n)\n\n# Send HTML email (auto-generated plain text fallback)\nzoho.send_html_email(\n    to=\"client@example.com\",\n    subject=\"Newsletter\",\n    html_body=\"<h1>Welcome!</h1><p>Rich HTML content here</p>\",\n    text_body=\"Welcome! Plain text version here\"  # optional, auto-generated if not provided\n)\n\n# Send multipart email (HTML + custom plain text)\nzoho.send_email(\n    to=\"client@example.com\",\n    subject=\"Update\",\n    body=\"Plain text version\",\n    html_body=\"<h1>HTML version</h1>\",\n    cc=\"manager@example.com\"\n)\n\n# Send email with attachments\nzoho.send_email_with_attachment(\n    to=\"client@example.com\",\n    subject=\"Invoice\",\n    body=\"Please find the invoice attached\",\n    attachments=[\"invoice.pdf\", \"receipt.jpg\"],\n    cc=\"manager@example.com\"  # optional\n)\n\n# List attachments\nattachments = zoho.get_attachments(folder=\"INBOX\", email_id=\"4590\")\nfor att in attachments:\n    print(f\"{att['index']}: {att['filename']} ({att['size']} bytes)\")\n\n# Download attachment\nresult = zoho.download_attachment(\n    folder=\"INBOX\",\n    email_id=\"4590\",\n    attachment_index=0,\n    output_path=\"downloaded_file.pdf\"  # optional, uses original filename if not provided\n)\n\n# Check unread count\ncount = zoho.get_unread_count()\n```\n\n## 📖 HTML Email Examples\n\nCheck out the complete example in `examples/send-html-newsletter.py`:\n\n```bash\n# Run the HTML email examples\npython3 examples/send-html-newsletter.py\n```\n\nThis demonstrates:\n- Sending simple inline HTML\n- Loading and sending HTML templates\n- Custom plain text fallbacks\n- Professional email layouts\n\n**Quick Start:**\n```python\n#!/usr/bin/env python3\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Load a template\nwith open('examples/templates/welcome.html', 'r') as f:\n    html = f.read()\n\n# Send to recipient\nzoho.send_html_email(\n    to=\"newuser@example.com\",\n    subject=\"🎉 Welcome to Our Platform!\",\n    html_body=html\n)\n```\n\n## 📁 Folder Reference\n\nCommon Zoho Mail folders:\n\n- `INBOX` - Main inbox\n- `Sent` - Sent emails\n- `Drafts` - Draft emails\n- `Spam` - Spam folder\n- `Trash` - Deleted emails\n- Custom folders (e.g., `INBOX/ClientName`)\n\n## 🔧 Advanced Configuration\n\nOverride default IMAP/SMTP servers (if using Zoho Mail self-hosted):\n\n```bash\nexport ZOHO_IMAP=\"imap.yourdomain.com\"\nexport ZOHO_SMTP=\"smtp.yourdomain.com\"\nexport ZOHO_IMAP_PORT=\"993\"\nexport ZOHO_SMTP_PORT=\"465\"\n```\n\n## ❓ Troubleshooting\n\n### Authentication Failed\n\n- Ensure IMAP is enabled in Zoho Mail settings\n- Use an **app-specific password**, not your main password\n- Verify credentials are properly exported\n\n### Connection Timeout\n\n- Check firewall allows port 993 (IMAP) and 465 (SMTP)\n- Verify Zoho Mail server status\n- Try with a different network (corporate firewalls may block IMAP)\n\n### Search Returns No Results\n\n- IMAP search is case-insensitive\n- Try broader keywords\n- Verify folder name is correct (case-sensitive)\n\n### \"ZOHO_EMAIL and ZOHO_PASSWORD must be set\"\n\nYou forgot to export credentials! Run:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-password\"\n```\n\n## 🛣️ Roadmap\n\n### ✅ Completed (v2.0.0)\n\n- [x] **OAuth2 authentication** - Secure token-based auth with auto-refresh\n- [x] **Zoho Mail REST API** - 5-10x faster than IMAP/SMTP\n- [x] **Attachment support** - Download and send attachments\n- [x] **HTML email composition** - Rich formatting with templates\n- [x] **Batch operations** - Mark, delete, move multiple emails\n- [x] **Bulk actions** - Search and act on many emails at once\n\n### 🔮 Future Enhancements\n\n- [ ] **Email threading/conversations** - Group related emails together\n- [ ] **Label management** - Create and manage Zoho Mail labels\n- [ ] **Draft email management** - Create, edit, and send drafts\n- [ ] **Scheduled sends** - Schedule emails to send later\n- [ ] **Email templates** - Reusable email templates with variables\n- [ ] **Webhooks** - Real-time notifications for new emails\n- [ ] **Advanced search** - Filter by size, has-attachment, date ranges\n- [ ] **Zoho Calendar integration** - Create events from emails\n- [ ] **Zoho CRM integration** - Sync contacts and activities\n\n## 📝 Notes\n\n- **Search limit:** Returns last 5-10 emails by default (configurable in code)\n- **Body truncation:** Search results show first 500 characters\n- **Encoding:** Handles UTF-8 and various email encodings\n- **Security:** Credentials never leave your system except to Zoho servers\n\n## 🤝 Contributing\n\nFound a bug or want to contribute? Submit issues or PRs on GitHub!\n\n## 📄 License\n\nMIT License - free to use, modify, and distribute.\n\n---\n\n**Created:** 2026-01-29  \n**Status:** Production-ready ✅  \n**Requires:** Python 3.x. For REST API mode: `pip install -r requirements.txt` (includes `requests`).\n\n## 🔄 Batch Operations\n\nNew in v1.1! Process multiple emails efficiently with batch commands.\n\n### Mark Multiple Emails as Read\n\n```bash\npython3 scripts/zoho-email.py mark-read INBOX 1001 1002 1003\n```\n\nMark several emails as read in one command. Perfect for clearing notifications.\n\n### Mark Multiple Emails as Unread\n\n```bash\npython3 scripts/zoho-email.py mark-unread INBOX 1004 1005\n```\n\nFlag important emails to revisit later.\n\n### Delete Multiple Emails\n\n```bash\npython3 scripts/zoho-email.py delete INBOX 2001 2002 2003\n```\n\n**Safety:** Asks for confirmation before deleting. Emails are moved to Trash (not permanently deleted).\n\n### Move Emails Between Folders\n\n```bash\npython3 scripts/zoho-email.py move INBOX \"Archive/2024\" 3001 3002 3003\n```\n\nOrganize emails by moving them to custom folders.\n\n### Bulk Actions with Search\n\nPerform actions on all emails matching a search query:\n\n```bash\n# Dry run first - see what would be affected\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action mark-read \\\n  --dry-run\n\n# Execute the action\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action mark-read\n```\n\n**Available actions:**\n- `mark-read` - Mark all matching emails as read\n- `mark-unread` - Mark all matching emails as unread\n- `delete` - Move all matching emails to Trash\n\n**Search query examples:**\n```bash\n# By subject\n--search 'SUBJECT \"invoice\"'\n\n# By sender\n--search 'FROM \"sender@example.com\"'\n\n# Unread emails\n--search 'UNSEEN'\n\n# Combine criteria (AND)\n--search '(SUBJECT \"urgent\" FROM \"boss@company.com\")'\n\n# Date range\n--search 'SINCE 01-Jan-2024'\n```\n\n### Batch Operations in Python\n\n```python\nfrom scripts.zoho_email import ZohoEmail\n\nzoho = ZohoEmail()\n\n# Mark multiple emails as read\nresult = zoho.mark_as_read(['1001', '1002', '1003'], folder=\"INBOX\")\nprint(f\"Success: {len(result['success'])}, Failed: {len(result['failed'])}\")\n\n# Delete multiple emails\nresult = zoho.delete_emails(['2001', '2002'], folder=\"INBOX\")\n\n# Move emails to another folder\nresult = zoho.move_emails(\n    email_ids=['3001', '3002'],\n    target_folder=\"Archive/2024\",\n    source_folder=\"INBOX\"\n)\n\n# Bulk action with search\nresult = zoho.bulk_action(\n    query='SUBJECT \"newsletter\"',\n    action='mark-read',\n    folder=\"INBOX\",\n    dry_run=True  # Preview first\n)\n\nprint(f\"Found {result['total_found']} emails\")\nprint(f\"Will process {result['to_process']} emails\")\n\n# Execute for real\nresult = zoho.bulk_action(\n    query='SUBJECT \"newsletter\"',\n    action='mark-read',\n    folder=\"INBOX\",\n    dry_run=False\n)\n```\n\n### Batch Cleanup Example\n\nClean up old newsletters automatically:\n\n```bash\n# 1. Preview what will be deleted\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action delete \\\n  --dry-run\n\n# 2. Review the preview output\n\n# 3. Execute if satisfied\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action delete\n```\n\nSee `examples/batch-cleanup.py` for a complete automated cleanup script.\n\nFile v2.2.8:examples/templates/README.md\n\n# HTML Email Templates\n\nProfessional, ready-to-use HTML email templates for the Zoho Email skill.\n\n## Available Templates\n\n### 📰 newsletter.html\n**Best for:** Monthly updates, company news, content roundups\n\n**Features:**\n- Modern gradient header\n- Multiple article sections\n- Call-to-action buttons\n- Professional footer\n- Social media links\n\n**Use case:** Send monthly newsletters, product updates, or content digests to subscribers.\n\n### 📢 announcement.html\n**Best for:** Important notifications, system updates, maintenance alerts\n\n**Features:**\n- Bold banner design\n- Highlight boxes for key information\n- Multiple content sections\n- Professional corporate style\n- Clear visual hierarchy\n\n**Use case:** Announce system maintenance, policy changes, or important company news.\n\n### 🎉 welcome.html\n**Best for:** New user onboarding, welcome emails\n\n**Features:**\n- Friendly, welcoming design\n- Step-by-step getting started guide\n- Emoji support\n- Social media integration\n- Engaging call-to-action\n\n**Use case:** Welcome new users, guide them through setup, or introduce your service.\n\n### 📝 simple.html\n**Best for:** Quick, straightforward communications\n\n**Features:**\n- Clean, minimal design\n- Easy to customize\n- Professional signature\n- Good typography\n- Fast to load\n\n**Use case:** General-purpose template for any email, great starting point for custom designs.\n\n## How to Use\n\n### CLI Usage\n\n```bash\n# Send a template\npython3 scripts/zoho-email.py send-html recipient@example.com \"Subject\" examples/templates/newsletter.html\n\n# Preview before sending\npython3 scripts/zoho-email.py preview-html examples/templates/welcome.html\n```\n\n### Python Usage\n\n```python\nfrom scripts.zoho_email import ZohoEmail\n\n# Load template\nwith open('examples/templates/newsletter.html', 'r') as f:\n    html = f.read()\n\n# Send email\nzoho = ZohoEmail()\nzoho.send_html_email(\n    to=\"recipient@example.com\",\n    subject=\"Your Monthly Newsletter\",\n    html_body=html\n)\n```\n\n## Customization Tips\n\n### 1. Replace Placeholder Content\nAll templates contain example text. Simply edit the HTML to replace:\n- Titles and headings\n- Body text and descriptions\n- Links and URLs\n- Footer information\n\n### 2. Change Colors\nEach template uses CSS variables or direct color codes. Search for color codes like:\n- `#667eea` (primary purple)\n- `#764ba2` (secondary purple)\n- `#f5576c` (red accent)\n\nReplace with your brand colors.\n\n### 3. Add Your Logo\nReplace the emoji or text in the header with your logo:\n```html\n<img src=\"https://your-site.com/logo.png\" alt=\"Logo\" style=\"max-width: 200px;\">\n```\n\n### 4. Update Links\nReplace all `href=\"#\"` with actual URLs:\n```html\n<a href=\"https://your-site.com/pricing\">View Pricing</a>\n```\n\n### 5. Modify Layout\nEach template uses inline CSS and modern layout techniques. Feel free to:\n- Add/remove sections\n- Adjust padding and margins\n- Change font sizes\n- Modify button styles\n\n## Email Client Compatibility\n\nAll templates are designed with maximum compatibility:\n- ✅ Gmail (Web, Mobile, App)\n- ✅ Outlook (Desktop, Web, Mobile)\n- ✅ Apple Mail (macOS, iOS)\n- ✅ Yahoo Mail\n- ✅ Proton Mail\n- ✅ Other modern email clients\n\n**Features used:**\n- Inline CSS (best compatibility)\n- Table-based layouts where needed\n- Web-safe fonts with fallbacks\n- Tested color schemes\n- Mobile-responsive design\n\n## Best Practices\n\n### DO ✅\n- Keep HTML under 100KB for best deliverability\n- Use inline CSS instead of `<style>` tags when possible\n- Test with multiple email clients\n- Include plain text fallback (automatic with this skill)\n- Use web-safe fonts (Arial, Helvetica, Georgia, etc.)\n- Optimize images before including\n\n### DON'T ❌\n- Use JavaScript (not supported in emails)\n- Rely solely on external stylesheets\n- Use video or audio embeds\n- Include forms (limited support)\n- Use complex CSS animations\n- Forget to test on mobile devices\n\n## Creating Your Own Templates\n\nStart with `simple.html` and customize:\n\n1. **Copy the template:**\n   ```bash\n   cp examples/templates/simple.html examples/templates/my-template.html\n   ```\n\n2. **Edit the content:**\n   - Update title and headings\n   - Add your content sections\n   - Customize colors and styles\n\n3. **Test it:**\n   ```bash\n   python3 scripts/zoho-email.py preview-html examples/templates/my-template.html\n   ```\n\n4. **Send it:**\n   ```bash\n   python3 scripts/zoho-email.py send-html test@example.com \"Test\" examples/templates/my-template.html\n   ```\n\n## Template Structure\n\nAll templates follow this structure:\n```html\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Email Title</title>\n    <style>\n        /* Inline styles for compatibility */\n    </style>\n</head>\n<body>\n    <!-- Email content -->\n</body>\n</html>\n```\n\n## Resources\n\n- **Email on Acid:** Test rendering across clients\n- **Litmus:** Professional email testing\n- **Can I Email:** Check CSS support in email clients\n- **HTML Email Template Generator:** Create custom templates\n\n## Support\n\nFor questions or issues with templates:\n1. Check `SKILL.md` for general documentation\n2. Review `HTML_FEATURE.md` for implementation details\n3. Run preview mode to debug: `preview-html <template>`\n4. Check MIME structure with `--verbose` flag\n\n---\n\n**Templates Created:** January 29, 2026  \n**Compatible With:** Zoho Email Skill v1.0+  \n**License:** MIT (Free to use and customize)\n\nFile v2.2.8:README.md\n\n# Zoho Email Integration for Clawdbot\n\n[![GitHub](https://img.shields.io/badge/GitHub-clawdbot--zoho--email-blue?logo=github)](https://github.com/briansmith80/clawdbot-zoho-email)\n[![ClawdHub](https://img.shields.io/badge/ClawdHub-Install-green)](https://clawdhub.com)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Version](https://img.shields.io/badge/version-2.2.8-blue)](https://github.com/briansmith80/clawdbot-zoho-email/releases)\n[![Security](https://img.shields.io/badge/security-hardened-brightgreen)](SECURITY.md)\n\n**v2.2.8** - Complete Zoho Mail integration with OAuth2, REST API backend (5-10x faster), **Clawdbot extension with /email commands**, and advanced email automation features. Perfect for email workflows, monitoring, and bulk operations in your Clawdbot projects.\n\n## 🔒 Security Notice (v2.2.0)\n\n**SECURITY UPDATE:** This version fixes critical vulnerabilities identified in security audit. **Upgrade recommended for all users.**\n\n**Fixed vulnerabilities:**\n- ✅ **CRITICAL:** Command injection in JavaScript handler\n- ✅ **HIGH:** Metadata mismatch (credential requirements)\n- ✅ **MEDIUM:** Insufficient input validation\n- ✅ **LOW:** Token file permission enforcement\n\n**See [SECURITY.md](SECURITY.md) for details and migration guide.**\n\n## 🚀 Quick Start (recommended path)\n\n```bash\n# 1) Install\nclawdhub install zoho-email\ncd zoho-email  # (or wherever ClawdHub installed it)\n\n# 2) Install Python deps (needed for REST API mode)\npip3 install -r requirements.txt\n\n# 3) Set your mailbox (required for both OAuth + app-password modes)\nexport ZOHO_EMAIL=\"your-email@domain.com\"\n\n# 4) OAuth2 setup (recommended: enables REST API + auto token refresh)\npython3 scripts/oauth-setup.py\n\n# 5) Sanity-check everything\npython3 scripts/zoho-email.py doctor\n\n# 6) Test\npython3 scripts/zoho-email.py unread\n```\n\n### Quick Start (app-password mode)\nIf you don't want OAuth2 yet:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\"\npython3 scripts/zoho-email.py doctor\npython3 scripts/zoho-email.py unread --api-mode imap\n```\n\n**OAuth token location (default):** `~/.clawdbot/zoho-mail-tokens.json`\n\n\n## ✨ Features\n\n### Core Features\n✅ **OAuth2 Authentication** - Secure authentication with automatic token refresh\n✅ **REST API Backend** - 5-10x faster than IMAP/SMTP (auto-enabled with OAuth2)\n✅ **Read & Search** - Search emails with advanced filters\n✅ **Send Emails** - Plain text, HTML, CC/BCC support\n✅ **Attachments** - Send and download attachments\n✅ **HTML Emails** - Send rich-formatted emails with templates\n✅ **Batch Operations** - Mark, delete, move multiple emails efficiently\n✅ **Folder Management** - Access all folders (Inbox, Sent, Drafts, etc.)\n\n### Performance\n⚡ **5-10x faster** operations with REST API mode\n⚡ **Connection pooling** for persistent HTTP connections\n⚡ **Server-side filtering** reduces data transfer\n⚡ **Automatic fallback** to IMAP if REST API unavailable\n\n## 📚 Documentation\n\n- **[SKILL.md](SKILL.md)** - Complete guide with examples\n- **[OAUTH2_SETUP.md](OAUTH2_SETUP.md)** - OAuth2 setup instructions\n- **[SECURITY.md](SECURITY.md)** - Security best practices and audit results\n- **[CHANGELOG.md](CHANGELOG.md)** - Version history\n\n## 🔒 Security & Best Practices\n\n**Credential Management:**\n- ✅ Use OAuth2 (recommended) or app-specific passwords only\n- ✅ Never use your main Zoho password\n- ✅ Token files automatically secured with 0600 permissions\n- ✅ Never commit credentials to version control\n\n**Command Handler Security (if exposing /email commands):**\n- ✅ Use `email-command-SECURE.js` (prevents command injection)\n- ✅ Restrict command access to authorized users only\n- ✅ Add rate limiting at bot level\n- ✅ Enable audit logging for sensitive operations\n\n**Verification:**\n```bash\n# Check token file permissions (should be 600)\nls -la ~/.clawdbot/zoho-mail-tokens.json\n\n# Fix if needed\nchmod 600 ~/.clawdbot/zoho-mail-tokens.json\n```\n\n**See [SECURITY.md](SECURITY.md) for complete security guide.**\n\n## 📖 Quick Examples\n\n### Most common Clawdbot-style actions\n```bash\n# Unread count (fast, good for briefings)\npython3 scripts/zoho-email.py unread\n\n# Search inbox\npython3 scripts/zoho-email.py search \"invoice\"\n\n# Read a specific email (folder + id)\npython3 scripts/zoho-email.py get INBOX <id>\n\n# Send a simple email\npython3 scripts/zoho-email.py send recipient@example.com \"Subject\" \"Body text\"\n\n# Empty Spam (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-spam\n# Execute for real\npython3 scripts/zoho-email.py empty-spam --execute\n\n# Empty Trash (safe by default: DRY RUN)\npython3 scripts/zoho-email.py empty-trash\n# Execute for real\npython3 scripts/zoho-email.py empty-trash --execute\n```\n\n\n### Basic Operations\n```bash\n# Get unread count\npython3 scripts/zoho-email.py unread\n\n# Search emails\npython3 scripts/zoho-email.py search \"important meeting\"\n\n# Send email\npython3 scripts/zoho-email.py send recipient@example.com \"Subject\" \"Message body\"\n```\n\n### HTML Emails (v1.1.0+)\n```bash\n# Send HTML email from template\npython3 scripts/zoho-email.py send-html user@example.com \"Newsletter\" templates/newsletter.html\n\n# Preview HTML before sending\npython3 scripts/zoho-email.py preview-html templates/welcome.html\n```\n\n### Attachments (v1.1.0+)\n```bash\n# Send with attachments\npython3 scripts/zoho-email.py send user@example.com \"Report\" \"See attached\" --attach report.pdf --attach data.xlsx\n\n# List attachments in an email\npython3 scripts/zoho-email.py list-attachments Inbox 4590\n\n# Download attachment\npython3 scripts/zoho-email.py download-attachment Inbox 4590 0 ./report.pdf\n```\n\n### Batch Operations (v1.1.0+)\n```bash\n# Mark multiple emails as read\npython3 scripts/zoho-email.py mark-read INBOX 1001 1002 1003\n\n# Delete multiple emails (with confirmation)\npython3 scripts/zoho-email.py delete INBOX 2001 2002 2003\n\n# Move emails to folder\npython3 scripts/zoho-email.py move INBOX \"Archive/2024\" 3001 3002\n\n# Bulk action with search\npython3 scripts/zoho-email.py bulk-action \\\n  --folder INBOX \\\n  --search 'SUBJECT \"newsletter\"' \\\n  --action mark-read \\\n  --dry-run\n```\n\n### OAuth2 & REST API (v1.2.0+, v2.0.0+)\n```bash\n# Set up OAuth2 (one-time)\npython3 scripts/oauth-setup.py\n\n# Check OAuth2 status\npython3 scripts/zoho-email.py oauth-status\n\n# Force REST API mode (5-10x faster)\npython3 scripts/zoho-email.py unread --api-mode rest --verbose\n\n# Force IMAP mode (compatibility)\npython3 scripts/zoho-email.py unread --api-mode imap\n```\n\n## 🧩 Clawdbot Integration (NEW!)\n\n### /email Commands (Telegram, Discord, etc.)\n\nUse email directly in Clawdbot messaging platforms via `/email` commands:\n\n```bash\n# Check unread count\n/email unread\n\n# Search your inbox\n/email search invoice\n\n# Send an email\n/email send john@example.com \"Hello\" \"Hi John\"\n\n# Brief summary (for briefings)\n/email summary\n\n# Diagnostics\n/email doctor\n\n# Get help\n/email help\n```\n\n**Setup:**\n1. Copy `examples/clawdbot-extension/clawdbot_extension.py` to your scripts directory\n2. Set `ZOHO_EMAIL` environment variable\n3. Run OAuth2 setup: `python3 scripts/oauth-setup.py`\n4. Test: `python3 scripts/clawdbot_extension.py unread`\n\n### Heartbeat/Cron Integration\n\nAdd email summary to morning briefings or scheduled tasks:\n\n```bash\n# In your heartbeat/cron script\npython3 scripts/clawdbot_extension.py summary\n\n# Output: 📭 No unread emails\n#     OR: 📧 3 unread emails\n```\n\n**Examples:**\n- `examples/clawdbot-extension/heartbeat-example.md` - Complete integration guide\n- `examples/clawdbot-commands/emails.sh` - Simple wrapper script\n\n### Use Cases\n✅ **Morning briefings** - Add email summary to daily briefing  \n✅ **Slack/Discord alerts** - Notify on unread emails  \n✅ **Interactive commands** - `/email search invoice` in chat  \n✅ **Automated workflows** - Cron + Clawdbot integration\n\n## 💡 Use Cases\n\n- **Morning briefings** - Automated unread email summaries\n- **Email monitoring** - Watch for VIP senders or keywords\n- **Newsletter cleanup** - Bulk-mark newsletters as read\n- **Automated responses** - Search and reply to specific emails\n- **Email archiving** - Move old emails to archive folders\n- **Notifications** - Alert when important emails arrive\n- **HTML campaigns** - Send rich-formatted newsletters\n- **Attachment workflows** - Download invoices, reports automatically\n\n## 🔧 Requirements\n\n**Minimum:**\n- Python 3.x\n- Zoho Mail account\n- App-specific password OR OAuth2 setup\n\n**Optional (for REST API mode):**\n- `requests>=2.31.0` (install: `pip3 install -r requirements.txt`)\n- OAuth2 credentials (automatic 5-10x performance boost)\n\n## 📦 Version History\n\n- **v2.0.0** (2025-01-29) - REST API backend with 5-10x performance boost\n- **v1.2.0** (2025-01-29) - OAuth2 authentication with automatic token refresh\n- **v1.1.0** (2025-01-29) - HTML emails, attachments, batch operations\n- **v1.0.0** (2025-01-29) - Initial IMAP/SMTP implementation\n\nSee [CHANGELOG.md](CHANGELOG.md) for complete version history.\n\n## 🤝 Contributing\n\nContributions are welcome! Here's how you can help:\n\n- 🐛 **Report bugs:** [Open an issue](https://github.com/briansmith80/clawdbot-zoho-email/issues)\n- 💡 **Request features:** [Open an issue](https://github.com/briansmith80/clawdbot-zoho-email/issues)\n- 🔧 **Submit PRs:** [Pull requests](https://github.com/briansmith80/clawdbot-zoho-email/pulls)\n- ⭐ **Star the repo:** Show your support!\n\nThis is an open-source Clawdbot skill maintained by the community.\n\n## 📄 License\n\nMIT License - see [LICENSE](LICENSE) for details.\n\n---\n\n**Part of the Clawdbot ecosystem** | [ClawdHub](https://clawdhub.com) | [Documentation](SKILL.md)\n\nFile v2.2.8:_meta.json\n\n{\n  \"ownerId\": \"kn780decc8bavz0r6qen0513xh804z45\",\n  \"slug\": \"zoho-email-integration\",\n  \"version\": \"2.2.8\",\n  \"publishedAt\": 1772189925869\n}\n\nFile v2.2.8:CHANGELOG.md\n\n# Changelog\n\nAll notable changes to the Zoho Email Integration skill will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [2.2.8] - 2026-02-27\n\n### Fixed\n\n- **Zoho JP regional IMAP compatibility** — Fixed `UnicodeDecodeError` when connecting to `imap.zoho.jp` and other regional servers that return non-ASCII bytes (NBSP `\\xc2\\xa0`) in their CAPABILITY response during the initial TLS handshake.\n\n  **Root cause:** Python's `imaplib` uses ASCII decoding by default. Regional Zoho servers send a non-breaking space character in the CAPABILITY greeting, which crashes the ASCII decoder before authentication can begin.\n\n  **Fix:** `PatchedIMAP4_SSL` now overrides `open()` to set UTF-8 encoding before the server greeting is read. UTF-8 is a strict superset of ASCII, so this is fully backwards-compatible with all servers.\n\n  **Note:** v2.2.7 included a community contribution (thanks @SenorToru) that identified and described this bug correctly, but had an implementation error — `_get_capabilities` was defined as a standalone function and never bound to the class, making the fix a no-op. This release corrects that.\n\n---\n\n## [2.2.5] - 2026-02-14\n\n### 🔒 CRITICAL SECURITY FIX\n\n**Vulnerable JavaScript handler removed from distribution.**\n\n#### Fixed\n\n- **CRITICAL: Removed vulnerable email-command.js** - The examples/clawdbot-extension/ directory contained both a vulnerable (`email-command.js`) and secure (`email-command-SECURE.js`) version of the JavaScript command handler. The vulnerable file used `execSync` with shell interpolation, allowing command injection. The secure version using `spawn` with argument arrays is now the default `email-command.js`.\n\n  **Impact:** Remote code execution if the vulnerable handler was deployed and user input was processed through /email commands.\n  \n  **Fix:** \n  - Deleted vulnerable `email-command.js` \n  - Renamed `email-command-SECURE.js` to `email-command.js`\n  - Only the secure handler (using `spawn` with argument arrays) now ships\n\n#### Upgrade Urgency\n**IMMEDIATE** - If you deployed the JavaScript handler from examples/, replace it with the new secure version.\n\n---\n\n## [2.2.1] - 2026-02-12\n\n### 🔒 CRITICAL SECURITY FIXES\n\n**Three additional security vulnerabilities discovered and fixed:**\n\n#### Fixed\n\n- **CRITICAL: Path traversal in attachment download** - The `download_attachment()` function in `scripts/zoho-email.py` used untrusted email attachment filenames directly for file writes. An attacker could send a malicious email with attachment name `../../../../etc/cron.d/backdoor` to write arbitrary files anywhere on the system, leading to remote code execution or privilege escalation.\n  \n  **Fix:** Implemented `_sanitize_filename()` function that:\n  - Strips all directory path components\n  - Removes null bytes and dangerous characters\n  - Prevents hidden files (leading dots)\n  - Limits filename length to 200 characters\n  - Only uses safe basenames for file writes\n\n- **HIGH: Command injection in test script** - The `test-app-password.sh` script used `eval` with environment variables (`TEST_EMAIL`), allowing command injection via malicious email addresses like `user@example.com'; rm -rf /; echo '`.\n  \n  **Fix:** \n  - Added email format validation with regex before any execution\n  - Replaced `eval` with safer `bash -c` for command execution\n  - Test script now exits immediately on invalid email format\n\n- **All v2.2.0 fixes included** (see v2.2.0 below)\n\n#### Security Impact\n- **Path traversal** → Remote code execution, privilege escalation, data exfiltration\n- **Test script injection** → Arbitrary command execution during testing\n- **JavaScript handler injection** → Same as v2.2.0\n\n#### Upgrade Urgency\n**IMMEDIATE** - All users should upgrade to v2.2.1, especially if:\n- Downloading email attachments from untrusted senders\n- Running test scripts in automated environments\n- Exposing `/email` commands to users\n\n#### Migration\n```bash\n# Upgrade skill\nclawdhub install zoho-email-integration@2.2.1\n\n# No configuration changes required\n# Existing code fully backward compatible\n```\n\n#### Disclosure\n- Vulnerabilities reported by ClawHub security scanner\n- Fixed within 2 hours of disclosure\n- No known exploitation in the wild\n- Coordinated disclosure: SECURITY.md published with fix\n\n---\n\n## [2.2.0] - 2026-02-12\n\n### 🔒 SECURITY FIXES\n\n**Critical security vulnerabilities addressed based on ClawHub security audit:**\n\n#### Fixed\n- **CRITICAL: Command injection in JavaScript handler** - Original `email-command.js` used shell command interpolation with user-supplied arguments, allowing potential command injection attacks. Replaced with `spawn()` using argument arrays (no shell interpretation).\n  \n- **HIGH: Metadata mismatch** - Registry metadata incorrectly claimed \"no credentials required\" when ZOHO_EMAIL + authentication is actually required. Updated `clawhub.json` with accurate credential declarations.\n\n- **MEDIUM: Insufficient input validation** - Added comprehensive input sanitization:\n  - Email address format validation\n  - Shell metacharacter filtering\n  - Length limits (1000 char max)\n  - Newline/carriage return removal\n\n- **LOW: Token file permission enforcement** - Added automatic permission checks and correction to enforce 0600 on token files (owner read/write only).\n\n#### Added\n- **`email-command-SECURE.js`** - Hardened version of JavaScript handler with security fixes\n- **`SECURITY.md`** - Comprehensive security advisory and best practices guide\n- **`clawhub.json`** - Proper ClawHub metadata with credential declarations\n- Automatic token file permission verification on handler initialization\n- Input sanitization for all user-provided arguments\n- Email address validation\n- Security checklist and deployment guidelines\n\n#### Changed\n- JavaScript handler now uses `spawn()` instead of `execSync()` to prevent shell injection\n- All user inputs are sanitized before processing\n- Token file permissions automatically enforced\n- Enhanced error messages with security context\n\n#### Security Notes\n- **Upgrade recommended for all users, especially if exposing /email commands to untrusted users**\n- No data migration required - drop-in replacement\n- See SECURITY.md for detailed vulnerability descriptions and mitigation steps\n\n#### Migration\n```bash\n# Update to secure handler\ncp examples/clawdbot-extension/email-command-SECURE.js \\\n   examples/clawdbot-extension/email-command.js\n\n# Verify token permissions\nchmod 600 ~/.clawdbot/zoho-mail-tokens.json\n```\n\n---\n\n## [2.1.0] - 2026-02-06\n\n### ✨ NEW - Clawdbot Extension & Commands\n\n**First-class Clawdbot integration with `/email` commands:**\n\n#### Added\n- **`clawdbot_extension.py`** - New extension module for Clawdbot integration\n  - `/email unread` - Check unread email count\n  - `/email summary` - Brief summary for briefings\n  - `/email search <query>` - Search emails from chat\n  - `/email send <to> <subject> <body>` - Send emails from chat\n  - `/email doctor` - Check setup/connectivity\n  - `/email help` - Command help\n  \n- **Clawdbot command handlers** - Ready-to-use implementations\n  - `email_command.py` - Python handler for Clawdbot CLI\n  - `email-command.js` - JavaScript handler (Node.js)\n  \n- **Heartbeat integration examples** - `heartbeat-example.md`\n  - Morning briefing integration\n  - Email monitoring (alert on new unread)\n  - Cron job examples\n  - Complete walkthrough with shell scripts\n\n#### Features\n- Formatted output for Telegram/Discord/Slack (emoji, bold text, etc.)\n- Graceful error handling with helpful messages\n- Direct messaging platform integration\n- Works with OAuth2 and app-password auth\n- No external dependencies (uses existing `zoho_email.py`)\n\n#### Documentation\n- Updated README with Clawdbot integration section\n- New heartbeat/cron integration guide\n- Examples for morning briefings, monitoring, bulk actions\n\n#### Use Cases\n- ✅ `/email unread` in Telegram chat\n- ✅ Discord bot commands\n- ✅ Slack integration\n- ✅ Morning briefing summaries\n- ✅ Alert on important emails\n- ✅ Scheduled cleanups\n\n### Impact\n**User Experience: 8.5/10 → 9.5/10**\n- Email commands now work directly in messaging (Telegram/Discord)\n- No longer need to remember Python commands\n- Integrated with existing Clawdbot workflows\n- Better error messages with context\n\n## [2.0.3] - 2026-01-31\n\n### ✅ UX / Quality of Life\n- **ClawdHub-friendly naming**: aligned docs + skill metadata to `clawdhub install zoho-email`\n- **`--help` without configuration**: help no longer requires credentials/tokens\n- **`doctor` command**: first-run diagnostics (env vars, token file, REST reachability, IMAP/SMTP reachability)\n- **Standardised token location**: default is now `~/.clawdbot/zoho-mail-tokens.json`\n- **Convenience cleanup commands**:\n  - `empty-spam` (dry-run by default, `--execute` to run)\n  - `empty-trash` (dry-run by default, `--execute` to run)\n- **Docs cleanup**: removed broken README links, added practical quick start + common task commands\n- **Clawdbot wrapper example**: added `examples/clawdbot-commands/emails.sh`\n\n## [2.0.2] - 2026-01-29\n\n### 📝 Documentation - Updated SKILL.md Introduction\n\n**Updated skill description to accurately reflect v2.0 capabilities:**\n\n#### Changed\n- **Updated intro** - Changed outdated \"IMAP/SMTP only\" description to highlight OAuth2 and REST API features\n- **Reorganized features** - Grouped into Authentication & Performance, Email Operations, Batch & Bulk Operations, Security\n- **Emphasized performance** - Highlighted 5-10x speed improvement with REST API mode\n- **Corrected installation** - Fixed package name references (current install slug: `zoho-email`)\n- **Added requirements** - Listed Python 3.x, requests library, and Zoho Mail account\n\nThis ensures users immediately see the modern features (OAuth2, REST API, HTML, batch ops) instead of the old v1.0 IMAP/SMTP-only description.\n\n## [2.0.1] - 2026-01-29\n\n### 🐛 Fixed - REST API Batch Operations\n\n**Critical bug fixes for REST API mode + updated documentation:**\n\n#### Fixed\n- **Mark as read/unread operations** - Fixed 404 errors by using correct `/updatemessage` endpoint with `mode` parameter\n- **HTML email NameError** - Removed orphaned code that caused \"name 'email_id' is not defined\" error\n- **Delete operation** - Added missing folder ID parameter required by API\n- **Move operation** - Fixed endpoint to use `/updatemessage` with proper mode and folder lookup\n- **Batch operations** - All operations now batch multiple messages in single API calls (90% reduction in API usage)\n\n#### Changed\n- REST API methods now use folder name-to-ID lookup for consistency with IMAP mode\n- Batch operations consolidated into single API requests instead of individual calls\n- Improved error messages for folder not found cases\n\n#### Technical Details\n- Endpoint changed from `PUT /accounts/{id}/messages/{id}` to `PUT /accounts/{id}/updatemessage`\n- Delete endpoint now uses `DELETE /accounts/{id}/folders/{folderId}/messages/{id}`\n- All message IDs converted to integers for API compatibility\n- Added folder caching via `list_folders()` for efficient lookups\n\n#### Documentation\n- **Updated roadmap** - Marked OAuth2, REST API, attachments, HTML emails, and batch operations as completed\n- **Added future enhancements** - Listed realistic future features (threading, labels, webhooks, scheduled sends, etc.)\n- **Cleaned up repository** - Removed 29 internal development docs, keeping only essential user-facing files\n\nSee [FIXES_COMPLETE.md](FIXES_COMPLETE.md) for detailed technical documentation.\n\n## [2.0.0] - 2026-01-29\n\n### 🚀 Added - REST API Backend Implementation\n\n**Major performance upgrade: 5-10x faster operations with REST API support!**\n\n### Added - REST API Features\n- **ZohoRestAPIClient class** - Complete REST API client with OAuth2 authentication\n- **Connection pooling** - Persistent HTTP connections using requests.Session\n- **Automatic token refresh** - Seamless token refresh on expiration\n- **Rate limiting** - Built-in rate limiting with exponential backoff\n- **Retry logic** - Automatic retry on 429/5xx errors\n- **API mode auto-detection** - Automatically uses REST API when OAuth2 is available\n- **Graceful fallback** - Falls back to IMAP/SMTP if REST API fails\n- **100% backward compatibility** - All existing code works unchanged\n\n### Added - REST API Client Methods\n- `list_messages()` - List emails with server-side filtering\n- `get_message()` - Get specific message by ID\n- `send_message()` - Send emails via REST API\n- `mark_as_read()` - Mark messages as read\n- `mark_as_unread()` - Mark messages as unread\n- `delete_messages()` - Delete messages (move to trash)\n- `move_messages()` - Move messages between folders\n- `list_folders()` - List all folders\n- `get_account_id()` - Get Zoho Mail account ID\n\n### Added - API Mode Support\n- `--api-mode <mode>` CLI flag - Force 'auto', 'rest', or 'imap' mode\n- `api_mode` parameter in `ZohoEmail.__init__()`\n- Auto-detection: Uses REST API if OAuth2 + requests library available\n- Force REST: `--api-mode rest` (requires OAuth2)\n- Force IMAP: `--api-mode imap` (works with any auth)\n\n### Modified - Updated Methods with REST API Support\n- `get_unread_count()` - Uses REST API when available\n- `search_emails()` - Uses REST API list_messages with query conversion\n- `send_email()` - Uses REST API send_message when available\n- `mark_as_read()` - Uses REST API batch operations\n- `mark_as_unread()` - Uses REST API batch operations\n- `delete_emails()` - Uses REST API delete operations\n- `move_emails()` - Uses REST API move operations\n\n### Added - Dependencies\n- `requests>=2.31.0` - Required for REST API mode\n\n### Added - Environment Variables\n- `ZOHO_API_BASE_URL` - REST API base URL (default: https://mail.zoho.com/api)\n- `ZOHO_API_TIMEOUT` - REST API timeout in seconds (default: 30)\n- `ZOHO_API_RATE_DELAY` - Delay between requests in seconds (default: 0.5)\n- `ZOHO_MAX_RETRIES` - Maximum retry attempts (default: 3)\n\n### Added - Documentation\n- `REST_API_IMPLEMENTATION.md` - Implementation details and code summary\n\n### Performance Improvements\n- **5-10x faster** operations with REST API\n- **Connection pooling** - Reuses HTTP connections\n- **Server-side filtering** - Reduces data transfer\n- **Batch operations** - More efficient than IMAP\n\n### Technical Details\n- Added `has_requests_library()` helper function\n- REST API client uses requests.Session for connection pooling\n- Automatic OAuth2 bearer token injection\n- Rate limiting with configurable delay\n- Exponential backoff on failures\n- Token refresh before expiration (5-minute buffer)\n- Graceful error handling with IMAP fallback\n\n## [1.2.0] - 2026-01-29\n\n### 🔐 Added - OAuth2 Authentication Support\n\n**Secure OAuth2 authentication with automatic token management!**\n\n### Added - OAuth2 Features\n- **OAuth2 authorization code flow** - Interactive browser-based login\n- **Automatic token refresh** - Access tokens refresh automatically when expired\n- **Secure token storage** - Tokens stored in `~/.clawdbot/zoho-mail-tokens.json` with 600 permissions\n- **Token management CLI** - Commands to check status, refresh, and revoke tokens\n- **IMAP XOAUTH2 support** - OAuth2 authentication for IMAP connections\n- **SMTP XOAUTH2 support** - OAuth2 authentication for SMTP connections\n- **Backward compatibility** - App passwords still work, auto-detection of auth method\n- **No external dependencies** - Uses Python standard library only\n\n### Added - New Commands\n- `oauth-status` - Check OAuth2 token validity and expiration\n- `oauth-login` - Manually refresh OAuth2 tokens\n- `oauth-revoke` - Revoke OAuth2 access (delete token file)\n\n### Added - New CLI Flags\n- `--auth <method>` - Specify authentication method: 'auto' (default), 'password', or 'oauth2'\n- `--token-file <path>` - Custom OAuth2 token file path (default: ~/.clawdbot/zoho-mail-tokens.json)\n\n### Added - OAuth2 Setup Tool\n- `scripts/oauth-setup.py` - Interactive OAuth2 setup wizard\n  - Browser-based authorization flow\n  - Automatic callback handling\n  - Secure token storage\n  - Token refresh support\n  - Status checking\n\n### Added - Python API Methods\n- `ZohoEmail(auth_method='oauth2')` - OAuth2 authentication mode\n- `refresh_token()` - Manually refresh OAuth2 access token\n- `revoke_token()` - Revoke and delete OAuth2 tokens\n- `get_token_status()` - Check token validity and expiration\n\n### Added - Documentation\n- `OAUTH2_SETUP.md` - Complete OAuth2 setup guide with troubleshooting\n- `OAUTH2_FEATURE.md` - Comprehensive feature documentation\n- `OAUTH2_COMPLETE.md` - Implementation summary\n- Updated `SKILL.md` with OAuth2 section\n- Updated `README.md` with OAuth2 information\n\n### Security Improvements\n- **No password storage** - OAuth2 eliminates password storage\n- **Token-based auth** - Short-lived access tokens (1 hour)\n- **Auto-refresh** - Seamless token renewal\n- **Revocable access** - Easy to revoke without changing passwords\n- **Secure file permissions** - Token files enforced to 600\n- **Zoho-recommended** - Official authentication method\n\n### Changed\n- Auto-detection now prefers OAuth2 if token file exists\n- IMAP/SMTP connection methods updated to support XOAUTH2\n- Help text updated with OAuth2 commands and options\n- Error messages now mention both auth methods\n\n### Backward Compatibility\n- ✅ App passwords still fully supported\n- ✅ All existing commands work unchanged\n- ✅ No breaking changes to CLI or Python API\n- ✅ Auto-detection fallsback to app password if no OAuth2 tokens\n- ✅ Existing scripts require no modifications\n\n### Migration Path\n1. Run `python3 scripts/oauth-setup.py` to configure OAuth2\n2. Test with `--auth oauth2` flag\n3. Once working, auto-mode uses OAuth2 automatically\n4. Optionally remove app password: `unset ZOHO_PASSWORD`\n\n### Performance\n- Negligible runtime overhead (<100ms for token check)\n- Automatic token refresh only when needed\n- No impact on IMAP/SMTP performance\n\n### Known Limitatio\n\nArchive v2.2.7: 33 files, 92326 bytes\n\nFiles: CHANGELOG.md (20400b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command.js (10065b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (96981b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (18620b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nArchive v2.2.6: 33 files, 92325 bytes\n\nFiles: CHANGELOG.md (20400b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command.js (10065b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (96981b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (18620b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nArchive v2.2.5: 33 files, 92049 bytes\n\nFiles: CHANGELOG.md (20400b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command.js (10065b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (96981b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (17942b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nArchive v2.2.4: 34 files, 94205 bytes\n\nFiles: CHANGELOG.md (19396b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command-SECURE.js (10065b), examples/clawdbot-extension/email-command.js (6479b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (96981b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (17942b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nArchive v2.2.3: 34 files, 94223 bytes\n\nFiles: CHANGELOG.md (19396b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command-SECURE.js (10065b), examples/clawdbot-extension/email-command.js (6479b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (96981b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (17958b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nArchive v2.2.2: 34 files, 94136 bytes\n\nFiles: CHANGELOG.md (19396b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command-SECURE.js (10065b), examples/clawdbot-extension/email-command.js (6479b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (96981b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (7128b), SKILL.md (17742b), test-app-password.sh (4886b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nArchive v2.2.1: 34 files, 90812 bytes\n\nFiles: CHANGELOG.md (17238b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command-SECURE.js (10065b), examples/clawdbot-extension/email-command.js (6479b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (93713b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (4730b), SKILL.md (17596b), test-app-password.sh (4286b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)\n\nArchive v2.2.0: 34 files, 90812 bytes\n\nFiles: CHANGELOG.md (17238b), examples/attachment-demo.py (5178b), examples/auto-reply.py (1339b), examples/batch-cleanup.py (5984b), examples/clawdbot-commands/emails.sh (1221b), examples/clawdbot-extension/email_command.py (2679b), examples/clawdbot-extension/email-command-SECURE.js (10065b), examples/clawdbot-extension/email-command.js (6479b), examples/clawdbot-extension/heartbeat-example.md (5967b), examples/morning-briefing.sh (538b), examples/send-html-newsletter.py (4029b), examples/templates/announcement.html (4522b), examples/templates/newsletter.html (3141b), examples/templates/README.md (5426b), examples/templates/simple.html (1672b), examples/templates/welcome.html (5564b), examples/vip-monitor.sh (854b), OAUTH2_SETUP.md (11035b), README.md (9728b), requirements.txt (910b), scripts/add_oauth_cli.py (5629b), scripts/apply_oauth2_cli.py (7011b), scripts/apply_oauth2.py (15624b), scripts/clawdbot_extension.py (8146b), scripts/oauth-setup.py (13889b), scripts/zoho-email.py (93713b), SECURITY-AUDIT-SUMMARY.md (8349b), SECURITY.md (4730b), SKILL.md (17596b), test-app-password.sh (4286b), test-batch-operations.sh (2628b), test-rest-api-fixes.sh (3740b), test.sh (2019b), _meta.json (141b)","readmeExcerpt":"Skill: Zoho Email Integration Owner: briansmith80 Summary: Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-harde... Tags: latest:2.2.9, security-fix:2.2.7 Version history: v2.2.9 | 2026-02-27T11:10:56.598Z | user Docs: Fix clawhub/clawdhub naming inconsistencies — correct CLI name, slug, badge URL, and version refe","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"clawhub install zoho-email-integration --force"},{"language":"bash","snippet":"clawhub update"},{"language":"bash","snippet":"# Re-download the secure handler\nclawhub install zoho-email-integration --force\ncp ~/.openclaw/skills/zoho-email-integration/examples/clawdbot-extension/email-command.js /your/deployment/path/"},{"language":"bash","snippet":"clawhub install zoho-email-integration"},{"language":"bash","snippet":"export ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\""},{"language":"bash","snippet":"#!/bin/bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\""}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: zoho-email-integration\ndescription: Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-hardened against path traversal and command injection. Perfect for email automation and workflows.\nhomepage: https://github.com/briansmith80/clawdbot-zoho-email\nmetadata:\n  openclaw:\n    requires:\n      bins:\n        - python3\n      env:\n        - ZOHO_EMAIL\n        - ZOHO_PASSWORD\n    primaryEnv: ZOHO_EMAIL\n    tokenFile: \"~/.clawdbot/zoho-mail-tokens.json\"\n---\n\n# Zoho Email Integration\n\n**v2.2.8** - Complete Zoho Mail integration with OAuth2 authentication, REST API backend (5-10x faster than IMAP/SMTP), and **Clawdbot extension with /email commands for Telegram/Discord**. **Security-hardened** against path traversal and command injection. Supports HTML emails, attachments, batch operations, and advanced automation workflows.\n\nChoose your authentication: OAuth2 (recommended, secure) or app password (simple setup).\n\n## 🔄 Update to Latest Version\n\n```bash\nclawhub install zoho-email-integration --force\n```\n\nOr update all skills:\n```bash\nclawhub update\n```\n\n## 🔒 Security Notice (v2.2.5+)\n\n**CRITICAL FIX:** Removed vulnerable JavaScript command handler. If you deployed `email-command.js` from the examples folder, update immediately:\n\n```bash\n# Re-download the secure handler\nclawhub install zoho-email-integration --force\ncp ~/.openclaw/skills/zoho-email-integration/examples/clawdbot-extension/email-command.js /your/deployment/path/\n```\n\nThe vulnerable version used `execSync` with shell interpolation. The new version uses `spawn` with argument arrays to prevent command injection.\n\n## ✨ Features\n\n### 🔐 Authentication & Performance\n- **OAuth2 authentication** - Secure token-based auth with automatic refresh\n- **REST API backend** - 5-10x faster operations than IMAP/SMTP\n- **Graceful fallback** - Automatically falls back to IMAP if REST API unavailable\n- **App password support** - Simple alternative to OAuth2\n\n### 📧 Email Operations\n- **📥 Read emails** - Fetch from any folder (Inbox, Sent, Drafts, etc.)\n- **🔍 Smart search** - Search by subject, sender, keywords with REST API speed\n- **📊 Monitor inbox** - Real-time unread count for notifications\n- **📤 Send emails** - Plain text or HTML with CC/BCC support\n- **🎨 HTML emails** - Rich formatting with professional templates included\n- **📎 Attachments** - Send and download file attachments\n\n### ⚡ Batch & Bulk Operations\n- **Batch operations** - Mark, delete, or move multiple emails efficiently\n- **Bulk actions** - Search and act on hundreds of emails at once\n- **Dry-run mode** - Preview actions before executing for safety\n\n### 🔒 Security\n- **No hardcoded credentials** - OAuth2 tokens or environment variables only\n- **Automatic token refresh** - Seamless token renewal\n- **Encrypted connections** - SSL/TLS for all operations\n\n## 📦 Installation\n\n```bash\nclawhub install zoho-email-integration\n```\n\n**Requirem"},{"path":"examples/templates/README.md","content":"# HTML Email Templates\n\nProfessional, ready-to-use HTML email templates for the Zoho Email skill.\n\n## Available Templates\n\n### 📰 newsletter.html\n**Best for:** Monthly updates, company news, content roundups\n\n**Features:**\n- Modern gradient header\n- Multiple article sections\n- Call-to-action buttons\n- Professional footer\n- Social media links\n\n**Use case:** Send monthly newsletters, product updates, or content digests to subscribers.\n\n### 📢 announcement.html\n**Best for:** Important notifications, system updates, maintenance alerts\n\n**Features:**\n- Bold banner design\n- Highlight boxes for key information\n- Multiple content sections\n- Professional corporate style\n- Clear visual hierarchy\n\n**Use case:** Announce system maintenance, policy changes, or important company news.\n\n### 🎉 welcome.html\n**Best for:** New user onboarding, welcome emails\n\n**Features:**\n- Friendly, welcoming design\n- Step-by-step getting started guide\n- Emoji support\n- Social media integration\n- Engaging call-to-action\n\n**Use case:** Welcome new users, guide them through setup, or introduce your service.\n\n### 📝 simple.html\n**Best for:** Quick, straightforward communications\n\n**Features:**\n- Clean, minimal design\n- Easy to customize\n- Professional signature\n- Good typography\n- Fast to load\n\n**Use case:** General-purpose template for any email, great starting point for custom designs.\n\n## How to Use\n\n### CLI Usage\n\n```bash\n# Send a template\npython3 scripts/zoho-email.py send-html recipient@example.com \"Subject\" examples/templates/newsletter.html\n\n# Preview before sending\npython3 scripts/zoho-email.py preview-html examples/templates/welcome.html\n```\n\n### Python Usage\n\n```python\nfrom scripts.zoho_email import ZohoEmail\n\n# Load template\nwith open('examples/templates/newsletter.html', 'r') as f:\n    html = f.read()\n\n# Send email\nzoho = ZohoEmail()\nzoho.send_html_email(\n    to=\"recipient@example.com\",\n    subject=\"Your Monthly Newsletter\",\n    html_body=html\n)\n```\n\n## Customization Tips\n\n### 1. Replace Placeholder Content\nAll templates contain example text. Simply edit the HTML to replace:\n- Titles and headings\n- Body text and descriptions\n- Links and URLs\n- Footer information\n\n### 2. Change Colors\nEach template uses CSS variables or direct color codes. Search for color codes like:\n- `#667eea` (primary purple)\n- `#764ba2` (secondary purple)\n- `#f5576c` (red accent)\n\nReplace with your brand colors.\n\n### 3. Add Your Logo\nReplace the emoji or text in the header with your logo:\n```html\n<img src=\"https://your-site.com/logo.png\" alt=\"Logo\" style=\"max-width: 200px;\">\n```\n\n### 4. Update Links\nReplace all `href=\"#\"` with actual URLs:\n```html\n<a href=\"https://your-site.com/pricing\">View Pricing</a>\n```\n\n### 5. Modify Layout\nEach template uses inline CSS and modern layout techniques. Feel free to:\n- Add/remove sections\n- Adjust padding and margins\n- Change font sizes\n- Modify button styles\n\n## Email Client Compatibility\n\nAll templates are designed with maximum compatibility:\n- ✅ Gmail (Web, Mob"},{"path":"README.md","content":"# Zoho Email Integration for Clawdbot\n\n[![GitHub](https://img.shields.io/badge/GitHub-clawdbot--zoho--email-blue?logo=github)](https://github.com/briansmith80/clawdbot-zoho-email)\n[![ClawHub](https://img.shields.io/badge/ClawHub-Install-green)](https://clawhub.com)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Version](https://img.shields.io/badge/version-2.2.9-blue)](https://github.com/briansmith80/clawdbot-zoho-email/releases)\n[![Security](https://img.shields.io/badge/security-hardened-brightgreen)](SECURITY.md)\n\n**v2.2.9** - Complete Zoho Mail integration with OAuth2, REST API backend (5-10x faster), **Clawdbot extension with /email commands**, and advanced email automation features. Perfect for email workflows, monitoring, and bulk operations in your Clawdbot projects.\n\n## 🔒 Security Notice (v2.2.0)\n\n**SECURITY UPDATE:** This version fixes critical vulnerabilities identified in security audit. **Upgrade recommended for all users.**\n\n**Fixed vulnerabilities:**\n- ✅ **CRITICAL:** Command injection in JavaScript handler\n- ✅ **HIGH:** Metadata mismatch (credential requirements)\n- ✅ **MEDIUM:** Insufficient input validation\n- ✅ **LOW:** Token file permission enforcement\n\n**See [SECURITY.md](SECURITY.md) for details and migration guide.**\n\n## 🚀 Quick Start (recommended path)\n\n```bash\n# 1) Install\nclawhub install zoho-email-integration\ncd zoho-email-integration  # (or wherever ClawHub installed it)\n\n# 2) Install Python deps (needed for REST API mode)\npip3 install -r requirements.txt\n\n# 3) Set your mailbox (required for both OAuth + app-password modes)\nexport ZOHO_EMAIL=\"your-email@domain.com\"\n\n# 4) OAuth2 setup (recommended: enables REST API + auto token refresh)\npython3 scripts/oauth-setup.py\n\n# 5) Sanity-check everything\npython3 scripts/zoho-email.py doctor\n\n# 6) Test\npython3 scripts/zoho-email.py unread\n```\n\n### Quick Start (app-password mode)\nIf you don't want OAuth2 yet:\n\n```bash\nexport ZOHO_EMAIL=\"your-email@domain.com\"\nexport ZOHO_PASSWORD=\"your-app-specific-password\"\npython3 scripts/zoho-email.py doctor\npython3 scripts/zoho-email.py unread --api-mode imap\n```\n\n**OAuth token location (default):** `~/.clawdbot/zoho-mail-tokens.json`\n\n\n## ✨ Features\n\n### Core Features\n✅ **OAuth2 Authentication** - Secure authentication with automatic token refresh\n✅ **REST API Backend** - 5-10x faster than IMAP/SMTP (auto-enabled with OAuth2)\n✅ **Read & Search** - Search emails with advanced filters\n✅ **Send Emails** - Plain text, HTML, CC/BCC support\n✅ **Attachments** - Send and download attachments\n✅ **HTML Emails** - Send rich-formatted emails with templates\n✅ **Batch Operations** - Mark, delete, move multiple emails efficiently\n✅ **Folder Management** - Access all folders (Inbox, Sent, Drafts, etc.)\n\n### Performance\n⚡ **5-10x faster** operations with REST API mode\n⚡ **Connection pooling** for persistent HTTP connections\n⚡ **Server-side filtering** reduces data transfer\n⚡ **Automatic fallback*"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn780decc8bavz0r6qen0513xh804z45\",\n  \"slug\": \"zoho-email-integration\",\n  \"version\": \"2.2.9\",\n  \"publishedAt\": 1772190656598\n}"},{"path":"CHANGELOG.md","content":"# Changelog\n\nAll notable changes to the Zoho Email Integration skill will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## [2.2.8] - 2026-02-27\n\n### Fixed\n\n- **Zoho JP regional IMAP compatibility** — Fixed `UnicodeDecodeError` when connecting to `imap.zoho.jp` and other regional servers that return non-ASCII bytes (NBSP `\\xc2\\xa0`) in their CAPABILITY response during the initial TLS handshake.\n\n  **Root cause:** Python's `imaplib` uses ASCII decoding by default. Regional Zoho servers send a non-breaking space character in the CAPABILITY greeting, which crashes the ASCII decoder before authentication can begin.\n\n  **Fix:** `PatchedIMAP4_SSL` now overrides `open()` to set UTF-8 encoding before the server greeting is read. UTF-8 is a strict superset of ASCII, so this is fully backwards-compatible with all servers.\n\n  **Note:** v2.2.7 included a community contribution (thanks @SenorToru) that identified and described this bug correctly, but had an implementation error — `_get_capabilities` was defined as a standalone function and never bound to the class, making the fix a no-op. This release corrects that.\n\n---\n\n## [2.2.5] - 2026-02-14\n\n### 🔒 CRITICAL SECURITY FIX\n\n**Vulnerable JavaScript handler removed from distribution.**\n\n#### Fixed\n\n- **CRITICAL: Removed vulnerable email-command.js** - The examples/clawdbot-extension/ directory contained both a vulnerable (`email-command.js`) and secure (`email-command-SECURE.js`) version of the JavaScript command handler. The vulnerable file used `execSync` with shell interpolation, allowing command injection. The secure version using `spawn` with argument arrays is now the default `email-command.js`.\n\n  **Impact:** Remote code execution if the vulnerable handler was deployed and user input was processed through /email commands.\n  \n  **Fix:** \n  - Deleted vulnerable `email-command.js` \n  - Renamed `email-command-SECURE.js` to `email-command.js`\n  - Only the secure handler (using `spawn` with argument arrays) now ships\n\n#### Upgrade Urgency\n**IMMEDIATE** - If you deployed the JavaScript handler from examples/, replace it with the new secure version.\n\n---\n\n## [2.2.1] - 2026-02-12\n\n### 🔒 CRITICAL SECURITY FIXES\n\n**Three additional security vulnerabilities discovered and fixed:**\n\n#### Fixed\n\n- **CRITICAL: Path traversal in attachment download** - The `download_attachment()` function in `scripts/zoho-email.py` used untrusted email attachment filenames directly for file writes. An attacker could send a malicious email with attachment name `../../../../etc/cron.d/backdoor` to write arbitrary files anywhere on the system, leading to remote code execution or privilege escalation.\n  \n  **Fix:** Implemented `_sanitize_filename()` function that:\n  - Strips all directory path components\n  - Removes null bytes and dangerous characters\n  - Prevents hidden files (leading do"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-harde... Skill: Zoho Email Integration Owner: briansmith80 Summary: Complete Zoho Mail integration with OAuth2, REST API (5-10x faster), Clawdbot /email commands, HTML emails, attachments, and batch operations. Security-harde... Tags: latest:2.2.9, security-fix:2.2.7 Version history: v2.2.9 | 2026-02-27T11:10:56.598Z | user Docs: Fix clawhub/clawdhub naming inconsistencies — correct CLI name, slug, badge URL, and version refe","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1828,"uniquenessScore":45,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-09T10:07:38.187Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-09T10:07:38.187Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T18:31:06.479Z","emptyReason":null},"items":[{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-10T18:48:31.762Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}