Email Bot That Answers in the Thread
medium15 minemail-bot.ts
You want an agent that answers mail sent to a mailbox, as a reply in the same thread, without answering spoofed senders or auto-replies.
What it shows
- Run a
GatewaywithemailChannel(): IMAP with IDLE reads new mail, SMTP sends the answers - Answers keep the thread:
Re:subject,In-Reply-ToandReferences, and every email thread is a conversation of its own - The agent reads the new text only, without quoted history and signatures, as HTML rendered from its Markdown goes out
- Only
allowFromreaches the agent, and mail whose DKIM, SPF or DMARC results fail for the sender domain is dropped - Auto-replies, bounces, bulk mail and its own mail are skipped, so it never loops with another bot
The code
email-bot.ts
import { Agent, Cogitator } from '@cogitator-ai/core';
import { Gateway, emailChannel } from '@cogitator-ai/channels';
const address = process.env.EMAIL_ADDRESS;
const password = process.env.EMAIL_PASSWORD;
const apiKey = process.env.GOOGLE_API_KEY;
if (!address || !password || !apiKey) {
throw new Error('Set EMAIL_ADDRESS, EMAIL_PASSWORD and GOOGLE_API_KEY');
}
const email = emailChannel({
address,
name: 'Acme Assistant',
allowFrom: ['acme.com'],
imap: { host: 'imap.gmail.com', auth: { user: address, pass: password } },
smtp: { host: 'smtp.gmail.com', port: 587, auth: { user: address, pass: password } },
});
const agent = new Agent({
name: 'email-assistant',
model: 'google/gemini-3.5-flash-lite',
instructions: 'You answer email for the Acme team. Be friendly and brief.',
});
const cogitator = new Cogitator({
llm: { providers: { google: { apiKey } } },
memory: { adapter: 'memory' },
});
const memory = await cogitator.getMemory();
const gateway = new Gateway({
agent,
cogitator,
channels: [email],
...(memory && { memory }),
});
await gateway.start();
console.log(`${address} answers mail from acme.com`);Run it
install · bash
pnpm add @cogitator-ai/core @cogitator-ai/channels imapflow postal-mime nodemailerEnvironment
EMAIL_ADDRESSEMAIL_PASSWORDGOOGLE_API_KEYrun · bash
npx tsx email-bot.tsOr run the full example from a clone of the repository (keys in .env):
repository · bash
npx tsx examples/channels/07-email-bot.ts