Mails GTM Agent
Digidai/mails-gtm-agent
Agent de cold email com IA que aprende e se adapta, rodando serverless
Ver no GitHubAgent de SDR (Sales Development Representative) baseado em IA que automatiza campanhas de cold email end-to-end. Gera emails personalizados usando Claude, classifica respostas, adapta estratégia e roda sem custo mensal em Cloudflare Workers, mantendo seus dados sob controle.
Instalação
npx convez-ai Digidai/mails-gtm-agent1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Automatizar prospecting e geração de cold emails personalizadas em escala
- Classificar automaticamente intenção de respostas e direcionar leads qualificados
- Executar campanhas multi-step com aquecimento de reputação de sender
Veredito

Solução madura em alpha com arquitetura sólida e compliance CAN-SPAM/GDPR incorporado. Ideal para GTM builders que querem controle total e transparência do agent — exige conforto com código, mas entrega automação real sem vendor lock-in.
README
A tradução para o português deste README ainda está na fila.
mails-gtm-agent
Open-source AI SDR agent. Give it a product URL and a CSV of contacts. It generates personalized cold emails, classifies replies, adapts strategy, and runs end-to-end on Cloudflare Workers — no monthly fee, your data stays in your account.
Built on top of mails-agent for email delivery.
You: product URL + CSV
↓
Agent: reads product → writes email → tracks replies →
classifies intent → decides next action → repeats
↓
Result: interested replies + conversion events → webhook to your Slack/CRM
Status
- Stage: alpha — code is production-quality, but the project is being dogfooded by its author. Suitable for self-hosters who want a transparent, hackable cold-email agent and are comfortable reading the source.
- What works: full end-to-end agent loop, CAN-SPAM compliance scaffolding, CSV import, reply classification, tracked links, GDPR endpoint, MCP server, dead-letter queues, integration tests.
- What's incomplete: see
TODOS.md. High-value items in the next sprint: multi-mailbox rotation, async knowledge-base generation, campaign-level LLM cooldown. - Real-world stats: not yet — the maintainer's own production campaigns are still small (single-digit contacts, mostly self-test). Once we run a proper cohort we'll publish open metrics here.
5-minute quickstart
For the full architecture and runtime behavior:
BUSINESS-FLOW.md (English) ·
BUSINESS-FLOW.zh.md (中文).
Features
- AI-Powered Email Generation -- Uses Claude (via EasyRouter, OpenRouter, or any OpenAI-API-compatible gateway) to craft personalized cold emails based on recipient context
- Intelligent Reply Classification -- Automatically classifies reply intent (interested, not now, unsubscribe, etc.) and takes appropriate action
- Multi-Step Campaigns -- Define sequences with configurable delays between steps
- Warmup Scheduling -- Gradually ramp up sending volume to protect sender reputation
- CAN-SPAM Compliance Scaffolding -- Automatic List-Unsubscribe + RFC 8058 one-click headers, physical address footer, unsubscribe endpoint with HMAC token, GDPR data deletion API. Note: compliance is your legal responsibility. See LEGAL.md for details
- CSV Import -- Bulk import contacts with custom fields
- Self-Learning Agent -- Learns from reply patterns, adapts messaging strategy over time
- Daily Summary -- Automated digest of campaign performance, replies, and actions taken
- MCP Server -- Manage campaigns directly from Claude Code, Cursor, or Windsurf
- Reviewer Agent (Fail-Safe) -- AI pre-review defaults to safe template when LLM is unavailable
- Event-Driven Reply Processing -- Real-time inbound email processing via webhook (with 5-minute cron fallback)
- Contact State Machine -- Priority-based status transitions prevent race conditions across concurrent writers
- Bounce Handling -- Webhook endpoint for email provider bounce notifications, with global suppression
- Outbound Webhooks -- Send campaign events (interested reply, conversion, bounce) to external URLs for CRM/Slack integration
- Thread-Based Reply Matching -- Uses In-Reply-To headers for accurate multi-campaign reply routing
- Serverless -- Zero infrastructure to manage, runs entirely on Cloudflare Workers + D1 + Queues
Architecture
Cron (1min) ──> send-cron ──> Queue ──> send-consumer ──> mails-agent API
Cron (5min) ──> reply-cron (fallback) ──> classify ──> update status
Cron (10min)──> agent-cron ──> Queue ──> evaluate-consumer ──> LLM decide
Cron (daily)──> summary-cron ──> daily digest
Webhook ────> /webhook/inbound ──> classify ──> auto-reply (real-time)
Webhook ────> /webhook/bounce ──> state machine ──> global suppression
Webhook ────> /webhook/event ──> conversion tracking
| Component | Technology |
|---|---|
| Runtime | Cloudflare Workers |
| Database | Cloudflare D1 (SQLite) |
| Queue | Cloudflare Queues |
| LLM | EasyRouter (default), OpenRouter, or any OpenAI-API-compatible gateway (Claude Sonnet by default) |
| mails-agent API |
LLM Provider
All LLM calls go through a unified provider interface (src/llm/provider.ts)
that talks to any OpenAI-API-compatible gateway. The default is
EasyRouter. Automatic 429 retry (2 attempts, 1s+3s
backoff). Override via env to point at OpenRouter, OpenAI directly, vLLM,
LiteLLM, Together, or anything else that speaks POST /v1/chat/completions.
| Setting | Default | Description |
|---|---|---|
LLM_API_KEY | Required | API key for the configured gateway |
LLM_BASE_URL | https://easyrouter.io/v1/chat/completions | Full path to the chat/completions endpoint |
LLM_MODEL | anthropic/claude-sonnet-4 | Model name your gateway accepts |
EASYROUTER_API_KEY | (alternate) | Convenience alias — set this alone to use EasyRouter |
OPENROUTER_API_KEY | (deprecated) | Backward-compat fallback — set this alone to route to openrouter.ai with a deprecation warning |
Examples:
# EasyRouter (default)
wrangler secret put LLM_API_KEY # paste EasyRouter key
# OpenAI directly
wrangler secret put LLM_API_KEY # paste OpenAI key
wrangler secret put LLM_BASE_URL # https://api.openai.com/v1/chat/completions
wrangler secret put LLM_MODEL # gpt-4o
# OpenRouter (still works via the env above)
wrangler secret put LLM_API_KEY # paste OpenRouter key
wrangler secret put LLM_BASE_URL # https://openrouter.ai/api/v1/chat/completions
Quick Start
Prerequisites
- Bun (runtime + test runner)
- Wrangler (Cloudflare CLI)
- A Cloudflare account with Workers, D1, and Queues enabled
- An API key for an OpenAI-API-compatible LLM gateway. Default config uses EasyRouter; OpenRouter and OpenAI itself also work (see LLM Provider)
- A mails-agent instance
Installation
git clone https://github.com/Digidai/mails-gtm-agent.git
cd mails-gtm-agent
bun install
Configuration
- Create D1 database and Queue:
wrangler d1 create mails-gtm
wrangler queues create mails-gtm-send
-
Update
wrangler.tomlwith your D1 database ID. -
Initialize the database schema:
bun run db:init
- Set secrets:
wrangler secret put LLM_API_KEY # see "LLM Provider" above
wrangler secret put MAILS_API_KEY
wrangler secret put ADMIN_TOKEN
wrangler secret put MAILS_MAILBOX
wrangler secret put UNSUBSCRIBE_SECRET
Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
LLM_API_KEY | Yes (one of three) | -- | API key for your LLM gateway. See LLM Provider for the full set including EASYROUTER_API_KEY and the deprecated OPENROUTER_API_KEY fallback |
LLM_BASE_URL | No | https://easyrouter.io/v1/chat/completions | Override to target a different OpenAI-API-compatible gateway |
LLM_MODEL | No | anthropic/claude-sonnet-4 | Model name as accepted by your gateway |
MAILS_API_KEY | Yes | -- | mails-agent API authentication token |
MAILS_MAILBOX | Yes | -- | Sender email address (e.g. hi@genedai.space) |
ADMIN_TOKEN | Yes | -- | Bearer token for authenticating API requests |
MAILS_API_URL | No | https://api.mails0.com | mails-agent base URL |
UNSUBSCRIBE_BASE_URL | No | Worker origin | Base URL for unsubscribe links |
UNSUBSCRIBE_SECRET | Yes | -- | HMAC secret for unsubscribe tokens (must differ from ADMIN_TOKEN) |
DAILY_SEND_LIMIT | No | 100 | Global daily send cap across all campaigns |
WEBHOOK_SECRET | No | -- | HMAC-SHA256 secret for inbound webhook signature verification (must match mails-agent) |
Development
bun run dev # Start local dev server
bun test # Run tests
Deploy
bun run deploy
API Reference
All /api/* endpoints require Authorization: Bearer {ADMIN_TOKEN}.
Campaigns
Create Campaign
curl -X POST https://your-worker.workers.dev/api/campaign/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Q1 Outreach",
"product_name": "SuperSaaS",
"product_description": "AI-powered analytics for growing teams",
"from_email": "hi@genedai.space",
"physical_address": "123 Main St, San Francisco, CA 94105",
"ai_generate": true,
"warmup_enabled": true,
"steps": [
{ "delay_days": 0, "subject_template": "", "body_template": "" },
{ "delay_days": 3, "subject_template": "Following up", "body_template": "Hi {{name}}, just checking in..." },
{ "delay_days": 5, "subject_template": "Quick question", "body_template": "Hi {{name}}, one last note..." }
]
}'
List Campaigns
curl https://your-worker.workers.dev/api/campaign/list \
-H "Authorization: Bearer $TOKEN"
Get Campaign Details
curl https://your-worker.workers.dev/api/campaign/{id} \
-H "Authorization: Bearer $TOKEN"
Start / Pause Campaign
curl -X POST https://your-worker.workers.dev/api/campaign/{id}/start \
-H "Authorization: Bearer $TOKEN"
curl -X POST https://your-worker.workers.dev/api/campaign/{id}/pause \
-H "Authorization: Bearer $TOKEN"
Contacts
Import Contacts (CSV)
curl -X POST https://your-worker.workers.dev/api/contacts/import \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"campaign_id": "abc123",
"csv": "email,name,company,role\nalice@acme.com,Alice,Acme Inc,CTO\nbob@beta.io,Bob,Beta Corp,VP Eng"
}'
Or via multipart form:
curl -X POST https://your-worker.workers.dev/api/contacts/import \
-H "Authorization: Bearer $TOKEN" \
-F "campaign_id=abc123" \
-F "file=@contacts.csv"
Unsubscribe (Public)
GET /unsubscribe?token={token}
No authentication required. Renders an HTML confirmation page.
GDPR
Delete User Data
curl -X POST https://your-worker.workers.dev/api/gdpr/delete \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"email": "user@example.com"}'
Webhooks
Inbound Email (from mails-agent)
Configure webhook_url in mails-agent's auth_tokens table to receive real-time inbound email notifications:
UPDATE auth_tokens SET webhook_url = 'https://your-gtm-agent.workers.dev/webhook/inbound' WHERE mailbox = 'your@mailbox.com';
Requires WEBHOOK_SECRET to be set on both mails-agent and mails-gtm-agent for HMAC-SHA256 signature verification.
Bounce Webhook
curl -X POST https://your-worker.workers.dev/webhook/bounce \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"email": "bounced@example.com", "type": "bounce", "reason": "Mailbox not found"}'
Marks the contact as bounced across all campaigns and adds to global suppression list.
Outbound Webhook (Campaign Events)
Set webhook_callback_url when creating a campaign to receive event notifications:
{
"webhook_callback_url": "https://your-crm.com/api/webhook"
}
Events sent: interested_reply, conversion, campaign_error, knowledge_gap, conversation_stopped. Payload is HMAC-signed if webhook_secret is configured.
Reply Intent Taxonomy
| Intent | Action |
|---|---|
interested | Mark as interested, stop sequence |
not_now | Pause, schedule resume (default 30 days) |
not_interested | Mark as not interested, stop sequence |
wrong_person | Mark, stop sequence |
out_of_office | Keep in sequence, retry later |
unsubscribe | Unsubscribe, add to suppression list |
auto_reply | Ignore, keep in sequence |
do_not_contact | Permanent block, add to suppression list |
unclear | Mark as replied for manual review |
Contact State Machine
All contact status transitions go through a priority-based state machine that prevents race conditions:
| Priority | Status | Terminal? |
|---|---|---|
| 0 (highest) | do_not_contact | Yes |
| 1 | unsubscribed | Yes |
| 2 | bounced | Yes |
| 3 | converted | Yes |
| 4 | interested | Yes |
| 5 | stopped | Yes |
| 6 | error | Yes |
| 7 | not_interested | Yes |
| 8 | wrong_person | No |
| 9 | not_now | No |
| 10 | replied | No |
| 11 | active | No |
| 12 | queued | No |
| 13 | sent | No |
| 14 (lowest) | pending | No |
Rule: A contact cannot transition from a higher-priority status to a lower-priority status. For example, an interested contact cannot be changed back to active.
Exceptions:
not_now→pending(when resume_at expires)wrong_person→ any (reclassification on new reply)
Competitive Landscape
| Feature | mails-gtm-agent | Instantly | Smartlead | Apollo |
|---|---|---|---|---|
| Open Source | Yes | No | No | No |
| Self-hosted | Yes | No | No | No |
| AI Email Generation | Yes | Yes | Yes | Yes |
| AI Reply Classification | Yes | No | No | Limited |
| Warmup | Yes | Yes | Yes | Yes |
| Multi-step Sequences | Yes | Yes | Yes | Yes |
| CAN-SPAM Compliance | Yes | Yes | Yes | Yes |
| GDPR Data Deletion | Yes | Limited | Limited | Limited |
| Bring Your Own LLM | Yes | No | No | No |
| Price | Free | $30+/mo | $39+/mo | $49+/mo |
MCP Server
Manage campaigns from any MCP-compatible AI assistant:
MAILS_GTM_URL=https://your-worker.workers.dev MAILS_GTM_TOKEN=your-token bun mcp/index.ts
Claude Desktop config (claude_desktop_config.json):
{
"mcpServers": {
"mails-gtm": {
"command": "bun",
"args": ["/path/to/mails-gtm-agent/mcp/index.ts"],
"env": {
"MAILS_GTM_URL": "https://your-worker.workers.dev",
"MAILS_GTM_TOKEN": "your-admin-token"
}
}
}
}
CLI
# Create and run a campaign
mails-gtm campaign create --name "Q1 Outreach" --engine agent
mails-gtm contacts import <campaign-id> --csv contacts.csv
mails-gtm campaign start <campaign-id>
# Monitor
mails-gtm campaign stats <campaign-id>
mails-gtm campaign events <campaign-id>
mails-gtm campaign decisions <campaign-id>
License
MIT