How to send email from an AI agent: MCP, REST API or SMTP

From
Postyard
Sent
Reading
9 minutes

The short answer

Give the agent a real mailbox and pick the connection that fits where it runs: MCP for agents inside Claude, ChatGPT or Cursor, a REST API wrapped as a tool for agents you code yourself, or SMTP with an app password for code that already uses a mail library. Have it draft before it sends, put an idempotency key on every send, and cap how many people it can mail per day.

For your AI assistant View Markdown Ask Claude Ask ChatGPT
On this page
  1. Three ways to send email from an AI agent
  2. MCP vs REST API vs SMTP compared
  3. A send_email tool for an LLM agent
  4. Why idempotency matters for agents that retry
  5. Draft first or send directly?
  6. Schedule a send for later
  7. Handle send errors
  8. Conversational email vs transactional email services
  9. Caps and limits to plan for
  10. Send your agent's first email with Postyard
  11. Questions

To send email from an AI agent, give it a mailbox and one way in: an MCP server if the agent runs inside Claude, ChatGPT or Cursor, a REST API wrapped as a tool if you write the agent's code, or SMTP with an app password if you already use a library such as nodemailer or smtplib. Whichever you pick, have the agent draft before it sends, attach an idempotency key to every send so retries can't send twice, and cap how many people it can mail per day.

No address for the agent yet? Start with How to give an AI agent its own email address. The examples use Postyard's API; the patterns apply to any provider.

Three ways to send email from an AI agent

MCP: for agents inside Claude, ChatGPT or Cursor

MCP (Model Context Protocol) is "an open-source standard for connecting AI applications to external systems" (modelcontextprotocol.io). Your mail host runs an MCP server, the assistant connects to its URL, and it sees mail tools such as send_message and create_draft. You write no code.

As of November 2026:

  • Claude Code and Claude.ai connect to remote MCP servers. For Postyard: claude mcp add --transport http postyard https://api.postyard.dev/mcp, then /mcp to sign in.
  • Cursor takes a remote server in mcp.json with a url and headers, so you can pass "Authorization": "Bearer ${env:POSTYARD_API_KEY}" (Cursor docs).
  • ChatGPT connects to custom remote MCP servers on Business and Enterprise/Edu plans; Pro users get read and fetch permissions only (OpenAI Help).

The MCP spec says there "SHOULD always be a human in the loop with the ability to deny tool invocations" (MCP spec), and Cursor, for one, asks before it runs an MCP tool by default. Postyard goes further on the server side: new OAuth connections start as "Read & draft", and the three send tools (send_draft, reply_to_message, send_message) need an admin to grant mail.send. Connect Claude, ChatGPT or Cursor with MCP has the setup for each client.

REST API: for agents you write yourself

If the agent is your code (your own loop over an LLM API, or an agent framework), wrap one HTTP call as a tool. On Postyard that call is POST /v1/mailboxes/{id}/messages with an Idempotency-Key header. The full tool is below.

SMTP: for code that already uses a mail library

SMTP works with every language and needs only a host, a port and a password. On Postyard, create an app password for the mailbox (in the web app, or POST /v1/mailboxes/{id}/app-passwords) and connect to mail.postyard.dev on 465 (implicit TLS) or 587 (STARTTLS). The username is the mailbox address.

JavaScript
// smtp-send.mjs (Node.js 20+, npm install nodemailer)
import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: "mail.postyard.dev",
  port: 465,
  secure: true, // implicit TLS; for port 587 (STARTTLS) set secure: false
  auth: {
    user: "support@northpour.coffee",
    pass: process.env.POSTYARD_APP_PASSWORD,
  },
});

const info = await transporter.sendMail({
  from: '"Northpour AI Assistant" <support@northpour.coffee>',
  to: "ana@example.com",
  subject: "Your order 1042 shipped",
  text: "Hi Ana,\n\nYour order 1042 left our roastery today.\n\nNorthpour AI Assistant",
});
console.log("accepted:", info.accepted, "id:", info.messageId);
Python
# smtp_send.py (standard library only)
import os
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg["From"] = "Northpour AI Assistant <support@northpour.coffee>"
msg["To"] = "ana@example.com"
msg["Subject"] = "Your order 1042 shipped"
msg.set_content("Hi Ana,\n\nYour order 1042 left our roastery today.\n\nNorthpour AI Assistant")

with smtplib.SMTP_SSL("mail.postyard.dev", 465) as smtp:
    smtp.login("support@northpour.coffee", os.environ["POSTYARD_APP_PASSWORD"])
    smtp.send_message(msg)

The costs of SMTP for an agent: there is no idempotency (if the connection drops after the server accepted the message, you can't tell whether it went), no draft mode, and the app password reads and sends everything in that mailbox. On Postyard, mail sent with an app password also isn't counted against a key's daily cap, though the organization's limits still apply, and a key that has a cap can't create app passwords.

MCP vs REST API vs SMTP compared

MCP REST API SMTP
Setup Add a server URL to the assistant and sign in Write a tool wrapper (about 100 lines) Host, port, username, app password
Auth OAuth sign-in or API key header API key (Bearer py_live_...) Per-mailbox app password
Permission granularity Per connection: read, draft, send; chosen mailboxes; daily cap Per key: same as MCP Full access to one mailbox
Idempotency idempotency_key argument on send tools Idempotency-Key header None
Receiving replies Read tools on the same connection List conversations, or message.received webhooks A separate IMAP connection
Best for Assistants: Claude, ChatGPT, Cursor Your own agent code and frameworks Existing scripts and mail libraries

The permission, idempotency and webhook rows describe Postyard; check the same rows for any provider you consider.

A send_email tool for an LLM agent

This tool works with any model that supports function calling: the JSON Schema is the part every framework shares. It's written against the Anthropic TypeScript SDK and runs on Node.js 24, which runs .ts files directly: npm install @anthropic-ai/sdk, then npm pkg set type=module so Node loads the files as ES modules (npm init -y now writes "type": "commonjs", and the files fail to load under it).

TypeScript
// send-email-tool.ts
import { createHash } from "node:crypto";
import type Anthropic from "@anthropic-ai/sdk";

const API = process.env.POSTYARD_API_URL ?? "https://api.postyard.dev";

export const sendEmailTool: Anthropic.Tool = {
  name: "send_email",
  description:
    "Send one plain-text email from the support mailbox. Only send when your " +
    "instructions allow it. If the result says a message for this task was " +
    "already sent, do not try again with different wording.",
  input_schema: {
    type: "object",
    properties: {
      to: {
        type: "array",
        items: { type: "string" },
        description: "Recipient email addresses (1 to 10).",
      },
      subject: { type: "string" },
      text: { type: "string", description: "Plain-text body." },
    },
    required: ["to", "subject", "text"],
    additionalProperties: false,
  },
  strict: true,
};

export type SendEmailInput = { to: string[]; subject: string; text: string };
type ToolOutput = { content: string; isError: boolean };
type ApiError = { error?: { code: string; message: string; request_id: string } };

const RETRYABLE = new Set(["rate_limited", "unavailable", "idempotency_in_flight"]);

export async function sendEmail(
  input: SendEmailInput,
  ctx: { mailboxId: string; taskId: string },
): Promise<ToolOutput> {
  if (input.to.length < 1 || input.to.length > 10) {
    return { content: "Give 1 to 10 recipients.", isError: true };
  }
  // One key per task and recipient set. A network retry, or the model calling
  // the tool a second time for the same task, can never send twice.
  const to = input.to.map((a) => a.trim());
  const recipients = to.map((a) => a.toLowerCase()).sort().join(",");
  const key =
    "send-" + createHash("sha256").update(`${ctx.taskId}\n${recipients}`).digest("hex");

  let wait = 5; // seconds before the next attempt
  for (let attempt = 1; attempt <= 4; attempt++) {
    if (attempt > 1) await new Promise((r) => setTimeout(r, wait * 1000));
    wait = 5;
    let res: Response;
    try {
      res = await fetch(`${API}/v1/mailboxes/${ctx.mailboxId}/messages`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.POSTYARD_API_KEY}`,
          "Content-Type": "application/json",
          "Idempotency-Key": key,
        },
        body: JSON.stringify({ to, subject: input.subject, text: input.text }),
        signal: AbortSignal.timeout(30_000),
      });
    } catch {
      continue; // timeout or dropped connection: it may have sent, so retry with the same key
    }

    if (res.ok) {
      const send = (await res.json()) as {
        id: string;
        recipients: { address: string; status: string }[];
      };
      const status = send.recipients.map((r) => `${r.address}: ${r.status}`).join(", ");
      return { content: `Sent (send ${send.id}). ${status}`, isError: false };
    }

    const body = (await res.json().catch(() => ({}))) as ApiError;
    const code = body.error?.code ?? `http_${res.status}`;

    if (RETRYABLE.has(code)) {
      wait = Math.min(Number(res.headers.get("retry-after")) || 5, 120);
      continue; // same key, same body
    }
    if (code === "idempotency_key_reused") {
      return {
        content:
          "This task already sent (or was refused) a message to these recipients. " +
          "Do not send again; ask a person if another message is needed.",
        isError: true,
      };
    }
    return {
      content: `Not sent: ${code}: ${body.error?.message ?? res.statusText} (request ${body.error?.request_id ?? "n/a"})`,
      isError: true,
    };
  }
  return {
    content: "No confirmed result after 4 attempts. Retry later with the same task id; it cannot send twice.",
    isError: true,
  };
}

Wire it into the agent loop. The task id comes from your code (a ticket, an order, an inbound message id), never from the model:

TypeScript
// agent.ts
import Anthropic from "@anthropic-ai/sdk";
import { sendEmail, sendEmailTool, type SendEmailInput } from "./send-email-tool.ts";

const client = new Anthropic();
const messages: Anthropic.MessageParam[] = [
  { role: "user", content: "Tell ana@example.com that order 1042 shipped today." },
];

while (true) {
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    tools: [sendEmailTool],
    messages,
  });
  messages.push({ role: "assistant", content: response.content });
  if (response.stop_reason !== "tool_use") break;

  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const block of response.content) {
    if (block.type !== "tool_use" || block.name !== "send_email") continue;
    const out = await sendEmail(block.input as SendEmailInput, {
      mailboxId: process.env.POSTYARD_MAILBOX_ID ?? "",
      taskId: "order-1042-shipped", // your job or ticket id, not the model's
    });
    results.push({
      type: "tool_result",
      tool_use_id: block.id,
      content: out.content,
      is_error: out.isError,
    });
  }
  messages.push({ role: "user", content: results });
}

Run it with POSTYARD_API_KEY, POSTYARD_MAILBOX_ID and ANTHROPIC_API_KEY set: node agent.ts. The key needs the read_draft_send preset; with read_draft the send answers 403 missing_scope, and the model sees that as the tool result.

Why idempotency matters for agents that retry

An idempotency key is a value you send with a request so that repeating the request has the same effect as sending it once. An IETF working-group draft defines the Idempotency-Key header so that "non-idempotent HTTP methods such as POST or PATCH" can be made "fault-tolerant" (IETF draft).

Agents retry in two ways, and both send duplicates without a key:

  1. Transport retries. The request times out after the server accepted it. Your code or SDK tries again, and the recipient gets two emails.
  2. Model retries. The model doesn't see a clear result, re-plans, and calls the tool again, often with slightly different wording.

A random key per HTTP attempt fixes neither. Derive the key from things that stay the same across both kinds of retry: the task id and the recipients. On Postyard, the same key with the same body returns the original result and never sends twice, for as long as the send is kept (180 days). The same key with a different body answers 409 idempotency_key_reused, which the tool above turns into a "don't send again" result for the model. The tool also retries timeouts and dropped connections with the same key, since those are exactly the cases where the first attempt may have gone through. Resend's API accepts the same header and keeps keys for 24 hours (Resend docs).

One detail to plan for: on Postyard, a send the mail server refuses for good (403, such as a daily cap or a suppressed recipient) is stored as that key's result, so retrying with the key replays the refusal. After you fix the cause, send under a new key, for example by adding :2 to the task id.

Draft first or send directly?

Draft first unless the message is low-risk and repetitive.

Draft first Send directly
Replies to customers, vendors or anyone new Templated notices to known recipients (order shipped, meeting moved)
Anything with prices, promises, refunds or legal weight Internal mail between your own mailboxes
The first few weeks of any new agent An agent whose drafts you've approved unchanged for weeks

Draft-first on Postyard: the agent calls POST /v1/mailboxes/{id}/drafts (or POST /v1/messages/{id}/reply-drafts to keep the thread). The draft appears in the Drafts folder of the person's mail app, where they edit and send it. A middle path is to let your own code send the draft with POST /v1/drafts/{id}/send after a check (a rule, an allowlist or a second model), using an Idempotency-Key as well. Build an AI support inbox with human review shows the full workflow.

Schedule a send for later

Scheduling suits agents that write at 3 a.m. but should deliver during the recipient's working hours. Create a draft, then schedule it:

Shell
curl -s https://api.postyard.dev/v1/drafts/$DRAFT_ID/schedule \
  -H "Authorization: Bearer $POSTYARD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"send_at": "2026-11-24T09:00:00-05:00"}'

send_at is RFC 3339, 1 minute to 90 days ahead, and scheduling needs the send scope. The draft goes out with the scheduler's permissions as they are at that time, so revoking the key also stops its scheduled mail. Scheduling again moves the time; editing, sending or deleting the draft cancels it, and DELETE /v1/drafts/{id}/schedule cancels it explicitly.

Handle send errors

Postyard returns every error as { "error": { "code", "message", "request_id" } }. What an agent should do with each:

Status and code What happened What to do
429 rate_limited Too many requests or recipients per minute Wait Retry-After seconds, retry with the same key
503 unavailable Server busy; the send may or may not have happened Wait Retry-After, retry with the same key (it can't send twice)
409 idempotency_in_flight The first attempt is still running Retry shortly with the same key
409 idempotency_key_reused This key was already used for a different message (sent, or refused for good) Stop. Use a new key only if a second message is intended
403 missing_scope The key can read and draft but not send Create a draft instead
403 forbidden Refused for good: daily limit, the agent's cap or a suppressed recipient (the message says which) Stop and tell a person; don't loop
422 invalid A field is wrong (the message names it) Fix the input
422 no_recipient_accepted Every recipient was refused; nothing was sent Check the addresses
429 limit_reached The organization's spending limit is reached An admin raises the limit
402 billing_required The subscription doesn't allow sending (none yet, payment overdue, or ended) Stop and tell an admin; reading still works

Retry-After can be a number of seconds or an HTTP date (RFC 9110); Postyard sends seconds. Retry only rate_limited, unavailable and idempotency_in_flight; retrying anything else wastes the agent's turns.

Conversational email vs transactional email services

Resend, Postmark and Amazon SES are built for mail your application sends: receipts, password resets, alerts. Postmark describes transactional email as "a unique, high-priority message sent to a single recipient" (Postmark). All three can also receive mail and pass it to your code (Resend, Postmark, SES). Postyard itself sends outbound mail through Amazon SES. The difference is the mailbox around it.

You need Use
Password resets, receipts, alerts from your app A transactional service
An agent that answers customers and keeps the thread A real mailbox
A person to review the agent's drafts in their mail app A real mailbox
A newsletter to thousands of subscribers A newsletter or broadcast service (not Postyard)

A mailbox gives replies a place to land, keeps threads together and lets a person take over from any mail app. A transactional service is built for volume and for mail nobody replies to.

Caps and limits to plan for

Set your own caps below your provider's, so a loop stops early. Postyard's limits as of November 2026:

  • Per message: 50 recipients across To, Cc and Bcc; attachments up to 17 MiB in total, at most 20 files.
  • Per minute: 30 messages and 60 recipients per organization, beyond which the API answers 429 rate_limited.
  • Per day: 200 external recipients during the trial, 1,000 in the first 30 paid days, 10,000 after that.
  • Per agent: an optional daily_recipient_cap on each key or connection (PATCH /v1/api-keys/{id}); GET /v1/usage/agents shows each one's external recipients in the last 24 hours.
  • Per month: 5,000 external recipients included, then $0.80 per 1,000, inside a spending limit (new organizations start at $50). Mail between your own Postyard mailboxes doesn't count.
  • Reputation: once an organization has sent to 50 or more external recipients in the last 7 days, sending pauses automatically if more than 4% bounced permanently (at least 5) or more than 0.08% complained (at least 3).

How to keep email sent by AI agents out of spam covers authentication, content and bounce handling.

Send your agent's first email with Postyard

  1. Start a 14-day trial (card required). The plan is $10 a month or $99 a year per organization, with 25 mailboxes and 5,000 outbound recipients a month included (pricing).
  2. Add your domain, publish the DNS records, and create a mailbox such as support@.
  3. Create a key restricted to that mailbox with POST /v1/api-keys (the web app restricts keys to domains; this guide has the request): read_draft for drafts only, or read_draft_send with a daily_recipient_cap of 20.
  4. Connect over MCP (https://api.postyard.dev/mcp) or drop the send_email tool above into your agent. Agents can read llms.txt for the full guide and the OpenAPI document for every route.

Questions people ask

Can Claude or ChatGPT send email on its own?

Only through a tool you connect, such as an MCP server for a mailbox. On Postyard, new MCP connections start as read and draft, so the assistant writes drafts and sending stays off until an admin turns it on.

Should an AI agent send email over SMTP or an API?

Use an API when you can. It gives you keys limited to one mailbox, drafts, idempotency keys that stop retries from sending twice, and structured errors. SMTP is fine for code that already uses a mail library, but it has none of those safeguards.

Why does my AI agent send the same email twice?

Usually a retry: the request timed out after the server accepted it, or the model called the send tool again. Send an Idempotency-Key derived from the task rather than a new random value per attempt, so the second call returns the first result instead of sending again.

Can I use Resend, Postmark or Amazon SES for an AI agent's email?

Yes, for notifications your app triggers, such as receipts and alerts. For conversations where people reply and a person may need to read the thread or review a draft, a real mailbox fits better.

How many emails can an AI agent send per day?

As many as its mail host and your own caps allow. On Postyard, an organization can send to 200 external recipients a day during the trial, 1,000 a day in the first 30 paid days and 10,000 after that, and each key can have a lower daily cap of its own.

Keep reading

All guides