
oauth vs api keys for ai agent email authentication
API keys are simple but dangerous for autonomous email agents. OAuth gives you scopes, revocation, and audit trails. Here's how to choose.
Your AI agent needs to send email. Before it composes a single message, it needs to authenticate with something: an API key, an OAuth token, or some combination of both. This decision shapes everything downstream, from what happens when credentials leak to whether you can revoke access without torching your entire setup.
Most developers pick the path of least resistance. For a weekend project, that's fine. For an autonomous agent sending email on behalf of users at scale, the wrong choice creates compliance nightmares you won't discover until an incident forces you to care.
I've spent the last year building email infrastructure for agents, and the auth question comes up in almost every onboarding conversation. Here's what I've learned.
OAuth vs API keys for AI agents: at a glance#
| Feature | API Key | OAuth 2.0 |
|---|---|---|
| Delegation | No user consent model | User explicitly grants scoped access |
| Token lifetime | Indefinite (until manually rotated) | Short-lived access tokens + refresh |
| Revocation | Regenerate key, break all clients | Revoke per-token without affecting others |
| Scope granularity | All-or-nothing access | Fine-grained (read, send, manage) |
| Audit trail | Identifies the app, not the user | Links actions to specific user grants |
| Best for | Server-to-server owned infra | User-delegated access, multi-tenant apps |
For email agents acting on behalf of users, OAuth wins on every axis that matters for security and compliance. API keys identify the calling application but don't model user delegation or consent, which means your agent either has full access or none.
How AI agents authenticate with email APIs today#
There are three common patterns, each with different tradeoffs.
Pattern 1: Raw API key in environment variables. The agent reads EMAIL_API_KEY from its environment and uses it for every request. Simple to implement. Also means a single leaked key exposes every inbox the agent manages. There's no way to revoke access for one user without regenerating the key for everyone.
Pattern 2: OAuth with user delegation. The agent requests specific scopes (like gmail.send or mail.readwrite) and receives tokens tied to individual user grants. If one user revokes access, other users are unaffected. The agent can only do what users explicitly permitted.
Pattern 3: Agent-provisioned infrastructure. The agent provisions its own email identity rather than authenticating against a user's existing inbox. No OAuth dance, no shared API keys. The agent owns the mailbox outright. This is what LobsterMail does: the agent creates its own inbox with a single SDK call, and credentials are scoped to that specific mailbox from the start.
Why API keys fall short for autonomous email agents#
An API key is a static string. It doesn't expire, doesn't scope, and doesn't delegate. For an autonomous agent, this creates three specific problems.
No scope boundaries. When your agent holds a Gmail API key (or service account credential), it typically has access to the full mailbox. Read, send, delete, manage filters. If the agent's behavior drifts or its prompt gets manipulated, there's no guardrail limiting what it can do. OAuth scopes let you restrict access to gmail.send only, so even a compromised agent can't read the user's inbox.
Revocation is destructive. Compromised API key? You regenerate it. Every agent instance, every deployment, every integration using that key breaks simultaneously. With OAuth, you revoke the specific token that was compromised. Other grants continue working.
No user consent model. API keys don't capture who authorized what. If your agent sends email on behalf of 50 users via a single key, your audit log shows "the app sent email." Not "User A authorized sending at 3pm on Tuesday." When a compliance audit hits (and for email, they always do), you need that granularity.
What OAuth scopes should an AI email agent request?#
The principle of least privilege matters more for agents than humans. A human checks their own inbox and self-corrects. An agent follows instructions without judgment.
For Gmail, the minimum scopes for a send-only agent:
https://www.googleapis.com/auth/gmail.send For read-and-send:
https://www.googleapis.com/auth/gmail.send
https://www.googleapis.com/auth/gmail.readonly
For Microsoft 365:
Mail.Send
Mail.Read
Never request Mail.ReadWrite or gmail.modify unless your agent genuinely needs to move, delete, or label messages. Every extra scope is attack surface.
PKCE and the machine-to-machine problem#
OAuth was designed for interactive flows where a human clicks "Allow." AI agents don't click buttons. This mismatch has created real friction in the ecosystem.
For agents acting on behalf of users, the Authorization Code flow with PKCE (Proof Key for Code Exchange) remains the standard. OAuth 2.1 makes PKCE mandatory, closing the authorization code interception attack that plagued earlier implementations.
For server-to-server agent communication (no user involved), the Client Credentials flow is appropriate. The agent authenticates as itself, not on behalf of a user. This works well for agents that own their own resources rather than accessing someone else's mailbox.
Credential rotation at scale#
Here's the operational reality nobody discusses in the "just use OAuth" blog posts. If your agent manages 300 inboxes, you're handling 300 refresh tokens. Each expires independently. Each can be revoked independently. Your agent needs retry logic for expired tokens, a secure storage layer for refresh tokens, and monitoring for revocation events.
API keys avoid this complexity, but at the cost of all the security properties listed above. It's not a good trade.
The third option, agent-owned infrastructure, sidesteps this entirely. When the agent provisions its own inbox through a service like LobsterMail, there's one credential per agent (not per user), scoped to the agent's own mailbox. Rotation is straightforward because you're not coordinating across user grants.
Deliverability impact of your auth choice#
This is the gap nobody talks about. Your authentication method affects email deliverability in non-obvious ways.
Shared API keys mean shared sender reputation. If one agent instance using your key sends spam, every message from that key gets tainted. OAuth-scoped tokens at least isolate reputation by sender identity.
Dedicated agent infrastructure takes this further. When your agent has its own domain and its own IP, its reputation is entirely self-contained. Bad behavior by other agents doesn't affect your deliverability. Good behavior compounds into better inbox placement over time.
Compliance considerations for agent-sent email#
CAN-SPAM, GDPR, and SOC 2 all care about attribution. Who authorized this message? On whose behalf was it sent? Can the authorization be traced and revoked?
API keys answer none of these questions cleanly. OAuth tokens answer all of them: the grant captures the user, the scope, the timestamp, and the revocation path.
For agents sending on their own behalf (newsletters, notifications, outbound), the compliance picture simplifies. The agent is the sender. No delegation question exists. But you still need audit trails showing which agent sent what, when, and whether the recipient opted in.
When API keys are actually fine#
I'm not arguing that OAuth is always correct. API keys work well in specific scenarios:
- Your agent only accesses its own resources (not user mailboxes)
- The key is scoped to a single mailbox or service
- You have infrastructure-level key rotation (not manual)
- The blast radius of a leak is limited to one agent's data
If your agent provisions its own inbox and only touches its own email, a scoped API key with automatic rotation is perfectly reasonable. The danger is shared keys with broad permissions acting on behalf of multiple users.
The third path: agent-first email#
The OAuth vs API key debate assumes your agent is authenticating against someone else's infrastructure. There's a simpler framing: give the agent its own email identity from the start.
When an agent owns its inbox outright, the authentication question collapses. There's no user delegation because the agent is the user. There's no scope negotiation because the agent has full authority over its own mailbox and nothing else. Credential rotation is between the agent and its own infrastructure, not coordinated across user grants.
This is the approach we took with LobsterMail. An agent calls LobsterMail.create(), gets its own inbox, and authenticates with a token scoped exclusively to that mailbox. No OAuth consent screens. No shared API keys. No credential coordination across hundreds of user grants.
For agents that need to read a human's existing Gmail inbox, OAuth remains the right tool. But for agents that need their own email presence (sending notifications, receiving webheets, handling verification flows), agent-provisioned infrastructure is simpler and more secure than either alternative.
Frequently asked questions
What is the main difference between OAuth and API keys for AI agent email access?
API keys identify the calling application and grant static access. OAuth models user delegation with scoped, time-limited, revocable tokens. For email agents acting on behalf of users, OAuth provides consent tracking and granular permissions that API keys cannot.
Why do API keys pose a security risk when used by autonomous email agents?
API keys are typically long-lived, broadly scoped, and shared across instances. A single leaked key can expose every mailbox the agent manages, with no way to revoke access for one user without breaking all others.
What OAuth scopes should an AI email agent request for Gmail or Outlook?
Request the minimum needed. For send-only Gmail agents: gmail.send. For Microsoft 365: Mail.Send. Only add gmail.readonly or Mail.Read if the agent genuinely needs to read incoming messages.
Can an OAuth access token be revoked without deleting the AI agent's account?
Yes. OAuth tokens can be revoked individually per user grant. Revoking one user's token doesn't affect other users or the agent's overall registration. This is a major advantage over API key regeneration.
How long do OAuth access tokens last for email APIs, and what happens when they expire?
Gmail access tokens expire after 1 hour. Microsoft tokens last 60-90 minutes. When they expire, the agent uses its refresh token to obtain a new access token without user interaction. If the refresh token is also expired or revoked, re-authorization is required.
What is PKCE and why does it matter for AI agents authenticating with email providers?
PKCE (Proof Key for Code Exchange) prevents authorization code interception attacks. It's mandatory in OAuth 2.1 and protects the token exchange step, which matters for agents running in environments where the redirect could be intercepted.
Does the choice of OAuth vs API key affect email deliverability or sender reputation?
Yes. Shared API keys mean shared sender reputation across all agents using that key. OAuth tokens tied to individual senders isolate reputation. Dedicated agent infrastructure (own domain, own IP) provides the strongest reputation isolation.
How do I rotate credentials if my AI agent's OAuth token or API key is compromised?
For OAuth: revoke the compromised token and re-authorize. Other grants remain valid. For API keys: regenerate the key and update every instance using it. OAuth's per-token revocation makes incident response far less disruptive.
What compliance risks arise when an AI agent uses a shared API key to send email on behalf of multiple users?
Shared keys make it impossible to attribute actions to specific user authorizations. GDPR requires demonstrable consent, CAN-SPAM requires sender identification, and SOC 2 requires audit trails. A shared key satisfies none of these cleanly.
When is it acceptable to use an API key instead of OAuth for an AI email agent?
API keys are appropriate when the agent only accesses its own resources (not user mailboxes), the key is scoped to a single mailbox, rotation is automated, and a compromise only affects one agent's data.
How does agent-to-agent authentication differ from user-to-agent authentication for email workflows?
User-to-agent uses OAuth delegation (the user grants scoped access). Agent-to-agent typically uses Client Credentials flow or mutual TLS, where both parties authenticate as themselves without user involvement.
What is delegated authorization and why does it matter for AI email agents?
Delegated authorization means a user grants an agent limited permission to act on their behalf. OAuth implements this through scoped tokens. Without delegation, the agent either has your full credentials or nothing, which is the API key problem.
How does OAuth 2.1 improve on OAuth 2.0 for AI agent authentication?
OAuth 2.1 makes PKCE mandatory, removes the implicit flow (which was insecure), and requires exact redirect URI matching. These changes close attack vectors that were especially dangerous for non-interactive agent flows.
Is it safe to store OAuth refresh tokens in an AI agent's environment variables?
It's acceptable for single-tenant deployments but risky at scale. Refresh tokens should be encrypted at rest, stored in a secrets manager, and monitored for unauthorized use. Environment variables are readable by any process in the same container.
Can my AI agent get its own email address without OAuth or API key setup?
Yes. Services like LobsterMail let agents provision their own inbox with a single SDK call. The agent authenticates with its own scoped token rather than delegating access to a user's existing mailbox.


