Secure Email API

Email API Security

Build email integrations your users can trust

Connecting to your users' inboxes carries real security stakes. Stored passwords, overly broad OAuth scopes, and unrotated tokens all create attack surfaces that breach user trust and violate GDPR.

Unipile's Email API guide covers the full integration picture. This article focuses on the security layer: what a secure email API must guarantee, what risks to avoid, and how Unipile is architected to protect your users' data by design.

Gmail logo Gmail
Outlook logo Outlook
IMAP logo IMAP
Start building for free
POST /api/v1/accounts/connect
Auth method
"type": "oauth2",
"provider": "GOOGLE",
"scopes": ["gmail.readonly"],
Response
"status": 200,
"password_stored": false,
"token_encrypted": true,
OAuth 2.0 only
GDPR compliant
No passwords stored
EU data residency
Building an email integration?

Read our Complete Email API Guide - OAuth flows, sync, send, and provider comparison.

What Makes an Email API "Secure"?

Security in an email API is not a single feature. It is an architectural choice that spans authentication, authorization, data handling, and infrastructure. A secure email API must guarantee four things simultaneously.

OAuth 2.0 authentication

Users authorize access via their provider's official OAuth flow. No password ever leaves the provider's server or lands in your database.

Minimal token scopes

Each linked account requests only the permissions it actually needs - read-only when no sending is required, send scope only when explicitly needed.

Encryption in transit and at rest

All API traffic uses TLS 1.2+. Stored tokens are encrypted at rest using AES-256. Email content is never persisted beyond the request lifecycle.

OAuth 2.0 vs. storing a password

The most fundamental security decision in any email integration is how you authenticate. Many legacy IMAP integrations ask users to enter their email password and store it. This approach creates a single point of failure: one database breach exposes every user's inbox. OAuth 2.0 eliminates this entirely. See how Google OAuth 2.0 and Microsoft OAuth 2.0 implement this flow.

Password storage (avoid)
Password stored in your database
One breach = all inboxes exposed
No granular permission control
Violates Google and Microsoft ToS
OAuth 2.0 (recommended)
Password never leaves the provider
Short-lived tokens, rotatable
Granular scopes per use case
User can revoke access at any time

Token scopes: read-only vs. send

OAuth scopes define exactly what your application can do with a user's mailbox. Requesting broad scopes when narrower ones would suffice is a serious security anti-pattern. For a CRM that only reads emails to log activity, requesting gmail.modify is unnecessary and exposes users to greater risk if your token is compromised. If your application needs to send email API requests, you will also find a full breakdown of the required scopes per provider in our send email API guide.

Scope Provider What it allows Risk level
gmail.readonly Gmail Read emails only Minimal
gmail.send Gmail Send on behalf of user Scoped
Mail.Read Outlook Read emails only Minimal
Mail.Send Outlook Send on behalf of user Scoped
https://mail.google.com/ Gmail Full mailbox access Broad
Mail.ReadWrite Outlook Read, write, delete Broad

Encryption in transit and at rest

A secure email API enforces TLS 1.2 or higher on all API endpoints. No plaintext communication is acceptable. Beyond transit, any tokens or credentials that must be persisted - OAuth refresh tokens, for instance - must be encrypted at rest using a strong symmetric cipher (AES-256). Equally important: email content itself should never be stored beyond what the request requires. Reading and surfacing an email in your UI does not require persisting its body in your database.

Email API Security Risks to Avoid

Most email integration security failures are not exotic attacks - they are predictable mistakes in how credentials, tokens, and data are handled. The four patterns below account for the majority of real-world incidents in email API integrations.

Risk 1
Storing user credentials (IMAP password)

Asking users to enter their email password and storing it - even encrypted - is the highest-risk pattern in email integration. It makes your database a high-value target. If an attacker gains access to your credential store, they gain direct access to every user's inbox. Beyond the security risk, Google and Microsoft explicitly prohibit password-based access to Gmail and Outlook accounts for third-party apps. IMAP with password is only acceptable for self-hosted or legacy mail servers where OAuth is genuinely unavailable.

The fix
Use OAuth 2.0 for Gmail and Outlook. For IMAP-only providers, treat credentials as secrets: encrypt at rest with AES-256, never log them, and scope database access tightly so only the connection service can read them.
Risk 2
Overly broad OAuth scopes

Requesting https://mail.google.com/ (full Gmail access) when you only need to read a user's sent folder is a scope anti-pattern. Broad scopes increase the blast radius of a token compromise and erode user trust during the OAuth consent screen - users who see "read, compose, send, and permanently delete all your email" are right to hesitate. Both Google and Microsoft now flag unnecessary scope usage during app reviews.

The fix
Map each feature to the minimum scope required. Start with read-only. Add send scope only when your use case genuinely requires sending. Document the scope rationale for your OAuth app review submission.
Risk 3
No token rotation

OAuth access tokens are short-lived by design - typically one hour for Gmail and Outlook. Refresh tokens can persist for months or indefinitely. If you store refresh tokens without a rotation strategy, a leaked refresh token grants long-term access to the user's mailbox. Some integrations also cache access tokens well past their expiry and fail to handle revocation events (when a user removes your app from their Google or Microsoft account settings).

The fix
Implement token rotation on every refresh cycle. Listen to provider webhook events for token revocation. Immediately invalidate cached tokens when a user disconnects their account. Never store access tokens - they should be fetched fresh from the refresh token when needed.
Risk 4
Logging email content

Application logs are often less protected than primary databases, retained for longer, and replicated to multiple systems (log aggregators, monitoring services, error trackers). Logging full email bodies, headers containing personal data, or recipient lists creates a significant GDPR exposure: you are processing personal data in a context the user never consented to and cannot audit. Error logs that include raw API responses can inadvertently capture entire email threads.

The fix
Implement log scrubbing at the middleware layer. Log metadata only (message ID, timestamp, status code) - never body content or personal data fields. Apply short log retention policies for email-related events and ensure log storage is subject to the same access controls as your primary datastore.

GDPR Compliance for Email API Integrations

Email data is among the most sensitive personal data categories under GDPR. When your application accesses a user's inbox via an API, you become a data processor. That creates concrete legal obligations around residency, consent, and erasure that your email API architecture must support.

01
Data residency

EU personal data must remain within the EU or in countries with an adequacy decision. Your email API infrastructure must offer EU-hosted endpoints.

02
Explicit consent

Users must explicitly authorize access to their mailbox. The OAuth consent screen must clearly state what data will be accessed and for what purpose.

03
Right to erasure

When a user requests deletion or disconnects their account, all associated tokens, cached data, and personal data must be purged within GDPR timelines.

Data residency

Under GDPR Article 44, transferring personal data outside the European Economic Area requires either an adequacy decision, Standard Contractual Clauses (SCCs), or another valid legal mechanism. For email API integrations serving EU users, the infrastructure that stores OAuth tokens, processes email metadata, or caches message content must be hosted in the EU. Choosing an API provider without EU data residency options forces you to rely on SCCs and additional compliance overhead. For healthcare or financial use cases where HIPAA-adjacent requirements apply, data residency becomes even more critical.

Key principle

Your email API provider is a sub-processor under GDPR. You must have a Data Processing Agreement (DPA) in place with them, and their infrastructure must support EU data residency for any EU user data they process on your behalf.

User consent flow

The OAuth authorization flow serves as the technical implementation of GDPR consent for email access - but only if it is designed correctly. The consent screen must accurately describe what the application will access, in plain language. Requesting scopes beyond what your privacy policy describes creates a compliance gap. Users must also be able to complete this flow without coercion: connecting their email account must not be a forced condition for accessing your core service unless email access is genuinely the service itself.

Right to erasure - account disconnection

GDPR Article 17 grants users the right to erasure. In an email integration context, this means your application must be able to immediately and completely remove all traces of a user's email access when requested. This is not just about deleting the OAuth token - it covers every artifact created during the integration's lifetime.

What must be deleted
OAuth access and refresh tokens
Any cached email metadata (subjects, senders)
Synced message IDs and thread identifiers
Linked account record and settings
Webhook subscription records for that account
What must happen at the provider
Token revoked via provider API (not just locally deleted)
App access removed from user's Google/Microsoft account
All push notification channels unregistered
Deletion confirmed and timestamped for audit log

How Unipile Handles Email API Security

Security is not a feature you add to Unipile - it is the default behaviour of the platform. Unipile is purpose-built to deliver a secure email API where authentication, email data security, and compliance controls are built in by default - not bolted on. Every architectural decision in how Unipile connects to Gmail, Outlook, and IMAP accounts is made with the security and privacy of end users as the primary constraint.

OAuth 2.0 only - no password storage

Unipile connects to Gmail via Google OAuth 2.0 and to Outlook and Microsoft 365 via Microsoft OAuth 2.0. Your users authenticate directly through the provider's official consent screen. No password ever passes through Unipile's infrastructure. For IMAP accounts where OAuth is unavailable, credentials are encrypted at rest with AES-256 and are never exposed via any API response - including the IMAP API guide covers this architecture in detail.

Gmail OAuth 2.0
Microsoft OAuth 2.0
IMAP encrypted at rest
Minimal scope requests

Unipile requests the narrowest OAuth scopes necessary for the features your SaaS application enables. If your integration only reads emails to populate a CRM activity feed, Unipile requests read-only scopes. Send scope is added only when your implementation explicitly requires sending. This reduces the blast radius of any credential issue and makes your app's OAuth consent screen straightforward for end users to approve.

Read-only by default
Send scope on demand
No broad mailbox access
EU data residency option

For SaaS teams serving EU customers, Unipile provides EU-hosted infrastructure options. OAuth tokens, linked account metadata, and any transiently processed email data remain within EU jurisdiction. This allows you to maintain a clean GDPR data processing record and enter into a Data Processing Agreement with Unipile as your sub-processor - a legal requirement under GDPR Article 28 for any processor handling EU personal data on your behalf.

EU infrastructure available
DPA available
GDPR Article 28 compliant
Instant account disconnection

Unipile exposes a DELETE endpoint for linked accounts. Calling it immediately revokes the OAuth token at the provider level, purges all associated metadata from Unipile's infrastructure, and cancels any active webhook subscriptions. This gives you a clean, single-API-call path to fulfil GDPR right-to-erasure requests related to email access - no manual cleanup across multiple provider dashboards required.

Single API call deletion
Token revoked at provider
Right to erasure ready
Developer docs
See how Unipile handles security

Read the full API reference - authentication flows, token management, and webhook security.

Read the Email API Guide

Compliance Certifications

Unipile is independently audited and certified across the three compliance frameworks most relevant to secure email API integrations: security operations, data protection, and Google API access.

SOC 2 Type II
CERTIFIED

Audited by an independent third party. Covers security, availability, and confidentiality trust service criteria across Unipile's infrastructure.

GDPR
COMPLIANT

Full compliance with EU data protection regulations. Unipile acts as Data Processor. All data hosted exclusively in the EU. DPA available upon request.

CASA Tier II
CERTIFIED

Google Cloud Application Security Assessment. Validates security controls for applications accessing Google user data, including Gmail OAuth scopes.

Your app inherits these certifications

When you build on Unipile, your secure email integration benefits from the same security controls that passed these audits. This is particularly relevant for CASA Tier II: apps built on top of a CASA-certified secure email API can maintain their own compliance status across the entire integration chain — without a separate audit of the email layer.

View full security & compliance page

Security Checklist for Email API Integration

Use this checklist before shipping any email API integration to production. All items must be validated before the integration can be considered production-ready from a security standpoint.

Authentication
OAuth 2.0 used for Gmail and Outlook - no password stored
IMAP credentials (if used) encrypted at rest with AES-256
Refresh tokens encrypted at rest, access tokens never stored
Token rotation implemented on every refresh cycle
Token revocation event handled (user removes app at provider)
Scopes and permissions
Only minimum required scopes are requested per linked account
Read-only scope used unless sending is explicitly required
Scope rationale documented for OAuth app review
Scopes listed in privacy policy match scopes requested
GDPR and compliance
DPA signed with your email API provider
EU data residency confirmed for EU user data
Right-to-erasure flow implemented (account deletion removes all data)
Consent event recorded with timestamp and scopes granted
Data handling and logging
Email body content never written to application logs
All API traffic uses TLS 1.2 or higher
Email content not persisted beyond the request lifecycle
Short log retention policy applied to email-related events
Production-ready
Build a Secure Email Integration

OAuth 2.0, minimal scopes, EU data residency, instant account disconnection - all included in a single secure email API. Connect Gmail, Outlook, and IMAP with encrypted email access and no password storage.

Start building for free View pricing
No password stored
GDPR compliant
Gmail, Outlook, IMAP
EU data residency

Secure Email API - FAQ

Common questions about email API security, OAuth, and compliance

IMAP can be secure, but it depends entirely on implementation. The protocol itself transmits data over TLS when properly configured, so the transit layer is not the issue. The risk is in how credentials are handled. IMAP requires a username and password - unlike Gmail and Outlook which support OAuth 2.0, IMAP has no delegated authorization standard. This means your application must store or retrieve the user's password each time it connects. That is manageable if credentials are encrypted at rest with AES-256, access to the credential store is tightly scoped, and passwords are never logged or exposed via API responses. For Gmail and Outlook, always prefer OAuth 2.0 over IMAP with password - both providers require it for third-party applications. IMAP with password is appropriate only for self-hosted mail servers or legacy corporate environments where OAuth is genuinely unavailable. Read more in the IMAP API guide.

HIPAA compliance for an email API integration is achievable but requires careful architecture. HIPAA does not certify email providers - rather, it requires that any system handling Protected Health Information (PHI) implements specific technical safeguards: encryption in transit and at rest, audit controls, access controls, and automatic logoff for inactive sessions. For an email API, this means: using OAuth 2.0 so no passwords are stored, ensuring tokens and any cached metadata are encrypted at rest, never logging email content that might contain PHI, and having a Business Associate Agreement (BAA) in place with your API provider. Gmail and Outlook both offer HIPAA-eligible configurations under Google Workspace and Microsoft 365 Business plans respectively, with a signed BAA from the provider. Your email API layer must also sign a BAA with you if it processes or transmits PHI on your behalf. From a practical standpoint, the safest HIPAA path is to treat email content as transient - read it, process it, surface it - but never persist the body or attachments in your own database.

Revoking access to a user's email involves two distinct actions that must both happen. First, revoke the token at the provider level. For Gmail, call Google's token revocation endpoint (https://oauth2.googleapis.com/revoke). For Outlook, call Microsoft's revocation endpoint or remove the app from the user's Microsoft account. Simply deleting the token from your database is not sufficient - the token remains valid at the provider until explicitly revoked. Second, purge all local data. Delete the refresh token, any cached access tokens, all email metadata you have stored for that linked account, webhook subscriptions, and the linked account record itself. With Unipile, a single DELETE /accounts/{id} call handles both steps - it revokes the token at the provider and cleans up all associated data on Unipile's infrastructure simultaneously.

Email security typically refers to protecting the email communication itself - spam filtering, phishing detection, DKIM/SPF/DMARC authentication, and encryption of the message in transit between mail servers. Email API security is a different layer entirely: it is about how a third-party application gains programmatic access to a user's mailbox, what data it handles as a result, and how it protects that access. You can have excellent email security (DMARC configured, TLS enforced between servers) while having poor email API security (passwords stored in plaintext, overly broad OAuth scopes). Both matter independently. This article focuses on the API security layer - the architectural decisions your development team makes when integrating with Gmail, Outlook, or IMAP via an API.

Unipile does not persistently store email content. When your application calls the Unipile API to retrieve emails, Unipile fetches the data from the provider (Gmail, Outlook, or IMAP server) in real time and returns it to your application. Email bodies and attachments are not cached or stored on Unipile's infrastructure beyond the request lifecycle. What Unipile does store is the OAuth token (encrypted at rest) and basic linked account metadata needed to maintain the connection - provider type, account identifier, and connection status. This architecture means email content stays between your application and the provider, with Unipile acting as the secure broker rather than a data store. For full details on how Unipile handles data, refer to the developer documentation and request a DPA from the Unipile team.

OAuth 2.0 improves email integration security in four concrete ways. No credential exposure: the user's password never leaves the provider's server - your application only ever receives a short-lived access token. Granular permissions: OAuth scopes let you request exactly the access you need (read-only, send-only) rather than full mailbox control. Revocability: a user can remove your application's access from their Google or Microsoft account settings at any time, without changing their password, and the token becomes immediately invalid. Short-lived tokens: access tokens expire (typically after one hour), limiting the window of exposure if a token is ever compromised. These properties make OAuth 2.0 the only acceptable authentication mechanism for Gmail and Outlook integrations in production SaaS applications. Learn how to implement it for Google OAuth 2.0 and Microsoft OAuth 2.0.

Still have questions? Our team is here to help.

Talk to an expert
en_USEN