Email API for Developers: Build with Gmail, Outlook & IMAP (2026 Guide)

Table of Contents
Table of Contents
01What is an Email API?
02Why Developers Need One
03Native APIs Compared
04Build vs Buy
05OAuth 2.0 Essentials
06SDKs & Tooling
07Pricing for Developers
08Security & Compliance
09Common Pitfalls
10FAQ
Foundations
01What is an Email API?
02Why Developers Need One
03Native APIs Compared
Integration
04Build vs Buy
05OAuth 2.0 Essentials
06SDKs & Tooling
Operations
07Pricing for Developers
08Security & Compliance
09Common Pitfalls
Reference
10FAQ
Developer Guide 2026

Email API for Developers:
Build with Gmail, Outlook & IMAP

A practical reference for developers building email integrations: compare Gmail API, Microsoft Graph, and IMAP, then see how a unified email API for developers cuts weeks of boilerplate into a single REST call.

Build with Unipile - Free Read the Docs
email-integration.js
// Unified email API for developers
// Read emails from Gmail, Outlook & IMAP
const unipile = require('@unipile/node-sdk');
const client = new unipile.UnipileClient(
'https://api7.unipile.com:13091',
'YOUR_ACCESS_TOKEN'
);
// List all emails, any provider
const emails = await client.email.listAll({
account_id: 'acc_gmail_xyz',
limit: 20
});
// Send email (same API, any provider)
await client.email.send({
account_id: 'acc_outlook_abc',
to: 'user@example.com',
subject: 'Hello from Unipile',
body: 'Your email API is live.'
});
200 OK - emails retrieved across all providers
Works with: Gmail Outlook IMAP
Definition

What is an email API for developers?

Before comparing providers and writing code, here is the precise definition that search engines and your teammates both need.

Snippet definition

An email API for developers is a programmatic interface that lets your application authenticate as a user, then read, send, or manage that user's emails directly inside Gmail, Outlook, or any IMAP mailbox - without ever handling their password. The API authenticates via OAuth 2.0 (or IMAP credentials), returns structured JSON responses, and fires webhooks when new mail arrives. It is categorically different from a transactional email API (SendGrid, Mailgun), which sends marketing or notification mail on your brand's behalf - an email API for developers acts on behalf of your user, inside their existing mailbox.

In practice: a SaaS helpdesk uses an email API to pull support tickets directly from a customer's Gmail inbox. A CRM uses it to sync every email thread a sales rep exchanges with a prospect. An AI agent uses it to read, classify, and draft replies inside a user's Outlook account. These are sync-side, OAuth user-side integrations - not mass-sending pipelines.

Read emails
List, fetch, search and paginate through a user's inbox, sent items, or any label/folder - across providers with a single unified schema.
Send emails
Compose and send from the user's linked account - Gmail, Outlook, or IMAP - with attachments, HTML body, reply-to threading, and CC/BCC support.
Receive webhooks
Subscribe to real-time new-email events. No polling. Unipile normalizes Gmail push notifications and Microsoft Graph subscriptions into one unified webhook format.
Use Cases

Why developers need an email API integration

These are the four product categories where an email API for developers delivers direct business value - reading and acting on real user emails, not sending bulk blasts.

SaaS inbox sync

CRMs, helpdesks, and project management tools need live access to a user's mailbox. Your app authenticates once via OAuth, then reads, threads, and surfaces emails directly in your UI - no copy-paste, no forward rules. The email API integration runs in the background, keeping your data fresh.

AI agents reading user emails

LLM-powered agents need to read and classify real emails to draft replies, extract entities, trigger workflows, or route tickets. An email API for developers gives your AI agent structured JSON access to the inbox - subject, body, attachments, headers - without building a custom mail client.

Helpdesk & ticket automation

Pull support emails directly from customer mailboxes or shared inboxes, tag them by topic, assign agents, and post replies - all programmatically. The email API integration replaces brittle SMTP polling with a proper REST interface and real-time webhooks.

CRM enrichment & outreach tracking

Log every email a sales rep sends or receives against the right contact or deal. Track open/reply status at the thread level. Keep your CRM in sync with real conversation history without asking reps to BCC a magic address. Pure email api integration - user-side, OAuth-based, on behalf of each individual rep.

This is NOT for transactional email. If your use case is sending password resets, order confirmations, or newsletters from your own domain - that is the transactional market (SendGrid, Mailgun, Resend). Unipile's email API for developers addresses the sync/read/write-on-behalf-of-user market: different infrastructure, different compliance requirements, different pricing model.

Native APIs

Gmail API, Microsoft Graph, and IMAP compared

Every email API integration starts with one of three native providers. Here is what each one offers and where each one creates friction for developers.

Gmail API
Google Workspace & personal Gmail
Google
Auth: OAuth 2.0 with Google identity. Scopes: gmail.readonly, gmail.send, gmail.modify
Real-time: Gmail Push Notifications via Google Pub/Sub. Requires separate GCP setup
OAuth consent: "Sensitive scopes" trigger Google verification (weeks) for unverified apps
Rate limits: 250 quota units per user per second. Attachment download adds quota per byte
SDK: google-api-python-client, googleapis/google-api-nodejs-client
Microsoft Graph
Outlook personal + Microsoft 365 / Exchange Online
Microsoft
Auth: OAuth 2.0 via Azure AD. Scopes: Mail.Read, Mail.Send, Mail.ReadWrite
Real-time: Graph change notifications (subscriptions) with validation endpoint. Max 4,230 min TTL
Admin consent: Enterprise M365 tenants require tenant admin to approve delegated permissions
Throttling: 10,000 requests per 10 min per app per tenant. Subscriptions expire and must be renewed
SDK: @microsoft/microsoft-graph-client (Node), msgraph-sdk-python
IMAP
Universal fallback - any provider
RFC 3501
Auth: Password-based (username + password) or SASL XOAUTH2 for Gmail/Outlook via IMAP
Real-time: No native webhooks. Requires IMAP IDLE polling loop in your backend (persistent TCP connection)
Coverage: Works with any provider - ProtonMail Bridge, Fastmail, Yahoo, custom Exchange, corporate servers
Security: Password storage risk. Gmail blocked basic auth in 2022 for consumer accounts. XOAUTH2 required
SDK: imaplib (Python), node-imap (Node - unmaintained), imap-simple. No official vendor SDK
Feature Gmail API Microsoft Graph IMAP Unipile (unified)
Auth method OAuth 2.0 OAuth 2.0 Password / XOAUTH2 OAuth 2.0 (all)
Real-time webhooks Pub/Sub (GCP needed) Graph subscriptions No (IDLE polling) Unified webhook
Response format Gmail JSON (non-standard) Graph JSON (OData) RFC 2822 raw MIME Unified JSON schema
Token refresh Manual (google-auth-library) Manual (MSAL) N/A Managed by Unipile
Rate limits 250 QU/user/s 10k req/10 min Varies by server Abstracted + retry
Send email Yes Yes SMTP only Yes (all providers)
Attachments Requires extra call Max 4MB inline Full MIME Unified attachment API
Setup time (estimate) 1-2 weeks 1-2 weeks 3-5 days Hours
Stop maintaining three separate email integrations
Unipile normalizes Gmail, Outlook, and IMAP into one API. Build once, ship to every provider.
Build it with Unipile
Build vs Buy

Native email API vs unified email API: real code comparison

Seeing both approaches side-by-side - in actual code - makes the tradeoff concrete. Select a language below to compare reading emails natively versus via the Unipile unified email API.

Node.js Python Go / cURL
Native - Gmail API (Node.js)
gmail-native.js
// 1. Install & configure OAuth client const {google} = require('googleapis'); const auth = new google.auth.OAuth2( CLIENT_ID, CLIENT_SECRET, REDIRECT_URI ); // 2. Exchange auth code for tokens const {tokens} = await auth.getToken(code); auth.setCredentials(tokens); // 3. Store & refresh tokens manually // 4. Call Gmail API const gmail = google.gmail({ version: 'v1', auth }); const res = await gmail.users.messages.list({ userId: 'me', maxResults: 10 }); // 5. Fetch full message per ID const msg = await gmail.users.messages.get({ userId: 'me', id: res.data.messages[0].id, format: 'full' }); // 6. Parse base64url-encoded payload yourself
Unified - Unipile email API (Node.js)
unipile-email.js
// 1. One SDK, all providers const unipile = require('@unipile/node-sdk'); const client = new unipile.UnipileClient( API_URL, ACCESS_TOKEN ); // 2. Tokens managed by Unipile // No manual OAuth flow needed // 3. List emails const emails = await client.email.listAll({ account_id: ACCOUNT_ID, limit: 10 }); // 4. Body already decoded // Unified JSON - same schema // for Gmail, Outlook, IMAP console.log(emails.items);
Native - Microsoft Graph (Python)
msgraph_native.py
import msal, requests # 1. MSAL confidential client app = msal.ConfidentialClientApplication( CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET ) # 2. Acquire token on behalf of user result = app.acquire_token_by_auth_code_flow( flow, auth_response ) token = result['access_token'] # 3. Handle token refresh, store securely # 4. Call Graph API headers = {'Authorization': f'Bearer {token}'} r = requests.get( 'https://graph.microsoft.com/v1.0/me/messages', headers=headers ) # 5. Parse OData envelope response
Unified - Unipile email API (Python)
unipile_email.py
import requests # Token managed by Unipile # No MSAL, no OAuth setup headers = { 'X-API-KEY': ACCESS_TOKEN, 'Accept': 'application/json' } # Works for Gmail AND Outlook # Same endpoint, same schema r = requests.get( 'https://api7.unipile.com:13091' '/api/v1/emails', headers=headers, params={ 'account_id': ACCOUNT_ID, 'limit': 10 } ) emails = r.json() # Already parsed, no OData
Native - IMAP (cURL)
imap_native.sh
# IMAP has no REST API # Must use imaplib or node-imap # No cURL equivalent # Example: openssl s_client # (debug only - not production) openssl s_client \ -connect imap.gmail.com:993 \ -quiet # Then send raw IMAP commands: # A001 LOGIN user@gmail.com pass # A002 SELECT INBOX # A003 FETCH 1 RFC822 # A004 LOGOUT # You receive raw RFC 2822 MIME # Must parse headers, decode # base64 parts, handle multipart # boundaries yourself # Also: no webhooks, must IDLE poll
Unified - Unipile email API (cURL)
unipile_email.sh
# REST API - works with any # email provider via cURL curl \ -X GET \ -H "X-API-KEY: $TOKEN" \ -H "Accept: application/json" \ "https://api7.unipile.com:13091 /api/v1/emails ?account_id=$ACCOUNT_ID &limit=10" # Response: clean JSON # { "items": [ { "id": "...", # "subject": "Hello", # "from": { "name": "Alice", # "address": "..." }, # "body_plain": "...", # "date": "2026-05-12T..." } ] } # Same endpoint for Gmail, # Outlook, and IMAP accounts
Start building - free trial Read the full API reference
Authentication

OAuth 2.0 essentials for email API integration

Every production email API integration relies on OAuth 2.0 to authenticate as a user without storing their password. Here is what you need to set up for each provider - and how Unipile handles it for you.

Google OAuth for Gmail API
1
Create a Google Cloud project and enable the Gmail API in the API Library.
2
Configure an OAuth consent screen. Add scopes: gmail.readonly, gmail.send. Sensitive scopes require Google verification for production.
3
Create OAuth 2.0 credentials (Web application type). Note the Client ID and Client Secret.
4
Implement the authorization code flow. Redirect users to Google's auth endpoint, exchange the code for access + refresh tokens.
5
Store and refresh tokens. Access tokens expire after 1 hour. Implement refresh logic using google-auth-library or a custom handler.
Microsoft OAuth for Graph API
1
Register an app in Azure Active Directory (portal.azure.com). Note the Application (client) ID and Directory (tenant) ID.
2
Add API permissions. Under Microsoft Graph, add delegated permissions: Mail.Read, Mail.Send, Mail.ReadWrite.
3
Generate a client secret under "Certificates & secrets". Record it immediately - it is only shown once.
4
Implement auth code flow with PKCE using MSAL.js or msal-python. For enterprise tenants, the admin may need to grant consent.
5
Handle token refresh. Microsoft access tokens expire after 60-90 minutes. MSAL handles refresh automatically if you pass the refresh token correctly.
IMAP: password-based fallback (use carefully)
IMAP uses a username + password credential model - no OAuth by default. This means your app must store the user's password or app-specific password, which creates a security liability. Gmail blocked basic auth for IMAP in 2022 for personal accounts; you must use XOAUTH2 over IMAP instead. For non-Google/Microsoft providers (ProtonMail Bridge, Fastmail, corporate Exchange), IMAP password-based auth remains the only option. Treat it as a last-resort fallback - always prefer OAuth 2.0 when available.
Skip the OAuth plumbing - let Unipile handle it
Unipile manages Google and Microsoft OAuth flows, token storage, and refresh - all behind a single API key. See the OAuth Email API guide for details.
Build your OAuth flow
SDKs & Tooling

SDKs and tooling for email API integration

Whether you are building natively or using a unified layer, the right SDK reduces boilerplate. Here is the current landscape for each provider and for Unipile.

Node.js
Gmail API
npm i googleapis
Official Google client. Covers full Gmail API + other Google services. Maintained by Google. Large dependency footprint. Auth handled via google-auth-library (separate install).
Python
Gmail API
pip install google-api-python-client google-auth-oauthlib
Official Python client. Requires two packages. Verbose initialization - credentials flow is several boilerplate files. Works well once configured.
Node.js
Microsoft Graph
npm i @microsoft/microsoft-graph-client
Official Graph client. Auth via MSAL.js (@azure/msal-node separate). Well-maintained. OData response format requires extra parsing for simple use cases.
Python
Microsoft Graph
pip install msgraph-sdk msal
Official Graph SDK for Python. Async-first (asyncio). Requires Python 3.8+. MSAL handles token acquisition. Well-documented for enterprise M365 scenarios.
Python
IMAP
pip install imapclient
imapclient is the most Pythonic wrapper around imaplib. No official vendor SDK. You handle connection pooling, IDLE loops, and MIME parsing manually. Fallback when OAuth is not available.
REST
Any language
curl / fetch / axios / httpx
All three native email APIs expose REST endpoints - you can use any HTTP client. No SDK required if you prefer minimal dependencies. Unipile's REST API is the same: one endpoint, any language.
Read the SDK docs
Pricing

Developer-friendly pricing: start free, scale transparently

"Free" native email APIs aren't really free. Gmail API and Microsoft Graph cost zero dollars per API call, but each one demands weeks of engineering: OAuth verification cycles, token refresh logic, webhook infrastructure, retry handlers, error mapping. A mid-size team typically burns 3 to 6 weeks before shipping a single feature. Unipile's unified email API for developers replaces that work with a 7-day free trial, no credit card required.

Native, DIY
Gmail API
$0in API fees
per API call (quota-based)
Real cost to ship
3 to 6 weeks of engineering
OAuth consent screen verification: 4 to 6 week wait from Google before production access
Pub/Sub real-time webhooks: separate GCP project, IAM, and infrastructure to host and renew
Token refresh, quota errors, exponential backoff: every edge case is yours to build
Only Gmail. Outlook and IMAP need two more integrations, each with its own complexity
Native, DIY
Microsoft Graph
$0in API fees
per API call (throttling-based)
Real cost to ship
4 to 8 weeks of engineering
Azure AD tenant, app registration, multi-step admin consent for every customer
Webhook subscriptions expire after 4230 minutes: build renewal jobs or lose events
Throttling at 10 000 requests per 10 minutes: build your own backoff and retry layer
Only Outlook and M365. Gmail and IMAP customers need two more integrations

Bottom line: the API calls are free, the engineering is not. Building production-grade email integration on top of native APIs (auth flows, token refresh, error handling, webhook infrastructure, multi-provider abstraction) commonly costs 3 to 8 weeks of senior dev time per provider, plus ongoing maintenance every time Google or Microsoft ships a breaking change. Unipile prices per linked account per month with transparent tiers. See the Free Email API guide for the full breakdown.

Security & Compliance

Security and compliance for email API integrations

When your application handles user emails, compliance is not optional. Unipile is built for the two frameworks that matter for developer-facing products handling European and enterprise data.

SOC 2 Type II
Certified

Unipile is SOC 2 Type II certified. The audit covers the Security, Availability, and Confidentiality trust service criteria. This means independent auditors have verified Unipile's controls over a sustained period - not just at a single point in time. Required by most enterprise buyers and SaaS security questionnaires.

GDPR Compliant
EU Data Regulation

Unipile processes email data as a data processor under GDPR Article 28. Data processing agreements (DPAs) are available for all paid plans. User email data is processed only for the duration of the authenticated session and within the scope granted by the user's OAuth consent. No parallel storage, no data sold to third parties.

Start building - free trial
Common Pitfalls

Common pitfalls in email API integration (and how to fix them)

Every developer building their first email API integration hits the same four walls. Here they are - and how to handle each one correctly.

Rate limit breaches

Gmail's 250 quota units per user per second sounds generous until you realize listing 10 messages costs 5-10 units each and fetching full bodies adds per-byte quota. Microsoft Graph caps at 10,000 requests per 10 minutes per app per tenant. Hitting the limit returns 429 - Too Many Requests. Without retry logic your sync loop crashes silently.

Fix: implement exponential backoff with jitter. Respect the Retry-After header. Batch message fetches when possible. Unipile abstracts rate limits and handles retries automatically.
Token expiry and refresh failures

Google access tokens expire after 3,600 seconds. Microsoft tokens after 60-90 minutes. If your refresh token is revoked (user changes password, revokes app access, or the token has not been used in 6 months for Google), your entire sync silently stops. No error is surfaced unless you monitor the refresh call response.

Fix: monitor refresh token validity separately from access tokens. Store last-refreshed timestamp. Alert when refresh fails. With Unipile, token state is managed server-side - you only interact with your API key.
Webhook subscription expiry

Microsoft Graph subscriptions expire after a maximum of 4,230 minutes (~3 days for mail). Forgetting to renew them means no more push notifications - your app falls back to polling or misses events entirely. Gmail Pub/Sub subscriptions are more persistent but require a GCP subscription to remain valid and the topic to exist.

Fix: implement a background job that renews subscriptions before they expire. Log each renewal. Unipile normalizes webhooks across providers and handles subscription lifecycle internally.
Sync state corruption

Email APIs are eventually consistent. If your sync process crashes mid-run, you may duplicate emails, skip a page of results, or miss deletes. Gmail uses historyId for incremental sync; Microsoft Graph uses deltaToken. Both require careful cursor management across restarts. IMAP has no native sync state - you must maintain your own UID tracking.

Fix: use provider-native delta/history tokens for incremental sync. Persist cursor state to durable storage before processing. Implement idempotency on write operations. Unipile tracks sync state per linked account.
FAQ

Email API for developers - frequently asked questions

Answers to the questions developers ask most often when building their first email API integration across Gmail, Outlook, and IMAP.

01
What is an email API for developers?
An email API for developers is a programmatic interface that lets your application authenticate as a user and then read, send, or manage that user's emails inside Gmail, Outlook, or an IMAP mailbox - without storing their password. It uses OAuth 2.0 for authentication and returns structured JSON. It is different from a transactional email API, which sends marketing or notification mail on your brand's behalf. For the full picture, see the complete Email API Guide.
02
What is the difference between Gmail API and Microsoft Graph for email?
Gmail API and Microsoft Graph are both OAuth 2.0 email APIs but use different auth flows, response formats, and webhook mechanisms. Gmail uses Google Pub/Sub for push notifications and returns messages in a Gmail-specific JSON envelope with base64url-encoded bodies. Microsoft Graph uses change notification subscriptions (max ~3 day TTL) and returns OData-formatted responses. Both require separate SDK setup and token management. See the Gmail API guide and Microsoft Graph guide for full walkthroughs.
03
How do I integrate email API with Node.js?
For a unified approach, install the Unipile Node.js SDK: npm install @unipile/node-sdk. Then create a client with your API URL and access token, and call client.email.listAll() to read emails or client.email.send() to send - across Gmail, Outlook, and IMAP with a single code path. For native Gmail, use the googleapis npm package. For Microsoft Graph, use @microsoft/microsoft-graph-client.
04
What email providers does Unipile's email API support?
Unipile's email API for developers supports three providers: Gmail (Google OAuth), Outlook / Microsoft 365 / Exchange Online (Microsoft OAuth via Microsoft Graph), and IMAP (universal fallback covering any IMAP-compatible mailbox). All three providers share a unified JSON schema - same endpoints, same response format, same webhook structure.
05
Do I need to implement OAuth myself to use an email API?
If you build natively against Gmail API or Microsoft Graph, yes - you must implement the full OAuth 2.0 authorization code flow, store tokens securely, handle token refresh, and manage scope consent. If you use Unipile, the OAuth flow and token management are handled server-side. You link accounts once through Unipile's hosted OAuth flow and then use a single API key. See the OAuth Email API guide for the full implementation walkthrough.
06
What are the rate limits for email APIs?
Gmail API allows 250 quota units per user per second, with each message fetch consuming units proportional to the operation. Microsoft Graph limits to 10,000 requests per 10 minutes per app per tenant. IMAP servers vary by host. Exceeding limits returns 429 Too Many Requests with a Retry-After header. Best practice is exponential backoff with jitter. Unipile abstracts rate limits and handles retries automatically on your behalf.
07
Is IMAP still relevant for email API integration in 2026?
IMAP remains relevant as a universal fallback for providers without a REST API - ProtonMail Bridge, Fastmail, Yahoo, and most corporate Exchange servers. However, Gmail blocked basic IMAP auth for personal accounts in 2022, requiring XOAUTH2. IMAP has no native webhooks, requiring IDLE polling for real-time events. For Gmail and Outlook, their native REST APIs or a unified layer are preferred. See the full IMAP API guide.
08
What compliance certifications does Unipile have?
Unipile is SOC 2 Type II certified and GDPR compliant. SOC 2 Type II means independent auditors have verified Unipile's security, availability, and confidentiality controls over a sustained period. GDPR compliance covers data processing agreements (DPAs) available on paid plans, with user email data processed only within the scope of the user's OAuth consent. No parallel storage, no data sold to third parties.
09
Can I try the email API for developers for free?
Yes. Gmail API and Microsoft Graph are free within quota limits. Unipile offers a 7-day free trial with no credit card required, giving full access to the unified email API for developers - including read, send, webhooks, OAuth account linking, and the Node.js SDK - across Gmail, Outlook, and IMAP. See the free email API guide for details.
10
What is the difference between a transactional email API and an email API for developers?
A transactional email API (SendGrid, Mailgun, Resend) sends emails from your own domain - used for password resets, order confirmations, and marketing campaigns. An email API for developers (Gmail API, Microsoft Graph, Unipile) acts on behalf of your user inside their existing mailbox - reading their emails, sending from their account, and syncing conversation history. These serve entirely different use cases, have different infrastructure, and different compliance requirements. See the Email API Guide for the full picture.

Still have questions? Talk to an email API expert - we'll help you choose the right stack for your use case.

Talk to an expert
en_USEN