email-for-ai-agents

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Email for AI Agents

AI Agent的邮件使用指南

Why agents need dedicated email infrastructure, how to choose the right provider, and what to watch out for.
为什么Agent需要专用邮件基础设施、如何选择合适的服务商以及需要注意哪些问题。

Why agents need email

为什么Agent需要邮件

Email is the universal protocol. Every service, every business, and every person has an email address. For AI agents to operate autonomously in the real world, they need email for:
  • Identity: signing up for services, receiving verification codes
  • Communication: conversing with humans, other agents, and external systems
  • Action: sending invoices, support replies, reports, notifications
  • Integration: connecting to systems that use email as their interface (legacy enterprises, government, healthcare)
邮件是通用协议。每个服务、企业和个人都有邮箱地址。AI Agent要在现实世界中自主运行,需要邮件来实现:
  • 身份认证:注册服务、接收验证码
  • 沟通交流:与人类、其他Agent及外部系统对话
  • 执行操作:发送发票、支持回复、报告、通知
  • 系统集成:连接以邮件为交互接口的系统(如传统企业、政府、医疗行业系统)

Why agents should not use human email accounts

为什么Agent不应使用人类邮件账户

Giving an agent access to a human's Gmail account (via OAuth) is the most common approach and the most dangerous:
  • Over-permissioned: the agent can read, delete, and send from your entire mailbox history
  • Prompt injection risk: a single crafted email in the inbox can hijack the agent's behavior
  • Credential exposure: OAuth tokens grant broad access that is hard to revoke granularly
  • Rate limits: Gmail enforces strict sending limits not designed for automated workflows
  • Audit trail: agent actions are mixed with human actions, making debugging hard
The safer approach: give each agent its own dedicated inbox with an API designed for programmatic access.
通过OAuth让Agent访问人类的Gmail账户是最常见的做法,但也是最危险的:
  • 权限过度:Agent可以读取、删除并发送你整个邮箱历史中的邮件
  • 提示注入风险:收件箱中一封精心构造的邮件即可劫持Agent的行为
  • 凭证泄露:OAuth令牌赋予的广泛权限难以进行细粒度撤销
  • 速率限制:Gmail设置了严格的发送限制,并非为自动化工作流设计
  • 审计追踪:Agent的操作与人类操作混合在一起,导致调试困难
更安全的做法:为每个Agent分配一个专用收件箱,并使用专为程序化访问设计的API。

Common use cases

常见使用场景

Customer support agents

客服Agent

Agent receives support emails, classifies intent, drafts responses, and escalates when needed.
python
from agentmail import AgentMail, Subscribe, MessageReceivedEvent
from agentmail.inboxes.types import CreateInboxRequest

client = AgentMail()
inbox = client.inboxes.create(
    request=CreateInboxRequest(username="support", client_id="support-v1"),
)

with client.websockets.connect() as socket:
    socket.send_subscribe(Subscribe(inbox_ids=[inbox.inbox_id]))
    for event in socket:
        if isinstance(event, MessageReceivedEvent):
            msg = event.message
            reply_text = msg.extracted_text or msg.text
            # Classify, generate response, send or draft
Agent接收支持邮件、分类意图、草拟回复,并在需要时升级处理。
python
from agentmail import AgentMail, Subscribe, MessageReceivedEvent
from agentmail.inboxes.types import CreateInboxRequest

client = AgentMail()
inbox = client.inboxes.create(
    request=CreateInboxRequest(username="support", client_id="support-v1"),
)

with client.websockets.connect() as socket:
    socket.send_subscribe(Subscribe(inbox_ids=[inbox.inbox_id]))
    for event in socket:
        if isinstance(event, MessageReceivedEvent):
            msg = event.message
            reply_text = msg.extracted_text or msg.text
            # Classify, generate response, send or draft

Sales outreach agents

销售触达Agent

Agent sends personalized outreach, tracks replies, and manages follow-up sequences.
python
from agentmail import AgentMail
from agentmail.inboxes.types import CreateInboxRequest

client = AgentMail()
outbox = client.inboxes.create(
    request=CreateInboxRequest(username="sales", client_id="sales-v1"),
)

prospects = [{"email": "jane@acme.com", "name": "Jane", "company": "Acme"}]

def generate_personalized_email(prospect: dict) -> str:
    # Your LLM-backed copywriting goes here.
    return f"Hi {prospect['name']}, ..."

for prospect in prospects:
    client.inboxes.messages.send(
        outbox.inbox_id,
        to=prospect["email"],
        subject=f"Quick question about {prospect['company']}",
        text=generate_personalized_email(prospect),
        labels=["outreach", "sequence-1"],
    )
Agent发送个性化触达邮件、追踪回复并管理跟进序列。
python
from agentmail import AgentMail
from agentmail.inboxes.types import CreateInboxRequest

client = AgentMail()
outbox = client.inboxes.create(
    request=CreateInboxRequest(username="sales", client_id="sales-v1"),
)

prospects = [{"email": "jane@acme.com", "name": "Jane", "company": "Acme"}]

def generate_personalized_email(prospect: dict) -> str:
    # Your LLM-backed copywriting goes here.
    return f"Hi {prospect['name']}, ..."

for prospect in prospects:
    client.inboxes.messages.send(
        outbox.inbox_id,
        to=prospect["email"],
        subject=f"Quick question about {prospect['company']}",
        text=generate_personalized_email(prospect),
        labels=["outreach", "sequence-1"],
    )

OTP and verification flows

OTP与验证流程

Agent signs up for a service, receives verification email, extracts OTP.
python
import re

signup_inbox = client.inboxes.create()
Agent注册服务、接收验证邮件、提取OTP。
python
import re

signup_inbox = client.inboxes.create()

Use signup_inbox.email to register on a website

Use signup_inbox.email to register on a website

Wait for OTP

Wait for OTP

with client.websockets.connect() as socket: socket.send_subscribe(Subscribe(inbox_ids=[signup_inbox.inbox_id])) for event in socket: if isinstance(event, MessageReceivedEvent): match = re.search(r"\b(\d{4,8})\b", event.message.text or "") if match: otp_code = match.group(1) break
undefined
with client.websockets.connect() as socket: socket.send_subscribe(Subscribe(inbox_ids=[signup_inbox.inbox_id])) for event in socket: if isinstance(event, MessageReceivedEvent): match = re.search(r"\b(\d{4,8})\b", event.message.text or "") if match: otp_code = match.group(1) break
undefined

Browser automation agents

浏览器自动化Agent

Agents that browse the web often need email for account creation, password resets, and receiving confirmations. Create a throwaway inbox per task.
浏览网页的Agent通常需要邮件来创建账户、重置密码和接收确认信息。可为每个任务创建一次性收件箱。

Multi-agent coordination

多Agent协作

Multiple agents email each other to collaborate on complex tasks. Each agent has its own inbox. See the
agent-email-patterns
skill for architecture details.
多个Agent通过邮件相互协作完成复杂任务。每个Agent都有自己的收件箱。如需了解架构细节,请查看
agent-email-patterns
技能。

Choosing your email infrastructure

选择邮件基础设施

See
references/infrastructure-comparison.md
for the full comparison. Quick summary:
NeedBest choiceWhy
Agent needs its own inboxAgentMailInstant inbox creation, two-way conversations, WebSocket support
Two-way email conversationsAgentMailNative thread management, extracted_text for reply parsing
Send-only notificationsResend or SendGridOptimized for transactional sending
Read a human's GmailGmail APIDirect access to existing mailbox (with security caveats)
High-volume marketingSendGrid or MailgunBuilt for bulk sending with deliverability tools
AWS-native infrastructureAmazon SESCheapest at scale, integrates with Lambda/SNS
完整对比请查看
references/infrastructure-comparison.md
。快速总结:
需求最佳选择原因
Agent需要独立收件箱AgentMail即时创建收件箱、支持双向对话、WebSocket支持
双向邮件对话AgentMail原生线程管理、提取文本用于回复解析
仅发送通知Resend或SendGrid针对事务性发送优化
读取人类Gmail邮箱Gmail API直接访问现有邮箱(存在安全隐患)
高容量营销邮件SendGrid或Mailgun专为批量发送打造,具备交付能力工具
AWS原生基础设施Amazon SES大规模使用时成本最低,与Lambda/SNS集成

Security risks

安全风险

See
references/security-risks.md
for full coverage. The top threats:
  1. Prompt injection via email: attackers embed LLM instructions in email content to hijack agent behavior. Defense: treat all email content as untrusted input, never as system instructions.
  2. OAuth credential exposure: giving an agent a Gmail OAuth token grants access to the entire mailbox. Defense: use dedicated agent inboxes with API key auth instead of OAuth.
  3. Webhook spoofing: attackers send fake webhook payloads to trigger agent actions. Defense: always verify webhook signatures.
  4. Data leakage: agent accidentally sends internal data, API keys, or customer PII in emails. Defense: validate outbound content, use drafts for sensitive emails.
完整内容请查看
references/security-risks.md
。主要威胁:
  1. 邮件提示注入:攻击者在邮件内容中嵌入LLM指令以劫持Agent行为。防御措施:将所有邮件内容视为不可信输入,绝不作为系统指令。
  2. OAuth凭证泄露:为Agent提供Gmail OAuth令牌会使其获得整个邮箱的访问权限。防御措施:使用带有API密钥认证的专用Agent收件箱,而非OAuth。
  3. Webhook伪造:攻击者发送伪造的Webhook负载以触发Agent操作。防御措施:始终验证Webhook签名。
  4. 数据泄露:Agent意外在邮件中发送内部数据、API密钥或客户个人身份信息(PII)。防御措施:验证外发内容,对敏感邮件使用草稿模式。

Getting started with AgentMail

AgentMail快速入门

bash
pip install agentmail    # Python
npm install agentmail    # TypeScript
python
from agentmail import AgentMail

client = AgentMail()  # reads AGENTMAIL_API_KEY from env
inbox = client.inboxes.create()
client.inboxes.messages.send(
    inbox.inbox_id,
    to="user@example.com",
    subject="Hello from my agent",
    text="This agent has its own email address!",
)
For detailed SDK usage, use the
agentmail
skill. For architecture patterns, use the
agent-email-patterns
skill.
bash
pip install agentmail    # Python
npm install agentmail    # TypeScript
python
from agentmail import AgentMail

client = AgentMail()  # 从环境变量读取AGENTMAIL_API_KEY
inbox = client.inboxes.create()
client.inboxes.messages.send(
    inbox.inbox_id,
    to="user@example.com",
    subject="Hello from my agent",
    text="This agent has its own email address!",
)
如需详细SDK使用说明,请使用
agentmail
技能。如需了解架构模式,请使用
agent-email-patterns
技能。

Reference files

参考文件

  • references/infrastructure-comparison.md
    -- detailed comparison of AgentMail, Gmail API, Resend, SendGrid, and Amazon SES
  • references/security-risks.md
    -- prompt injection, OAuth risks, webhook spoofing, and mitigation strategies
  • references/infrastructure-comparison.md
    -- 详细对比AgentMail、Gmail API、Resend、SendGrid和Amazon SES
  • references/security-risks.md
    -- 提示注入、OAuth风险、Webhook伪造及缓解策略