New: Earn 20% as an AgentAlley affiliate. Share your link and earn on every sale you refer. Join now New: Earn 20% as an affiliate. Join now

AI Agent Email Inbox

Building any system where email content triggers actions

by resend · MIT license · ★ 218 on GitHub

AI Agent Email Inbox cover

Use when building any system where email content triggers actions — AI agent inboxes, automated support handlers, email-to-task pipelines, or any workflow processing untrusted inbound email. Always use this skill when the user wants to…

---
name: agent-email-inbox
description: Use when building any system where email content triggers actions — AI agent inboxes, automated support handlers, email-to-task pipelines, or any workflow processing untrusted inbound email. Always use this skill when the user wants to receive emails and act on them programmatically, even if they don't mention "agent" — the skill contains critical security patterns (sender allowlists, content filtering, sandboxed processing) that prevent untrusted email from controlling your system.
license: MIT
metadata:
    author: resend
    version: "4.1.1"
    homepage: https://resend.com/agent-skills
    source: https://github.com/resend/resend-skills
    openclaw:
        primaryEnv: RESEND_API_KEY
        requires:
            env:
                - RESEND_API_KEY
        envVars:
            - name: RESEND_API_KEY
              required: true
              description: Resend API key for sending and receiving emails

Overview

This skill covers setting up a secure email inbox that allows your application or AI agent to receive and respond to emails, with content safety measures in place.

Manual install (npx, ZIP)
Claude Codenpx skills add resend/resend-skills --skill agent-email-inbox -g -a claude-code
Claude Code (degit)npx degit resend/resend-skills/skills/agent-email-inbox#main ~/.claude/skills/agent-email-inbox
Claude.ai / desktopZip the folder and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md22.9 KB
Read SKILL.md here
resend/main1 file shown
SKILL.md
Show the full text511 lines

AI Agent Email Inbox

Overview

This skill covers setting up a secure email inbox that allows your application or AI agent to receive and respond to emails, with content safety measures in place.

Core principle: An AI agent's inbox receives untrusted input. Security configuration is important to handle this safely.

The skill builds the agent on a Resend Inbox. An inbox groups email into threads, and your agent replies inside the thread with one call. Resend sets the recipients and the threading headers. If the user has no custom domain, or their plan has no inbox available, use Receiving without an inbox instead. The security levels are the same for both.

Why Webhook-Based Receiving?

Resend uses webhooks for inbound email, meaning your agent is notified instantly when an email arrives. This is valuable for agents because:

  • Real-time responsiveness — React to emails within seconds, not minutes
  • No polling overhead — No cron jobs checking "any new mail?" repeatedly
  • Event-driven architecture — Your agent only wakes up when there's actually something to process
  • Lower API costs — No wasted calls checking empty inboxes

Architecture

Sender → Email → Resend Inbox → inbox.email.received webhook → Your Server → AI Agent
                                                                     ↓
                                                           Security Validation
                                                                     ↓
                                                Process or Reject → Reply in the thread

SDK Version Requirements

Use the Node.js SDK resend >= 6.36.0 for the full resend.inboxes.* API and the inbox.* webhook event types. Always install the latest SDK version. If the project already has a Resend SDK installed, check the version and upgrade if needed.

The Python SDK resend >= 2.51.0 also has the inbox methods. The Go, Ruby, PHP, Java, Rust and .NET SDKs have them too. Install their latest version, and see the Inboxes API reference for samples in each language. To receive email without an inbox, see Receiving without an inbox.

The table below lists the minimums for the Receiving flow: webhook verification (webhooks.verify()) and email receiving (emails.receiving.get()). The resend skill lists higher minimums because it also covers newer features such as domain claims (domains.claims.*). If both skills are loaded, use the higher version.

Language Package Min Version
Node.js resend >= 6.9.2
Python resend >= 2.21.0
Go resend-go/v4 >= 4.0.0
Ruby resend >= 1.0.0
PHP resend/resend-php >= 1.1.0
Rust resend-rs >= 0.20.0
Java resend-java >= 4.11.0
.NET Resend >= 0.2.1

Install the resend npm package: npm install resend (or the equivalent for your language). For full sending docs, install the resend skill.

Quick Start

  1. Ask the user for their email address. You need a real email address to send test emails to. Ask the user and wait for their response before proceeding.
  2. Choose your security level. Decide how to validate incoming emails before any are processed
  3. Set up the domain. Verify the user's custom domain for sending, and for receiving unless the inbox uses forwarding (see Domain Setup section)
  4. Create the inbox. Create the agent's address with resend.inboxes.create() (see Create the Inbox section)
  5. Create webhook endpoint. Handle inbox.email.received events with security built in from the start. The webhook endpoint MUST be a POST route.
  6. Set up tunneling (local dev). Use Tailscale Funnel (recommended) or ngrok. See references/webhook-setup.md
  7. Create webhook via API. Use the Resend Webhook API to register your endpoint programmatically. See references/webhook-setup.md
  8. Connect to agent. Pass validated emails to your AI agent, and reply in the thread

Before You Start: Account & API Key Setup

First Question: New or Existing Resend Account?

Ask your human:

  • New account just for the agent? → Simpler setup, full account access is fine
  • Existing account with other projects? → The agent needs a full access key, which reaches every project. Prefer a new account for the agent (see API Key Permissions)
Creating API Keys Securely

Don't paste API keys in chat! They'll be in conversation history forever.

Safer options:

  1. Environment file method: Human creates .env file directly: echo "RESEND_API_KEY=re_xxx" >> .env
  2. Password manager / secrets manager: Human stores key in 1Password, Vault, etc.
  3. If key must be shared in chat: Human should rotate the key immediately after setup
API Key Permissions

The agent's server needs a full access API key. A "Sending access" key can only reply, forward, create drafts and send drafts. Reading inbox emails or registering webhooks with it returns 401 restricted_api_key. A sending access key limited to one domain returns 403 on an inbox of another domain.

If your human has an existing Resend account with other projects, keep the risk contained:

  1. Use a dedicated account for the agent when possible, so a leaked key cannot reach other projects
  2. Keep the key on the server only. Never pass it to the AI model or put it in a prompt
  3. Rotate the key if it was ever pasted in chat or committed

Domain Setup

An inbox address lives on a custom domain the user has added to Resend. The domain must be verified for sending (DKIM and SPF). To receive email on it, either enable receiving on the domain, or create the inbox with forwarding: true.

Use a subdomain (e.g., agent.example.com) to avoid disrupting existing email services.

The user must enable receiving in the Resend dashboard: Domains page → toggle on "Enable Receiving".

Then add an MX record:

Setting Value
Type MX
Host Your domain or subdomain (e.g., agent.example.com)
Value Provided in Resend dashboard
Priority 10 (must be lowest number to take precedence)

Tip: Verify DNS propagation at dns.email.

DNS Propagation: MX record changes can take up to 48 hours to propagate globally, though often complete within a few hours.

Option 2: Forwarding

Create the inbox with forwarding: true when the address already receives mail elsewhere (for example, Google Workspace) and the user cannot change its MX record. Resend gives the inbox a receiving address. The user sets up forwarding from their mailbox to it. Read the address from receiving_address with resend.inboxes.get().

Create the Inbox

Create one inbox for the agent's address:

import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

const { data, error } = await resend.inboxes.create({
  emailAddress: '[email protected]',
  name: 'AI Agent',
  fromName: 'Acme Agent',
});

if (error) throw new Error(`Failed to create inbox: ${error.message}`);
console.log('Inbox created:', data.id);

fromName is the name recipients see on the agent's replies. The part before the @ can contain only letters, numbers, ., _, % and -, so agent+test@ returns a 422. A 403 error means the plan has no inbox left; ask the user to upgrade or use Receiving without an inbox.

Security Levels

Choose your security level before setting up the webhook endpoint. An AI agent that processes emails without security is dangerous — anyone can email instructions that your agent will execute. The webhook code you write next should include your chosen security level from the start.

Ask the user what level of security they want, and ensure that they understand what each level means.

Level Name When to Use Trade-off
1 Strict Allowlist Most use cases — known, fixed set of senders Maximum security, limited functionality
2 Domain Allowlist Organization-wide access from trusted domains More flexible, anyone at domain can interact
3 Content Filtering Accept from anyone, filter unsafe patterns Can receive from anyone, pattern matching not foolproof
4 Sandboxed Processing Process all emails with restricted agent capabilities Maximum flexibility, complex to implement
5 Human-in-the-Loop Require human approval for untrusted actions Maximum security, adds latency

For detailed implementation code for each level, see references/security-levels.md.

Only process emails from explicitly approved addresses. Reject everything else.

import type { GetInboxThreadEmailResponseSuccess as InboxEmail } from 'resend';

const ALLOWED_SENDERS = [
  '[email protected]',
  '[email protected]',
];

// `from` is either `address` or `Name <address>`. Compare the address only:
// a substring check would accept a display name such as "[email protected]".
function senderAddress(from: string): string {
  const match = from.match(/<([^<>]+)>\s*$/);
  return (match ? match[1] : from).trim().toLowerCase();
}

function isAllowedSender(from: string): boolean {
  const sender = senderAddress(from);
  return ALLOWED_SENDERS.some(allowed => sender === allowed.toLowerCase());
}

// Identifies the email, so the agent can reply in its thread
type ThreadRef = { inboxId: string; threadId: string; emailId: string };

async function processEmailForAgent(email: InboxEmail, thread: ThreadRef) {
  if (!isAllowedSender(email.from)) {
    console.log(`Rejected email from unauthorized sender: ${senderAddress(email.from)}`);
    await notifyOwnerOfRejectedEmail(email);
    return;
  }

  await agent.processEmail({
    from: email.from,
    subject: email.subject,
    body: email.text || email.html,
    thread,
  });
}

InboxEmail is the email returned by resend.inboxes.threads.emails.get(). The webhook payload carries the same fields without html and text. agent and notifyOwnerOfRejectedEmail stand for your own code.

Security Best Practices
Always Do
Practice Why
Verify webhook signatures Prevents spoofed webhook events
Log all rejected emails Audit trail for security review
Use allowlists where possible Explicit trust is safer than filtering
Rate limit email processing Prevents excessive processing load
Separate trusted/untrusted handling Different risk levels need different treatment
Never Do
Anti-Pattern Risk
Process emails without validation Anyone can control your agent
Trust email headers for authentication Headers are trivially spoofed
Execute code from email content Untrusted input should never run as code
Store email content in prompts verbatim Untrusted input mixed into prompts can alter agent behavior
Give untrusted emails full agent access Scope capabilities to the minimum needed

Webhook Endpoint

After choosing your security level and setting up your domain, create a webhook endpoint. The webhook endpoint MUST be a POST route. Resend sends all webhook events as POST requests.

Critical: Use raw body for verification. Webhook signature verification requires the raw request body.

  • Next.js App Router: Use req.text() (not req.json())
  • Express: Use express.raw({ type: 'application/json' }) on the webhook route
Next.js App Router
// app/webhook/route.ts
import { Resend } from 'resend';
import { NextRequest, NextResponse } from 'next/server';

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req: NextRequest) {
  const payload = await req.text();

  let event;
  try {
    event = resend.webhooks.verify({
      payload,
      headers: {
        id: req.headers.get('svix-id') ?? '',
        timestamp: req.headers.get('svix-timestamp') ?? '',
        signature: req.headers.get('svix-signature') ?? '',
      },
      webhookSecret: process.env.RESEND_WEBHOOK_SECRET!,
    });
  } catch {
    return new NextResponse('Invalid signature', { status: 400 });
  }

  if (event.type === 'inbox.email.received') {
    const { inbox_id, thread_id, email_id } = event.data;

    // The webhook payload has no body. Fetch the email to read it.
    const { data: email, error } = await resend.inboxes.threads.emails.get({
      inboxId: inbox_id,
      threadId: thread_id,
      emailId: email_id,
    });

    if (error) {
      // A non-2xx response makes Resend retry the webhook later
      return new NextResponse('Error', { status: 500 });
    }

    // Apply the security level chosen above
    await processEmailForAgent(email, {
      inboxId: inbox_id,
      threadId: thread_id,
      emailId: email_id,
    });
  }

  return new NextResponse('OK', { status: 200 });
}
Express
import express from 'express';
import { Resend } from 'resend';

const app = express();
const resend = new Resend(process.env.RESEND_API_KEY);

const ALLOWED_SENDERS = (process.env.ALLOWED_SENDERS || '')
  .split(',')
  .map((sender) => sender.trim().toLowerCase())
  .filter(Boolean);

const senderAddress = (from) => {
  const match = from.match(/<([^<>]+)>\s*$/);
  return (match ? match[1] : from).trim().toLowerCase();
};

const isAllowedSender = (from) => ALLOWED_SENDERS.includes(senderAddress(from));

app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = resend.webhooks.verify({
      payload: req.body.toString(),
      headers: {
        id: req.headers['svix-id'],
        timestamp: req.headers['svix-timestamp'],
        signature: req.headers['svix-signature'],
      },
      webhookSecret: process.env.RESEND_WEBHOOK_SECRET,
    });
  } catch {
    res.status(400).send('Invalid signature');
    return;
  }

  if (event.type === 'inbox.email.received') {
    const { inbox_id, thread_id, email_id, email } = event.data;

    // The payload already has the sender, so reject before fetching the body
    if (!email || !isAllowedSender(email.from)) {
      console.log(`Rejected email from unauthorized sender: ${email ? senderAddress(email.from) : 'unknown'}`);
      res.status(200).send('OK'); // Return 200 even for rejected emails
      return;
    }

    const { data: fullEmail, error } = await resend.inboxes.threads.emails.get({
      inboxId: inbox_id,
      threadId: thread_id,
      emailId: email_id,
    });

    if (error) {
      res.status(500).send('Error'); // Resend retries the webhook later
      return;
    }

    await processEmailForAgent(fullEmail, { inboxId: inbox_id, threadId: thread_id, emailId: email_id });
  }

  res.status(200).send('OK');
});

app.get('/', (req, res) => res.send('Agent Email Inbox - Ready'));
app.listen(3000, () => console.log('Webhook server running on :3000'));

Resend signs inbox webhooks with the same svix-* headers as every other webhook. inbox.email.received fires for email the inbox receives. The agent's own replies fire inbox.email.sent instead, so subscribe to inbox.email.received only.

For webhook registration via API, tunneling setup, svix fallback, and retry behavior, see references/webhook-setup.md.

Replying from Your Agent

Reply inside the thread. Resend addresses the reply and sets the In-Reply-To and References headers, so the sender's mail client shows it in the same conversation:

import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

async function replyInThread(
  thread: { inboxId: string; threadId: string; emailId: string },
  body: string,
) {
  const { data, error } = await resend.inboxes.threads.emails.reply({
    inboxId: thread.inboxId,
    threadId: thread.threadId,
    emailId: thread.emailId,
    text: body,
  });

  if (error) throw new Error(`Failed to reply: ${error.message}`);
  return data.id;
}

The reply goes to the email's Reply-To addresses, or to its sender when it has none. A sender on your allowlist can set Reply-To to any address, so check email.reply_to against the allowlist too before the agent replies with anything sensitive. Leave replyAll off unless the agent should copy every recipient of the original email.

To start a new conversation, send from the inbox address with resend.emails.send(). For full sending docs, install the resend skill.

Receiving without an Inbox

Use Resend Receiving directly when the user has no custom domain, or their plan has no inbox available. The security levels above apply unchanged. What differs:

  • Address: use the auto-generated <anything>@<your-id>.resend.app address (Dashboard → Emails → Receiving → "Receiving address"), or a custom domain with receiving enabled. No inbox is created.
  • Webhook event: subscribe to email.received instead of inbox.email.received. The payload has email_id, from, to and subject, but no body.
  • Reading the email: fetch it with resend.emails.receiving.get(emailId).
  • Replying: send with resend.emails.send() and set the In-Reply-To header yourself. There are no threads.
if (event.type === 'email.received') {
  if (!isAllowedSender(event.data.from)) {
    return new NextResponse('OK', { status: 200 });
  }

  const { data: email, error } = await resend.emails.receiving.get(event.data.email_id);
  if (error) {
    return new NextResponse('Error', { status: 500 });
  }

  await agent.processEmail({ from: email.from, subject: email.subject, body: email.text || email.html });
}

The webhook verification is the same as in the inbox examples.

Environment Variables

# Required
RESEND_API_KEY=re_xxxxxxxxx
RESEND_WEBHOOK_SECRET=whsec_xxxxxxxxx

# Security Configuration
SECURITY_LEVEL=strict                    # strict | domain | filtered | sandboxed
[email protected],[email protected]
ALLOWED_DOMAINS=example.com
[email protected]               # For security notifications

Common Mistakes

Mistake Fix
No sender verification Always validate who sent the email before processing
Trusting email headers Use webhook verification, not email headers for auth
Same treatment for all emails Differentiate trusted vs untrusted senders
Verbose error messages Keep error responses generic to avoid leaking internal logic
No rate limiting Implement per-sender rate limits. See references/advanced-patterns.md
Processing HTML directly Strip HTML or use text-only to reduce complexity and risk
No logging of rejections Log all security events for audit
Using ephemeral tunnel URLs Use persistent URLs (Tailscale Funnel, paid ngrok) or deploy to production
Using express.json() on webhook route Use express.raw({ type: 'application/json' }) — JSON parsing breaks signature verification
Returning non-200 for rejected emails Always return 200 to acknowledge receipt — otherwise Resend retries
Old Resend SDK version resend.inboxes.* needs Node.js resend >= 6.36.0 or Python resend >= 2.51.0. emails.receiving.get() and webhooks.verify() also need recent versions. See SDK Version Requirements
Comparing from as a whole string from can be Name <address>. Extract the address before you compare it with the allowlist
Replying to Reply-To without checking it A trusted sender can point Reply-To anywhere. Check it against the allowlist before a sensitive reply
Using a "Sending access" API key It can only reply, forward, create drafts and send drafts. Inbox reads and webhook setup need a full access key
Passing secret or svix-* keys to webhooks.verify() Pass webhookSecret, and headers as { id, timestamp, signature }

Testing

Use Resend's test addresses for development:

For security testing, send test emails from non-allowlisted addresses to verify rejection works correctly.

Quick verification checklist:

  1. Server is running: curl http://localhost:3000 should return a response
  2. Tunnel is working: curl https://<your-tunnel-url> should return the same response
  3. Webhook is active: Check status in Resend dashboard → Webhooks
  4. Send a test email from an allowlisted address and check server logs
  • For full sending, receiving and inbox docs, install the resend skill
1---
2name: agent-email-inbox
3description: Use when building any system where email content triggers actions — AI agent inboxes, automated support handlers, email-to-task pipelines, or any workflow processing untrusted inbound email. Always use this skill when the user wants to receive emails and act on them programmatically, even if they don't mention "agent" — the skill contains critical security patterns (sender allowlists, content filtering, sandboxed processing) that prevent untrusted email from controlling your system.
4license: MIT
5metadata:
6 author: resend
7 version: "4.1.1"
8 homepage: https://resend.com/agent-skills
9 source: https://github.com/resend/resend-skills
10 openclaw:
11 primaryEnv: RESEND_API_KEY
12 requires:
13 env:
14 - RESEND_API_KEY
15 envVars:
16 - name: RESEND_API_KEY
17 required: true
18 description: Resend API key for sending and receiving emails
19 - name: RESEND_WEBHOOK_SECRET
20 required: false
21 description: Webhook signing secret for verifying inbound email event payloads
22 - name: SECURITY_LEVEL
23 required: false
24 description: Security level for inbound email processing (strict, moderate, permissive)
25 - name: ALLOWED_SENDERS
26 required: false
27 description: Comma-separated list of allowed sender email addresses
28 - name: ALLOWED_DOMAINS
29 required: false
30 description: Comma-separated list of allowed sender domains
31 - name: OWNER_EMAIL
32 required: false
33 description: Owner email address for forwarding or notifications
34 links:
35 repository: https://github.com/resend/resend-skills
36 documentation: https://resend.com/docs/agent-email-inbox-skill
37inputs:
38 - name: RESEND_API_KEY
39 description: Resend API key for sending and receiving emails. Get yours at https://resend.com/api-keys
40 required: true
41 - name: RESEND_WEBHOOK_SECRET
42 description: Webhook signing secret for verifying inbound email event payloads. Returned as `signing_secret` in the response when you create a webhook via the API.
43 required: false
44references:
45 - security-levels.md
46 - webhook-setup.md
47 - advanced-patterns.md
48---
49 
50# AI Agent Email Inbox
51 
52## Overview
53 
54This skill covers setting up a secure email inbox that allows your application or AI agent to receive and respond to emails, with content safety measures in place.
55 
56**Core principle:** An AI agent's inbox receives untrusted input. Security configuration is important to handle this safely.
57 
58The skill builds the agent on a Resend **Inbox**. An inbox groups email into threads, and your agent replies inside the thread with one call. Resend sets the recipients and the threading headers. If the user has no custom domain, or their plan has no inbox available, use [Receiving without an inbox](#receiving-without-an-inbox) instead. The security levels are the same for both.
59 
60### Why Webhook-Based Receiving?
61 
62Resend uses webhooks for inbound email, meaning your agent is notified **instantly** when an email arrives. This is valuable for agents because:
63 
64- **Real-time responsiveness** — React to emails within seconds, not minutes
65- **No polling overhead** — No cron jobs checking "any new mail?" repeatedly
66- **Event-driven architecture** — Your agent only wakes up when there's actually something to process
67- **Lower API costs** — No wasted calls checking empty inboxes
68 
69## Architecture
70 
71```
72Sender → Email → Resend Inbox → inbox.email.received webhook → Your Server → AI Agent
73 ↓
74 Security Validation
75 ↓
76 Process or Reject → Reply in the thread
77```
78 
79## SDK Version Requirements
80 
81Use the Node.js SDK `resend` >= 6.36.0 for the full `resend.inboxes.*` API and the `inbox.*` webhook event types. Always install the latest SDK version. If the project already has a Resend SDK installed, check the version and upgrade if needed.
82 
83The Python SDK `resend` >= 2.51.0 also has the inbox methods. The Go, Ruby, PHP, Java, Rust and .NET SDKs have them too. Install their latest version, and see the [Inboxes API reference](https://resend.com/docs/api-reference/inboxes/create-inbox) for samples in each language. To receive email without an inbox, see [Receiving without an inbox](#receiving-without-an-inbox).
84 
85The table below lists the minimums for the Receiving flow: webhook verification (`webhooks.verify()`) and email receiving (`emails.receiving.get()`). The `resend` skill lists higher minimums because it also covers newer features such as domain claims (`domains.claims.*`). If both skills are loaded, use the higher version.
86 
87| Language | Package | Min Version |
88|----------|---------|-------------|
89| Node.js | `resend` | >= 6.9.2 |
90| Python | `resend` | >= 2.21.0 |
91| Go | `resend-go/v4` | >= 4.0.0 |
92| Ruby | `resend` | >= 1.0.0 |
93| PHP | `resend/resend-php` | >= 1.1.0 |
94| Rust | `resend-rs` | >= 0.20.0 |
95| Java | `resend-java` | >= 4.11.0 |
96| .NET | `Resend` | >= 0.2.1 |
97 
98Install the `resend` npm package: `npm install resend` (or the equivalent for your language). For full sending docs, install the `resend` skill.
99 
100## Quick Start
101 
1021. **Ask the user for their email address.** You need a real email address to send test emails to. Ask the user and wait for their response before proceeding.
1032. **Choose your security level.** Decide how to validate incoming emails *before* any are processed
1043. **Set up the domain.** Verify the user's custom domain for sending, and for receiving unless the inbox uses forwarding (see Domain Setup section)
1054. **Create the inbox.** Create the agent's address with `resend.inboxes.create()` (see Create the Inbox section)
1065. **Create webhook endpoint.** Handle `inbox.email.received` events with security built in from the start. **The webhook endpoint MUST be a POST route.**
1076. **Set up tunneling (local dev).** Use Tailscale Funnel (recommended) or ngrok. See [references/webhook-setup.md](references/webhook-setup.md)
1087. **Create webhook via API.** Use the Resend Webhook API to register your endpoint programmatically. See [references/webhook-setup.md](references/webhook-setup.md)
1098. **Connect to agent.** Pass validated emails to your AI agent, and reply in the thread
110 
111## Before You Start: Account & API Key Setup
112 
113### First Question: New or Existing Resend Account?
114 
115Ask your human:
116- **New account just for the agent?** → Simpler setup, full account access is fine
117- **Existing account with other projects?** → The agent needs a full access key, which reaches every project. Prefer a new account for the agent (see API Key Permissions)
118 
119### Creating API Keys Securely
120 
121> Don't paste API keys in chat! They'll be in conversation history forever.
122 
123**Safer options:**
124 
1251. **Environment file method:** Human creates `.env` file directly: `echo "RESEND_API_KEY=re_xxx" >> .env`
1262. **Password manager / secrets manager:** Human stores key in 1Password, Vault, etc.
1273. **If key must be shared in chat:** Human should rotate the key immediately after setup
128 
129### API Key Permissions
130 
131The agent's server needs a **full access** API key. A "Sending access" key can only reply, forward, create drafts and send drafts. Reading inbox emails or registering webhooks with it returns 401 `restricted_api_key`. A sending access key limited to one domain returns 403 on an inbox of another domain.
132 
133If your human has an existing Resend account with other projects, keep the risk contained:
134 
1351. **Use a dedicated account for the agent** when possible, so a leaked key cannot reach other projects
1362. **Keep the key on the server only.** Never pass it to the AI model or put it in a prompt
1373. **Rotate the key** if it was ever pasted in chat or committed
138 
139## Domain Setup
140 
141An inbox address lives on a custom domain the user has added to Resend. The domain must be verified for sending (DKIM and SPF). To receive email on it, either enable receiving on the domain, or create the inbox with `forwarding: true`.
142 
143**Use a subdomain** (e.g., `agent.example.com`) to avoid disrupting existing email services.
144 
145### Option 1: Receiving on the Domain (Recommended)
146 
147The user must enable receiving in the Resend dashboard: Domains page → toggle on "Enable Receiving".
148 
149Then add an MX record:
150 
151| Setting | Value |
152|---------|-------|
153| **Type** | MX |
154| **Host** | Your domain or subdomain (e.g., `agent.example.com`) |
155| **Value** | Provided in Resend dashboard |
156| **Priority** | 10 (must be lowest number to take precedence) |
157 
158**Tip:** Verify DNS propagation at [dns.email](https://dns.email).
159 
160> DNS Propagation: MX record changes can take up to 48 hours to propagate globally, though often complete within a few hours.
161 
162### Option 2: Forwarding
163 
164Create the inbox with `forwarding: true` when the address already receives mail elsewhere (for example, Google Workspace) and the user cannot change its MX record. Resend gives the inbox a receiving address. The user sets up forwarding from their mailbox to it. Read the address from `receiving_address` with `resend.inboxes.get()`.
165 
166## Create the Inbox
167 
168Create one inbox for the agent's address:
169 
170```typescript
171import { Resend } from 'resend';
172 
173const resend = new Resend(process.env.RESEND_API_KEY);
174 
175const { data, error } = await resend.inboxes.create({
176 emailAddress: '[email protected]',
177 name: 'AI Agent',
178 fromName: 'Acme Agent',
179});
180 
181if (error) throw new Error(`Failed to create inbox: ${error.message}`);
182console.log('Inbox created:', data.id);
183```
184 
185`fromName` is the name recipients see on the agent's replies. The part before the `@` can contain only letters, numbers, `.`, `_`, `%` and `-`, so `agent+test@` returns a 422. A 403 error means the plan has no inbox left; ask the user to upgrade or use [Receiving without an inbox](#receiving-without-an-inbox).
186 
187## Security Levels
188 
189**Choose your security level before setting up the webhook endpoint.** An AI agent that processes emails without security is dangerous — anyone can email instructions that your agent will execute. The webhook code you write next should include your chosen security level from the start.
190 
191Ask the user what level of security they want, and ensure that they understand what each level means.
192 
193| Level | Name | When to Use | Trade-off |
194|-------|------|-------------|-----------|
195| **1** | Strict Allowlist | Most use cases — known, fixed set of senders | Maximum security, limited functionality |
196| **2** | Domain Allowlist | Organization-wide access from trusted domains | More flexible, anyone at domain can interact |
197| **3** | Content Filtering | Accept from anyone, filter unsafe patterns | Can receive from anyone, pattern matching not foolproof |
198| **4** | Sandboxed Processing | Process all emails with restricted agent capabilities | Maximum flexibility, complex to implement |
199| **5** | Human-in-the-Loop | Require human approval for untrusted actions | Maximum security, adds latency |
200 
201For detailed implementation code for each level, see [references/security-levels.md](references/security-levels.md).
202 
203### Level 1: Strict Allowlist (Recommended)
204 
205Only process emails from explicitly approved addresses. Reject everything else.
206 
207```typescript
208import type { GetInboxThreadEmailResponseSuccess as InboxEmail } from 'resend';
209 
210const ALLOWED_SENDERS = [
211 '[email protected]',
212 '[email protected]',
213];
214 
215// `from` is either `address` or `Name <address>`. Compare the address only:
216// a substring check would accept a display name such as "[email protected]".
217function senderAddress(from: string): string {
218 const match = from.match(/<([^<>]+)>\s*$/);
219 return (match ? match[1] : from).trim().toLowerCase();
220}
221 
222function isAllowedSender(from: string): boolean {
223 const sender = senderAddress(from);
224 return ALLOWED_SENDERS.some(allowed => sender === allowed.toLowerCase());
225}
226 
227// Identifies the email, so the agent can reply in its thread
228type ThreadRef = { inboxId: string; threadId: string; emailId: string };
229 
230async function processEmailForAgent(email: InboxEmail, thread: ThreadRef) {
231 if (!isAllowedSender(email.from)) {
232 console.log(`Rejected email from unauthorized sender: ${senderAddress(email.from)}`);
233 await notifyOwnerOfRejectedEmail(email);
234 return;
235 }
236 
237 await agent.processEmail({
238 from: email.from,
239 subject: email.subject,
240 body: email.text || email.html,
241 thread,
242 });
243}
244```
245 
246`InboxEmail` is the email returned by `resend.inboxes.threads.emails.get()`. The webhook payload carries the same fields without `html` and `text`. `agent` and `notifyOwnerOfRejectedEmail` stand for your own code.
247 
248### Security Best Practices
249 
250#### Always Do
251 
252| Practice | Why |
253|----------|-----|
254| Verify webhook signatures | Prevents spoofed webhook events |
255| Log all rejected emails | Audit trail for security review |
256| Use allowlists where possible | Explicit trust is safer than filtering |
257| Rate limit email processing | Prevents excessive processing load |
258| Separate trusted/untrusted handling | Different risk levels need different treatment |
259 
260#### Never Do
261 
262| Anti-Pattern | Risk |
263|--------------|------|
264| Process emails without validation | Anyone can control your agent |
265| Trust email headers for authentication | Headers are trivially spoofed |
266| Execute code from email content | Untrusted input should never run as code |
267| Store email content in prompts verbatim | Untrusted input mixed into prompts can alter agent behavior |
268| Give untrusted emails full agent access | Scope capabilities to the minimum needed |
269 
270## Webhook Endpoint
271 
272After choosing your security level and setting up your domain, create a webhook endpoint. **The webhook endpoint MUST be a POST route.** Resend sends all webhook events as POST requests.
273 
274> **Critical: Use raw body for verification.** Webhook signature verification requires the raw request body.
275> - **Next.js App Router:** Use `req.text()` (not `req.json()`)
276> - **Express:** Use `express.raw({ type: 'application/json' })` on the webhook route
277 
278### Next.js App Router
279 
280```typescript
281// app/webhook/route.ts
282import { Resend } from 'resend';
283import { NextRequest, NextResponse } from 'next/server';
284 
285const resend = new Resend(process.env.RESEND_API_KEY);
286 
287export async function POST(req: NextRequest) {
288 const payload = await req.text();
289 
290 let event;
291 try {
292 event = resend.webhooks.verify({
293 payload,
294 headers: {
295 id: req.headers.get('svix-id') ?? '',
296 timestamp: req.headers.get('svix-timestamp') ?? '',
297 signature: req.headers.get('svix-signature') ?? '',
298 },
299 webhookSecret: process.env.RESEND_WEBHOOK_SECRET!,
300 });
301 } catch {
302 return new NextResponse('Invalid signature', { status: 400 });
303 }
304 
305 if (event.type === 'inbox.email.received') {
306 const { inbox_id, thread_id, email_id } = event.data;
307 
308 // The webhook payload has no body. Fetch the email to read it.
309 const { data: email, error } = await resend.inboxes.threads.emails.get({
310 inboxId: inbox_id,
311 threadId: thread_id,
312 emailId: email_id,
313 });
314 
315 if (error) {
316 // A non-2xx response makes Resend retry the webhook later
317 return new NextResponse('Error', { status: 500 });
318 }
319 
320 // Apply the security level chosen above
321 await processEmailForAgent(email, {
322 inboxId: inbox_id,
323 threadId: thread_id,
324 emailId: email_id,
325 });
326 }
327 
328 return new NextResponse('OK', { status: 200 });
329}
330```
331 
332### Express
333 
334```javascript
335import express from 'express';
336import { Resend } from 'resend';
337 
338const app = express();
339const resend = new Resend(process.env.RESEND_API_KEY);
340 
341const ALLOWED_SENDERS = (process.env.ALLOWED_SENDERS || '')
342 .split(',')
343 .map((sender) => sender.trim().toLowerCase())
344 .filter(Boolean);
345 
346const senderAddress = (from) => {
347 const match = from.match(/<([^<>]+)>\s*$/);
348 return (match ? match[1] : from).trim().toLowerCase();
349};
350 
351const isAllowedSender = (from) => ALLOWED_SENDERS.includes(senderAddress(from));
352 
353app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
354 let event;
355 try {
356 event = resend.webhooks.verify({
357 payload: req.body.toString(),
358 headers: {
359 id: req.headers['svix-id'],
360 timestamp: req.headers['svix-timestamp'],
361 signature: req.headers['svix-signature'],
362 },
363 webhookSecret: process.env.RESEND_WEBHOOK_SECRET,
364 });
365 } catch {
366 res.status(400).send('Invalid signature');
367 return;
368 }
369 
370 if (event.type === 'inbox.email.received') {
371 const { inbox_id, thread_id, email_id, email } = event.data;
372 
373 // The payload already has the sender, so reject before fetching the body
374 if (!email || !isAllowedSender(email.from)) {
375 console.log(`Rejected email from unauthorized sender: ${email ? senderAddress(email.from) : 'unknown'}`);
376 res.status(200).send('OK'); // Return 200 even for rejected emails
377 return;
378 }
379 
380 const { data: fullEmail, error } = await resend.inboxes.threads.emails.get({
381 inboxId: inbox_id,
382 threadId: thread_id,
383 emailId: email_id,
384 });
385 
386 if (error) {
387 res.status(500).send('Error'); // Resend retries the webhook later
388 return;
389 }
390 
391 await processEmailForAgent(fullEmail, { inboxId: inbox_id, threadId: thread_id, emailId: email_id });
392 }
393 
394 res.status(200).send('OK');
395});
396 
397app.get('/', (req, res) => res.send('Agent Email Inbox - Ready'));
398app.listen(3000, () => console.log('Webhook server running on :3000'));
399```
400 
401Resend signs inbox webhooks with the same `svix-*` headers as every other webhook. `inbox.email.received` fires for email the inbox receives. The agent's own replies fire `inbox.email.sent` instead, so subscribe to `inbox.email.received` only.
402 
403For webhook registration via API, tunneling setup, svix fallback, and retry behavior, see [references/webhook-setup.md](references/webhook-setup.md).
404 
405## Replying from Your Agent
406 
407Reply inside the thread. Resend addresses the reply and sets the `In-Reply-To` and `References` headers, so the sender's mail client shows it in the same conversation:
408 
409```typescript
410import { Resend } from 'resend';
411 
412const resend = new Resend(process.env.RESEND_API_KEY);
413 
414async function replyInThread(
415 thread: { inboxId: string; threadId: string; emailId: string },
416 body: string,
417) {
418 const { data, error } = await resend.inboxes.threads.emails.reply({
419 inboxId: thread.inboxId,
420 threadId: thread.threadId,
421 emailId: thread.emailId,
422 text: body,
423 });
424 
425 if (error) throw new Error(`Failed to reply: ${error.message}`);
426 return data.id;
427}
428```
429 
430The reply goes to the email's `Reply-To` addresses, or to its sender when it has none. **A sender on your allowlist can set `Reply-To` to any address**, so check `email.reply_to` against the allowlist too before the agent replies with anything sensitive. Leave `replyAll` off unless the agent should copy every recipient of the original email.
431 
432To start a new conversation, send from the inbox address with `resend.emails.send()`. For full sending docs, install the `resend` skill.
433 
434## Receiving without an Inbox
435 
436Use Resend Receiving directly when the user has no custom domain, or their plan has no inbox available. The security levels above apply unchanged. What differs:
437 
438- **Address:** use the auto-generated `<anything>@<your-id>.resend.app` address (Dashboard → Emails → Receiving → "Receiving address"), or a custom domain with receiving enabled. No inbox is created.
439- **Webhook event:** subscribe to `email.received` instead of `inbox.email.received`. The payload has `email_id`, `from`, `to` and `subject`, but no body.
440- **Reading the email:** fetch it with `resend.emails.receiving.get(emailId)`.
441- **Replying:** send with `resend.emails.send()` and set the `In-Reply-To` header yourself. There are no threads.
442 
443```typescript
444if (event.type === 'email.received') {
445 if (!isAllowedSender(event.data.from)) {
446 return new NextResponse('OK', { status: 200 });
447 }
448 
449 const { data: email, error } = await resend.emails.receiving.get(event.data.email_id);
450 if (error) {
451 return new NextResponse('Error', { status: 500 });
452 }
453 
454 await agent.processEmail({ from: email.from, subject: email.subject, body: email.text || email.html });
455}
456```
457 
458The webhook verification is the same as in the inbox examples.
459 
460## Environment Variables
461 
462```bash
463# Required
464RESEND_API_KEY=re_xxxxxxxxx
465RESEND_WEBHOOK_SECRET=whsec_xxxxxxxxx
466 
467# Security Configuration
468SECURITY_LEVEL=strict # strict | domain | filtered | sandboxed
469[email protected],[email protected]
470ALLOWED_DOMAINS=example.com
471[email protected] # For security notifications
472```
473 
474## Common Mistakes
475 
476| Mistake | Fix |
477|---------|-----|
478| No sender verification | Always validate who sent the email before processing |
479| Trusting email headers | Use webhook verification, not email headers for auth |
480| Same treatment for all emails | Differentiate trusted vs untrusted senders |
481| Verbose error messages | Keep error responses generic to avoid leaking internal logic |
482| No rate limiting | Implement per-sender rate limits. See [references/advanced-patterns.md](references/advanced-patterns.md) |
483| Processing HTML directly | Strip HTML or use text-only to reduce complexity and risk |
484| No logging of rejections | Log all security events for audit |
485| Using ephemeral tunnel URLs | Use persistent URLs (Tailscale Funnel, paid ngrok) or deploy to production |
486| Using `express.json()` on webhook route | Use `express.raw({ type: 'application/json' })` — JSON parsing breaks signature verification |
487| Returning non-200 for rejected emails | Always return 200 to acknowledge receipt — otherwise Resend retries |
488| Old Resend SDK version | `resend.inboxes.*` needs Node.js `resend` >= 6.36.0 or Python `resend` >= 2.51.0. `emails.receiving.get()` and `webhooks.verify()` also need recent versions. See SDK Version Requirements |
489| Comparing `from` as a whole string | `from` can be `Name <address>`. Extract the address before you compare it with the allowlist |
490| Replying to `Reply-To` without checking it | A trusted sender can point `Reply-To` anywhere. Check it against the allowlist before a sensitive reply |
491| Using a "Sending access" API key | It can only reply, forward, create drafts and send drafts. Inbox reads and webhook setup need a full access key |
492| Passing `secret` or `svix-*` keys to `webhooks.verify()` | Pass `webhookSecret`, and `headers` as `{ id, timestamp, signature }` |
493 
494## Testing
495 
496Use Resend's test addresses for development:
497- `[email protected]` — Simulates successful delivery
498- `[email protected]` — Simulates hard bounce
499 
500For security testing, send test emails from non-allowlisted addresses to verify rejection works correctly.
501 
502**Quick verification checklist:**
5031. Server is running: `curl http://localhost:3000` should return a response
5042. Tunnel is working: `curl https://<your-tunnel-url>` should return the same response
5053. Webhook is active: Check status in Resend dashboard → Webhooks
5064. Send a test email from an allowlisted address and check server logs
507 
508## Related Skills
509 
510- For full sending, receiving and inbox docs, install the `resend` skill
511 
View all files on GitHub →

Details

License
MIT
Stars on the repo
★ 218
Checked
Source
resend/resend-skills ↗
Creator
resend · 2 listings
View creator

Similar skills

See all →

More from resend