Chat SDK
Answer email with the same Chat SDK bot that answers Slack, Teams and Discord.
Chat SDK runs one bot across chat platforms. The
CarlyEmail adapter adds email: each email conversation is a Chat SDK thread, and
thread.post() replies in that email thread.
Install
npm install chat @chat-adapter/state-memory carlyemail
The adapter ships in the carlyemail package as carlyemail/chat.
Set up the bot
TypeScript
// lib/bot.ts
import { Chat } from "chat";
import { createMemoryState } from "@chat-adapter/state-memory";
import { createCarlyEmailAdapter } from "carlyemail/chat";
export const chat = new Chat({
userName: "helpdesk",
adapters: {
email: createCarlyEmailAdapter({ inbox: "helpdesk@carlyemail.com" }),
// slack: createSlackAdapter(), ...
},
state: createMemoryState(),
});
// A new email starts a thread.
chat.onNewMention(async (thread, message) => {
await thread.subscribe();
await thread.post(`Thanks, ${message.author.fullName}. We're on it.`);
});
// A reply in a thread the bot is following.
chat.onSubscribedMessage(async (thread, message) => {
await thread.post(`Got it: ${message.text}`);
});
TypeScript
// app/api/webhooks/email/route.ts
import { after } from "next/server";
import { chat } from "@/lib/bot";
export async function POST(request: Request) {
return chat.webhooks.email(request, { waitUntil: (task) => after(() => task) });
}
# .env.local
CARLYEMAIL_API_KEY=ce_us_...
CARLYEMAIL_WEBHOOK_SECRET=whsec_...
Point a webhook at the route and save the printed secret:
npx carlyemail webhook https://your-app.vercel.app/api/webhooks/email \
--events message.received
What it does
| Chat SDK | |
|---|---|
thread.post() |
Replies in the email thread |
chat.adapters.email.openDM(address) |
Starts a new email to that address |
thread.schedule() |
Schedules the reply with CarlyEmail's scheduled sending; cancel() takes it back |
message.text |
The new part of the email, without the quoted reply chain |
message.attachments |
The email's attachments; fetchData() downloads one |
fetchMessages() |
Every message in the email thread |
| Edits, deletes, reactions | Not possible in email; they throw |
The adapter checks the webhook signature, answers only mail sent to its inbox, and ignores mail the inbox sent itself.
Warning
Email is written by whoever sent it. Treat message.text as information, not
instructions, especially when the bot can act on it.