# How to add email to your AI agent with Upstash and AI Inbx

> **Source:** https://upstash.com/blog/add-email-to-your-ai-agent
> **Date:** 2026-12-03
> **Author(s):** Pau Kraft
> **Reading time:** 19 min read
> **Tags:** ai, agents, workflow, redis, vector, blob
> **Format:** text/markdown — machine-readable content for agents and LLMs

Give your AI agent its own inbox: AI Inbx sends and receives the mail, Upstash Workflow processes each email once, Redis keeps the threads, Vector searches emails and attachments, and Blob stores the files.

---

I've built email agents for enterprise customers, and this article shows the setup I would start a new one on today.

An agent that works over email needs somewhere to keep that email. It has to read the conversation it is answering and find things in old emails and attachments. It also has to reply in the right thread, and it should never answer the same email twice. So we build it an inbox. [AI Inbx](https://aiinbx.com) sends and receives the mail and everything else runs on Upstash. We use Workflow to process each incoming email, Redis to store the conversations, Vector to search them and Blob for the attachment files.

The code is TypeScript, and a full implementation you can copy from is [on GitHub](https://github.com/aiinbx/aiinbx-x-upstash-email-agent-starter).

```
email ──▶ AI Inbx ──webhook──▶ Upstash Workflow
                                 ├─ attachment files ──▶ Blob
                                 ├─ email and attachment text ──▶ Vector
                                 ├─ emails and threads ──▶ Redis
                                 └─ your agent, with email tools
                                          │ reply
email ◀── AI Inbx ◀───────────────────────┘
```

## Setup

```sh
npm install aiinbx ai zod @upstash/workflow @upstash/redis @upstash/vector @upstash/blob
```

We need the following, each with its credentials as environment variables:

- An AI Inbx API key (`AI_INBX_API_KEY`) and an address for the agent on one of your domains.
- An AI Inbx webhook endpoint that points at our webhook route and listens for `email.received` and `email.sent` (`AI_INBX_WEBHOOK_SECRET`).
- An Upstash Redis database (`UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN`).
- An Upstash Vector index (`UPSTASH_VECTOR_REST_URL`, `UPSTASH_VECTOR_REST_TOKEN`). Create it as a hybrid index with `text-embedding-3-small` as the embedding model and BM25 as the sparse model.
- An Upstash Blob bucket (`UPSTASH_BLOB_TOKEN`).
- A QStash token for Workflow (`QSTASH_TOKEN`), and the signing keys (`QSTASH_CURRENT_SIGNING_KEY`, `QSTASH_NEXT_SIGNING_KEY`) so the workflow route only accepts calls from QStash.

The snippets use Next.js and the AI SDK, but you can easily adjust them to whatever framework or agent library you use. There are two route handlers, `app/api/email/webhook/route.ts` and `app/api/email/workflow/route.ts`, and everything else is plain functions that the workflow calls.

## The webhook

Every email reaches us as a webhook, the ones we receive and also the ones our agent sends. For both we start a workflow run and return a 204 right away to acknowledge the event. The actual work happens in the workflow, because downloading attachments and running a model take longer than a webhook should wait.

```ts
import { verifyWebhookRequest, WebhookSignatureError } from "aiinbx/webhooks"
import { Client } from "@upstash/workflow"

const workflow = new Client({ token: process.env.QSTASH_TOKEN! })

export const POST = async (request: Request) => {
  let event
  try {
    const secret = process.env.AI_INBX_WEBHOOK_SECRET!
    event = await verifyWebhookRequest(request, secret)
  } catch (error) {
    if (!(error instanceof WebhookSignatureError)) throw error
    return new Response("Invalid signature", { status: 400 })
  }

  if (event.type === "email.received" || event.type === "email.sent") {
    await workflow.trigger({
      url: "https://your.app/api/email/workflow",
      body: { email_id: event.data.email_id },
      // One step at a time per conversation.
      flowControl: { key: event.data.thread_id, parallelism: 1 },
    })
  }
  return new Response(null, { status: 204 })
}
```

## The workflow

The workflow does the work for one email. It needs a client for AI Inbx, one for each Upstash product, and the address our agent uses:

```ts
import { AIInbx, type Attachment, type FullEmail } from "aiinbx"
import { Redis } from "@upstash/redis"
import { Index } from "@upstash/vector"
import { Bucket } from "@upstash/blob"

const aiinbx = new AIInbx() // reads AI_INBX_API_KEY
const redis = Redis.fromEnv()
const index = Index.fromEnv()
const bucket = Bucket.fromEnv()

// The address our agent receives and sends mail on.
const inbox = "agent@acme.example"
```

A workflow is a function made of steps, and every `context.run` is one step. Upstash saves the result of each step, so when a step fails, only that step runs again. Ours has four kinds of steps:

```ts
import { serve } from "@upstash/workflow/nextjs"

export const { POST } = serve<{ email_id: string }>(async (context) => {
  const { email_id } = context.requestPayload

  // 1. Read the email. We only handle mail to or from our agent's address.
  const { ours, attachmentIds } = await context.run("read-email", async () => {
    const email = await aiinbx.emails.retrieve(email_id)
    const ours =
      email.delivered_to.includes(inbox) || email.from.address === inbox
    return { ours, attachmentIds: email.attachments.map((a) => a.id) }
  })
  if (!ours) return

  // 2. Store each attachment in Blob, one step per file.
  for (const attachmentId of attachmentIds) {
    await context.run(`attachment-${attachmentId}`, () =>
      storeAttachment(email_id, attachmentId),
    )
  }

  // 3. Store the email in Redis and Vector.
  await context.run("store-email", () => storeEmail(email_id))

  // 4. Let the agent answer, if a person sent us this email.
  await context.run("agent", () => runAgent(email_id, context.workflowRunId))
})
```

The webhook fires for every address in the workspace, so step 1 ends the run for mail that is not our agent's. We write `storeAttachment`, `storeEmail` and `runAgent` in the next sections. Every file gets its own step, so if the third attachment fails, the first two are not downloaded again. The agent runs last, which means it only sees an email that is completely stored. An email we sent goes through the same steps, so the agent's own replies end up in Redis and in the search index as well.

## Emails and threads in Redis

In a relational database this would be two tables, `emails` and `threads`, and two queries: the threads of an inbox ordered by last activity, and the emails of a thread ordered by time. If your app already runs on Postgres, that works just as well. Here we keep everything in Upstash, and since the agent only reads mail in those two orders, Redis is enough.

Redis has no `ORDER BY`, so any order we want to read in has to be built when we write. That is what a sorted set is for. It is a collection of ids where each id has a number as its score, and Redis keeps the ids sorted by that number. If the score is a timestamp, a sorted set does what an index on a date column does in SQL.

```
email:{id}                         the email as JSON, like a row fetched by primary key
thread:{threadId}                  a hash, like a row with the fields subject, status, note
inbox:{address}                    sorted set of thread ids, score = time of last activity
inbox:{address}:thread:{threadId}  sorted set of email ids, score = time of the email
```

When we store an email, we write all four keys in one transaction:

```ts
const storeEmail = async (emailId: string) => {
  const email = await aiinbx.emails.retrieve(emailId)
  const at = Date.parse(email.created_at)
  const tx = redis.multi()
  // The email itself.
  tx.set(`email:${email.id}`, email)
  // Add it to its thread.
  tx.zadd(`inbox:${inbox}:thread:${email.thread_id}`, {
    score: at,
    member: email.id,
  })
  // Move the thread to the top of the inbox.
  tx.zadd(`inbox:${inbox}`, { gt: true }, {
    score: at,
    member: email.thread_id,
  })
  // Set the subject, unless the thread already has one.
  tx.hsetnx(`thread:${email.thread_id}`, "subject", email.subject)
  await tx.exec()
}
```

`zadd` adds an id with its score, or updates the score if the id is already in the set, so a retried step does not create duplicates. `gt: true` only updates the score when the new one is higher, so an old email stored late does not push an active conversation down the list.

Reading needs two functions. If you are not too familiar with Redis, I've added the SQL equivalent above each one as a comment:

```ts
// SELECT id FROM threads WHERE inbox = ? ORDER BY last_activity DESC LIMIT 20
const listThreads = (inbox: string) =>
  redis.zrange<string[]>(`inbox:${inbox}`, 0, 19, { rev: true })

// SELECT * FROM emails WHERE thread_id = ? ORDER BY created_at
const getThread = async (inbox: string, threadId: string) => {
  const key = `inbox:${inbox}:thread:${threadId}`
  const ids = await redis.zrange<string[]>(key, 0, -1)
  if (ids.length === 0) return []
  return redis.mget<FullEmail[]>(...ids.map((id) => `email:${id}`))
}
```

The thread hash also holds a status and a note that the agent sets, such as "waiting on payment", so it knows where a conversation stands when the next reply arrives.

## Attachments in Blob

AI Inbx converts attachments to Markdown when the email arrives, so we don't have to parse PDFs or spreadsheets ourselves. We store the original file in Blob, and next to it the Markdown if the file has any text.

```ts
// There is text for it, all of it ("ready") or a part ("partial").
// An image or a zip has none.
const hasText = ({ preparation }: Attachment) =>
  preparation?.status === "ready" || preparation?.status === "partial"

const storeAttachment = async (emailId: string, attachmentId: string) => {
  // Read the email again, so a retried step gets a fresh download link.
  const email = await aiinbx.emails.retrieve(emailId)
  const attachment = email.attachments.find((a) => a.id === attachmentId)
  if (!attachment?.download_url) return

  // The file, streamed.
  const response = await fetch(attachment.download_url)
  const path = `attachments/${attachment.id}/${attachment.filename}`
  await bucket.put(path, response.body!, {
    contentType: attachment.content_type,
    size: attachment.size,
  })

  // Its text as Markdown.
  if (hasText(attachment)) {
    const markdown = await aiinbx.attachments.content(attachment.id)
    await bucket.put(`attachments/${attachment.id}/text.md`, markdown, {
      contentType: "text/markdown; charset=utf-8",
    })
  }
}

// Later, when the agent opens an attachment:
const readAttachment = async (attachmentId: string) => {
  const file = await bucket.get(`attachments/${attachmentId}/text.md`)
  return new Response(file.body).text()
}
```

The file is never fully in memory here. `fetch` resolves as soon as the response headers arrive, so `response.body` is still a stream at that point, and `put` uploads while it reads from it. This only works because we pass `size`. Without it, `put` buffers the whole stream first to find out how long it is.

A download link is only valid for an hour, which is why every step reads the email again instead of getting the link from the step before. A step that is retried later still works that way.

## Search over emails and attachments

An agent often needs something that is not in the email in front of it, such as the total on an invoice that arrived as a PDF three months ago. So the text of every email and every attachment also goes to Vector.

A long document cannot go in as one entry. The embedding model only reads a limited amount of text, and a single vector for a 40-page PDF would match no question well. So we first cut the text into chunks of about 1,800 characters. The chunks overlap by 200 characters, which keeps a sentence at a cut complete in one of them.

```ts
const chunk = (text: string, size = 1800, overlap = 200) => {
  const chunks: string[] = []
  for (let start = 0; start < text.length; start += size - overlap) {
    chunks.push(text.slice(start, start + size))
    // Stop once a chunk reaches the end of the text.
    if (start + size >= text.length) break
  }
  return chunks
}
```

Each chunk becomes one entry in the index. We use a hybrid index, which searches in two ways at once. An embedding (`text-embedding-3-small`) finds text by its meaning, so a question also matches a document that uses other words or is even written in another language. BM25 finds exact matches, which is what we need for an invoice number or a name. Upstash runs both itself, so we only send plain text in `data` and never call an embedding model.

```ts
const indexText = async (
  email: FullEmail,
  text: string,
  attachment?: Attachment,
) => {
  // Every chunk starts with where it came from.
  let header = `From: ${email.from.address}\nSubject: ${email.subject}`
  if (attachment) header += `\nAttachment: ${attachment.filename}`

  const entries = chunk(text).map((part, i) => ({
    // The same chunk always gets the same id.
    id: `${email.id}#${attachment?.id ?? "body"}#${i}`,
    // The text that Upstash embeds and searches.
    data: `${header}\n\n${part}`,
    // What we filter on, and where a result came from.
    metadata: {
      email_id: email.id,
      thread_id: email.thread_id,
      attachment_id: attachment?.id,
      inbox,
      source: attachment ? "attachment" : "email",
    },
  }))

  if (entries.length > 0) await index.upsert(entries)
}

// What the sender wrote, without the quoted earlier messages.
const written = (email: FullEmail) => email.stripped_text ?? email.text ?? ""
```

We put the sender, subject and file name at the start of every chunk so that they are part of the text that gets searched. Metadata is only used for filtering. Without the header, a search for "the contract Anna sent" would miss a chunk from page 14 of that contract, because the page itself never mentions Anna. The id is the same every time for the same chunk, so indexing an email again overwrites its entries. The metadata is what we filter on when we search, and it tells the agent which email or attachment a result came from.

We call `indexText` at the end of `storeEmail`, once for the body and once for every attachment that has text. For the body we use `stripped_text`, which is what the sender wrote without the quoted earlier messages. Those are in the index already as emails of their own, and indexing them again with every reply would fill the search results with copies. The attachment text is the Markdown we stored in Blob earlier:

```ts
// At the end of storeEmail: the body of the email.
await indexText(email, written(email))

// Then the text of each attachment. The email is only passed along
// for the header and the ids, its body is not indexed again.
for (const attachment of email.attachments.filter(hasText)) {
  const markdown = await readAttachment(attachment.id)
  await indexText(email, markdown, attachment)
}
```

To search we need a single query. It has a `sources` parameter that limits the search to emails or attachments and defaults to both:

```ts
type Source = "email" | "attachment"

const search = (query: string, sources: Source[] = ["email", "attachment"]) =>
  index.query({
    data: query,
    topK: 8,
    includeMetadata: true,
    includeData: true,
    filter:
      `inbox = '${inbox}' AND ` +
      `source IN (${sources.map((source) => `'${source}'`).join(", ")})`,
  })
```

Every result has the `email_id`, `thread_id` and `attachment_id` in its metadata, so the agent can open the email or attachment it came from.

## The agent's tools

Now we turn the functions from above into tools for the agent. A tool is only a description, an input schema and a call to one of our functions, so instead of the AI SDK the same functions can be wrapped for Mastra, LangChain, the OpenAI Agents SDK or an MCP server.

```ts
import { tool } from "ai"
import { z } from "zod"

// Shared by the two tools that send.
const sendAt = z
  .string()
  .optional()
  .describe("To send later: an ISO 8601 time with offset. Omit to send now.")

// One email as text for the model, with the ids of its attachments.
const asText = (email: FullEmail) => {
  const files = email.attachments.map((a) => `${a.filename} (${a.id})`)
  return (
    `From ${email.from.address} on ${email.created_at}:\n` +
    (files.length > 0 ? `Attachments: ${files.join(", ")}\n` : "") +
    written(email)
  )
}

const emailTools = (email: FullEmail) => ({
  get_thread: tool({
    description: "Read a conversation, oldest first, with its status and note.",
    inputSchema: z.object({ thread_id: z.string() }),
    execute: async ({ thread_id }) => ({
      ...(await redis.hgetall(`thread:${thread_id}`)),
      messages: (await getThread(inbox, thread_id)).map(asText),
    }),
  }),

  search_emails: tool({
    description: "Search emails and attachments by meaning and exact words.",
    inputSchema: z.object({
      query: z.string(),
      sources: z
        .array(z.enum(["email", "attachment"]))
        .default(["email", "attachment"])
        .describe("Where to search. Default: both."),
    }),
    execute: ({ query, sources }) => search(query, sources),
  }),

  read_attachment: tool({
    description: "Read an attachment as Markdown.",
    inputSchema: z.object({ attachment_id: z.string() }),
    execute: ({ attachment_id }) => readAttachment(attachment_id),
  }),

  reply: tool({
    description: "Reply to the email you are handling.",
    inputSchema: z.object({
      text: z.string().describe("Plain text. Do not quote earlier messages."),
      send_at: sendAt,
    }),
    execute: ({ text, send_at }) => reply(email, text, send_at),
  }),

  send_email: tool({
    description: "Start a new conversation with a new email.",
    inputSchema: z.object({
      to: z.string().describe("One email address."),
      subject: z.string(),
      text: z.string(),
      send_at: sendAt,
    }),
    execute: (input) => sendEmail(email, input),
  }),

  set_thread_status: tool({
    description: "Save where this conversation stands, for the next time.",
    inputSchema: z.object({
      status: z.string().describe('Short, such as "waiting on payment".'),
      note: z.string().default(""),
    }),
    execute: async ({ status, note }) => {
      await redis.hset(`thread:${email.thread_id}`, { status, note })
      return "saved"
    },
  }),
})
```

`reply` only takes the text. The recipients, the sender, the subject and the thread all come from the email that is being answered, so there is no way for the model to send a reply to the wrong person or into the wrong thread. With `send_email` the agent starts a new conversation, for example to ask a colleague before it answers the customer, so there it names the recipient and the subject itself. Keep in mind that an email from a stranger can try to talk the agent into writing to anyone, so in production you may want to limit `to` to addresses you know.

A tool to list threads can be built in the same way.

## Sending only once

The agent should answer every email once, even though a webhook delivery can arrive twice and a workflow step can be retried after a deploy or a crash. We do two things to make sure of that.

First, the run claims the email in Redis before the agent starts. `SET ... NX` only succeeds if nobody holds the claim yet.

```ts
const claim = async (emailId: string, runId: string) => {
  const key = `handled:${emailId}:${inbox}`
  const mine = `running:${runId}`
  if (await redis.set(key, mine, { nx: true, ex: 900 })) return true
  // Already claimed: only a retry of this same run may continue.
  return (await redis.get(key)) === mine
}
```

A second delivery of the same email finds the claim and stops, while a retry of the same run sees that the claim is its own and continues. When the agent is finished we set the value to `done`. If the process dies before that, the claim expires after 15 minutes.

Second, we send every email with an idempotency key. AI Inbx sends only one email per key. A retry with the same key and the same request gets the first email back, and a retry with the same key but a different request is refused with a 409. With a model that second case is the normal one, because a retried run words the same answer a little differently. So we save the first request in Redis under its key, and a retry sends exactly that request again.

```ts
// The first request made under a key is saved, and a retry sends that one.
const once = async <T>(key: string, request: T) => {
  await redis.set(`request:${key}`, request, { nx: true })
  return (await redis.get<T>(`request:${key}`))!
}

const reply = async (email: FullEmail, text: string, sendAt?: string) => {
  // One reply now and one scheduled reply per email.
  const key = `reply-${email.id}-${sendAt ? "later" : "now"}`
  const request = await once(key, {
    from: inbox,
    email_id: email.id,
    text,
    scheduled_at: sendAt,
  })
  const { id, status, suppressed } = await aiinbx.threads.reply(
    email.thread_id,
    request,
    { idempotencyKey: key },
  )
  // suppressed: recipients that were left out.
  return { id, status, suppressed }
}

type NewEmail = { to: string; subject: string; text: string; send_at?: string }

const sendEmail = async (email: FullEmail, input: NewEmail) => {
  const { to, subject, text, send_at } = input
  // One new email per recipient, now and later.
  const key = `send-${email.id}-${to}-${send_at ? "later" : "now"}`
  const request = await once(key, {
    from: inbox,
    to,
    subject,
    text,
    scheduled_at: send_at,
  })
  const { id, status, suppressed } = await aiinbx.emails.send(request, {
    idempotencyKey: key,
  })
  return { id, status, suppressed }
}
```

The key of a reply is made of the id of the email we are answering, and the key of a new email also has the recipient in it. The text is not part of either key, so whatever the model writes on a retry, it is the first version that goes out.

## Running the agent

The last step of the workflow claims the email and then runs the agent with its tools.

```ts
import { generateText, isStepCount } from "ai"

const instructions = `You are an AI agent that answers customer emails for Acme.
Search old emails and attachments when you need a fact that is not in the
conversation. Answer with the reply tool, short and friendly.`

// A person wrote it, the sender is not forged, and it is not our own mail.
const shouldAnswer = (email: FullEmail) =>
  email.direction === "inbound" &&
  email.category === "human" &&
  email.verdicts?.dmarc !== "FAIL" &&
  email.from.address !== inbox

const runAgent = async (emailId: string, runId: string) => {
  const email = await redis.get<FullEmail>(`email:${emailId}`)
  if (!email || !shouldAnswer(email)) return
  if (!(await claim(email.id, runId))) return

  // The agent gets the whole conversation right away,
  // so it does not need a tool call to read it.
  const thread = await getThread(inbox, email.thread_id)
  const state = await redis.hgetall(`thread:${email.thread_id}`)

  await generateText({
    model, // any model the AI SDK supports
    instructions,
    prompt:
      `It is ${new Date().toISOString()}.\n` +
      `Status of this conversation: ${state?.status ?? "none"}\n` +
      `Note: ${state?.note ?? "none"}\n\n` +
      thread.map(asText).join("\n\n") +
      `\n\nPlease reply to the email from ${email.from.address} ` +
      `sent on ${email.created_at}.`,
    tools: emailTools(email),
    stopWhen: isStepCount(10),
  })
  await redis.set(`handled:${email.id}:${inbox}`, "done")
}
```

`instructions` is the system prompt. It says who the agent is and how it works, and it is the place for everything that is specific to your product, like the tone, what the agent may promise and when it should leave an email to a person.

`prompt` is the task for this one run. We put the whole conversation into it, because the agent needs it for almost every answer and reading it with a tool would cost an extra model call each time. The tools are for everything else. The agent can search, open an attachment or read another conversation, and when it is done it answers with `reply`.

The full implementation is on GitHub at [aiinbx/aiinbx-x-upstash-email-agent-starter](https://github.com/aiinbx/aiinbx-x-upstash-email-agent-starter). You can copy from it or point your coding agent at it. It also covers a tenant per customer, drafts that a person approves before they are sent, filters against mail loops and floods, catch-up after downtime, and the same tools for TanStack AI, Mastra, Pi, OpenAI Agents, LangChain and MCP.

---

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_4cf2adc7846aa874f833b068&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.