Ellipse Gradient for Header

Gmail Integration Guide

Integrate Gmail with enterprise systems through the Gmail REST API, OAuth 2.0, mailbox-change notifications, and workflow-based synchronization.

Gmail integration options at a glance

Gmail provides a REST API for messages, threads, labels, drafts, history, users, and attachments. OAuth 2.0 authorizes mailbox access, with refresh tokens supporting longer-lived integrations and domain-wide delegation available for suitably configured Google Workspace environments. Gmail also provides selected mailbox-change notifications through Google Cloud Pub/Sub after a watch is registered; the notification carries a history ID rather than the complete message. Martini can consume these APIs, coordinate Pub/Sub-driven workflows, schedule watch renewal and synchronization, retrieve paginated changes, transform MIME content, route attachments, and expose controlled APIs for downstream applications.

Integration pointSupported by Gmail?Common use casesHow Martini supports it
REST APIsYesRead and modify messages, threads, labels, drafts, history, users, and mailbox-related resources through the Gmail API.Martini can consume the Gmail REST API from workflows, handle pagination and request orchestration, transform responses, and expose REST APIs that abstract Gmail operations.
Webhooks and outbound callbacksLimitedGmail supports mailbox-change notifications through the users.watch method and Google Cloud Pub/Sub. Notifications provide a history ID rather than a complete message and are not universal per-message webhooks.Martini can coordinate a Pub/Sub-based notification design where the required endpoint and permissions are available, then call Gmail history APIs to retrieve the actual changes.
Incremental synchronizationYesInitial synchronization followed by history.list calls allows integrations to retrieve changes from a stored history ID. An expired history ID requires a full or appropriately scoped resynchronization.Martini workflows can persist history IDs, process changes before advancing state, recover from history expiration, and combine scheduled synchronization with notification-driven processing.
Batch requestsLimitedGmail supports HTTP batch requests for grouping multiple API calls, although each operation remains subject to Gmail quotas and authorization rules.Martini can orchestrate grouped or controlled API calls and apply concurrency, retry, and error-handling policies around individual operations.
File and attachment APIsYesMessage attachments can be retrieved through the Gmail API. These resources support message-attachment handling rather than general-purpose file storage or transfer.Martini can retrieve attachment resources, decode and validate content, map metadata, and route files to target applications or services while tracking attachment IDs.
AuthenticationYesGmail uses OAuth 2.0 user authorization, refresh tokens, and, for configured Google Workspace environments, service accounts with domain-wide delegation.Martini can store protected credentials and configuration, invoke authorized API requests, and separate environment-specific authorization details from workflow logic.
SDKsYesGoogle provides optional client libraries for Java, Python, Node.js, PHP, .NET, and Ruby. Direct REST calls remain available.Martini can consume the documented REST endpoints directly and use custom JVM-compatible logic when specialized processing is required; an SDK is not required for the integration.

How Gmail exposes data and business events

Gmail REST APIs

The Gmail API is a REST interface for users, messages, threads, labels, drafts, history, attachments, and related mailbox operations. It supports retrieving different message representations and performing authorized mailbox actions.

Martini implementation pattern

Martini consumes Gmail REST endpoints from workflows, supplies OAuth 2.0 authorization, handles page tokens and response normalization, maps Gmail objects to canonical models, and invokes downstream APIs or exposes a controlled internal API for other applications.

Implementation sequence

Authorize access with the required Gmail OAuth 2.0 scopes
Call the relevant Gmail REST resource
Follow page tokens until the operation is complete
Parse message, thread, label, history, or attachment data
Map the result to the target application model
Persist correlation and synchronization state

Gmail mailbox-change notifications

Gmail provides selected mailbox-change notifications through users.watch and Google Cloud Pub/Sub. A notification identifies a mailbox and history ID but does not contain the complete changed message.

Martini implementation pattern

Martini can coordinate a notification-driven workflow when the Pub/Sub topic, permissions, and receiving endpoint are configured. The workflow treats the notification as a signal, calls Gmail history.list, retrieves affected resources, and renews the Gmail watch before it expires.

Implementation sequence

Register or renew the Gmail watch registration
Receive the mailbox-change notification through the configured messaging path
Extract the mailbox identifier and history ID
Call Gmail history.list to identify affected changes
Retrieve required messages, threads, labels, or attachments
Process the changes and persist the latest successful history ID

Incremental synchronization

Gmail supports incremental synchronization through an initial mailbox sync followed by history.list requests using a stored history ID. History can become unavailable, requiring a full or scoped resynchronization.

Martini implementation pattern

Martini uses a scheduled or notification-driven workflow with durable synchronization state. It advances the stored history ID only after downstream processing succeeds and provides a recovery branch for expired or missing history.

Implementation sequence

Perform the initial mailbox synchronization
Store the returned history ID securely
Retrieve subsequent changes using history.list
Apply filters and retrieve the required resource details
Complete downstream processing successfully
Persist the newest history ID or start recovery when history has expired

Gmail attachments

Gmail exposes message attachments through dedicated API resources. Attachments are associated with messages and may be represented alongside nested MIME parts, inline content, and encoded body data.

Martini implementation pattern

Martini retrieves attachment resources after identifying qualifying messages, decodes and validates the content, maps metadata, and routes the file to a target application or service. The workflow records Gmail message and attachment IDs for duplicate protection.

Implementation sequence

Identify messages with relevant attachment parts
Retrieve each attachment resource
Decode and validate the content and metadata
Apply file type, size, and routing rules
Write the attachment to the target application or service
Persist attachment identifiers and processing results

Common Gmail integration patterns

Pattern 1: Process inbound Gmail messages

When to use this pattern

Use this pattern when operational or customer emails should become structured work in another application. A scheduled workflow or mailbox-change notification can identify relevant messages, while labels and message metadata reduce unnecessary retrieval.

Integration direction
Gmail
Martini
ServiceNow
Example Mapping
Gmail FieldCanonical FieldTarget Field
Message.idexternalMessageIdcorrelation_id
Message.payload.headers.FromsenderEmailcaller_email
Message.payload.headers.Subjectsubjectshort_description
Message.payload.bodymessageTextdescription
Martini implementation pattern

Martini receives a notification or runs a scheduled synchronization, calls Gmail history APIs, filters by sender, subject, label, or metadata, and parses the selected MIME content. It validates required fields, creates or updates the target item, applies a processed Gmail label where appropriate, and retains message and thread IDs so retries do not create duplicates.

Martini capabilities used
  • workflows
  • API consumption
  • data mapping
  • business rules
  • error handling

Pattern 2: Send controlled transactional email

When to use this pattern

Use this pattern when an internal application needs Gmail to send a notification, approval request, or operational message from an authorized mailbox. Gmail sending limits and Workspace policies should be evaluated before production use.

Integration direction
Salesforce
Martini
Gmail
Example Mapping
Gmail FieldCanonical FieldTarget Field
recipienttoAddressesMessage.raw To header
subjectemailSubjectMessage.raw Subject header
bodyemailBodyMessage MIME body
attachmentsoutboundAttachmentsMessage MIME attachment parts
Martini implementation pattern

Martini exposes or consumes an internal API request, validates recipients and content, constructs the Gmail message representation, and calls the Gmail send operation using OAuth-authorized credentials. It records a business correlation key, handles uncertain outcomes conservatively, and routes quota or authorization failures for controlled retry or review.

Martini capabilities used
  • APIs
  • workflows
  • data mapping
  • business rules
  • error handling

Pattern 3: Synchronize Gmail correspondence to a CRM

When to use this pattern

Use this pattern when customer or prospect correspondence should be available as activities, notes, or case context in a CRM. Incremental history synchronization avoids repeatedly scanning an entire mailbox.

Integration direction
Gmail
Martini
Salesforce
Example Mapping
Gmail FieldCanonical FieldTarget Field
Message.idemailMessageIdExternal_Id__c
Thread.idconversationIdThread_Identifier__c
Message.internalDatereceivedAtActivityDateTime
Message.payload.headers.FromcontactEmailWhoId or contact email
Martini implementation pattern

Martini performs an initial synchronization, stores the Gmail history ID, and then processes history changes from notifications or a schedule. It matches contacts using configured business rules, maps headers and message content to CRM activities, preserves thread correlation, and advances the checkpoint only after the CRM write succeeds.

Martini capabilities used
  • scheduled workflows
  • API consumption
  • data mapping
  • business rules
  • error handling

Pattern 4: Route Gmail attachments to a business application

When to use this pattern

Use this pattern when invoices, forms, reports, or other email attachments must be delivered to a target system. It is appropriate for message attachments, not as a replacement for general-purpose file transfer or storage.

Integration direction
Gmail
Martini
NetSuite
Example Mapping
Gmail FieldCanonical FieldTarget Field
Message.idsourceMessageIdexternal_email_id
Attachment.filenamedocumentNamefile_name
Attachment.mimeTypecontentTypemime_type
Attachment.datadocumentContentfile_content
Martini implementation pattern

Martini identifies qualifying messages using history, labels, and metadata, retrieves attachment resources, validates file type and size, and sends the content to the target API. It records message and attachment IDs, applies a processing label only after success, and retries transient failures without duplicating completed transfers.

Martini capabilities used
  • workflows
  • API consumption
  • file handling
  • data mapping
  • error handling

Applications commonly integrated with Gmail

Gmail can be integrated with named business applications when email is used for intake, correspondence, notifications, or operational collaboration. Martini can orchestrate these flows without requiring a dedicated Gmail connector, using Gmail's REST API, OAuth 2.0 authorization, mailbox-change synchronization, and target application APIs.

Application Scenario Direction Martini Pattern
Salesforce Synchronize customer correspondence, email-driven leads, activities, or support communications, and send controlled outbound messages from business workflows. Gmail → Martini → Salesforce A Martini workflow retrieves new Gmail messages or history changes, maps headers and message content to Salesforce activities, leads, or cases, and stores Gmail message and thread IDs for idempotency. A separate API-led workflow can receive Salesforce-originated requests and send authorized Gmail messages.
ServiceNow Convert monitored mailbox messages into incidents, requests, or cases and send status notifications through Gmail. Gmail → Martini → ServiceNow Martini uses a scheduled or Pub/Sub-coordinated Gmail synchronization workflow to retrieve matching messages, validate and transform the content, and call ServiceNow APIs. Message IDs and target identifiers are retained to prevent duplicate ticket creation, while failures are routed through retry and error handling.
Zendesk Route support emails into tickets and support outbound responses or notifications through an authorized Gmail mailbox. Gmail → Martini → Zendesk A Martini workflow filters Gmail messages by label, sender, or subject, decodes the relevant MIME parts and attachments, and creates or updates Zendesk tickets. It can also receive outbound ticket events through an API and map them to Gmail send requests.
Jira Create or update issues from project or operational emails and send workflow notifications to mailbox recipients. Gmail → Martini → Jira Martini retrieves selected Gmail messages, applies business rules to identify project or operational requests, maps the content into Jira issue fields, and records Gmail identifiers alongside the Jira issue key. Retry handling and validation prevent duplicate issue creation.
Slack Post selected mailbox alerts or operational email events to channels and coordinate follow-up workflows. Gmail → Martini → Slack Martini processes Gmail history changes or scheduled searches, filters messages according to configured labels and metadata, transforms the relevant summary, and calls Slack's API. The workflow can suppress duplicates using Gmail message IDs and route API failures for retry.
Microsoft Teams Deliver mailbox alerts, approvals, or operational notifications to Teams channels or users. Gmail → Martini → Microsoft Teams A Martini workflow retrieves qualifying Gmail messages, applies privacy and routing rules, formats a concise notification, and sends it to Microsoft Teams through its available API. Sensitive message content can be reduced or excluded before delivery.
HubSpot Synchronize lead or customer correspondence and use Gmail messages in sales or service processes. Gmail → Martini → HubSpot Martini maps Gmail sender and recipient headers, thread context, and message content to HubSpot activities or contacts. It maintains external identifiers and applies matching rules before creating or updating records, with separate handling for outbound Gmail messages.
NetSuite Route finance, order, or vendor mailbox messages into operational workflows and send automated responses. Gmail → Martini → NetSuite Martini identifies relevant Gmail messages using labels and metadata, extracts structured values and attachments, and calls NetSuite APIs after validation. A reverse workflow can receive NetSuite events or requests and send authorized Gmail notifications with controlled retry behavior.

How to build a Gmail integration in Martini

Objective

Establish Gmail authorization using OAuth 2.0 and configure the required environment-specific credentials and scopes.

Instructions in Martini

  • Use the least-privileged Gmail scopes required by the workflow
  • Store client secrets, refresh tokens, or delegated credentials in protected configuration
  • Use domain-wide delegation only when Google Workspace administration has configured it
  • Separate authorization details across development, test, and production environments

Objective

Select a scheduled, API-led, or mailbox-change notification trigger based on latency, reliability, and Google Cloud Pub/Sub availability.

Instructions in Martini

  • Use a Gmail watch and notification path for selected mailbox-change processing
  • Schedule synchronization and watch renewal when a notification path is unavailable or as a recovery mechanism
  • Treat notifications as signals that require follow-up history API calls
  • Define the initial synchronization and recovery path before production deployment

Objective

Call Gmail resources to retrieve messages, threads, labels, history, drafts, or attachments required by the business process.

Instructions in Martini

  • Follow Gmail page tokens for list operations
  • Request an appropriate message format or partial data where possible
  • Use history.list for incremental changes after the initial synchronization
  • Retrieve attachment resources separately when message parts reference them

Objective

Coordinate Gmail calls, target application operations, filtering, enrichment, and state management in a maintainable Martini workflow.

Instructions in Martini

  • Use workflows to separate retrieval, transformation, routing, and downstream writes
  • Apply sender, recipient, subject, label, and metadata rules before expensive processing
  • Persist correlation identifiers and synchronization checkpoints
  • Keep reusable Gmail request and parsing logic separate from target-specific mapping

Objective

Convert Gmail headers, MIME content, thread context, labels, and attachments into the canonical and target data models.

Instructions in Martini

  • Handle plain-text and HTML alternatives, nested MIME parts, inline content, and encoded values
  • Normalize dates, addresses, subjects, and message identifiers
  • Map attachments with their MIME metadata and source identifiers
  • Validate required values and tolerate optional or unknown headers

Objective

Apply routing, privacy, deduplication, labeling, and target matching rules before committing changes.

Instructions in Martini

  • Use Gmail message, thread, and attachment IDs as external correlation keys
  • Apply target matching rules before creating new contacts, activities, cases, or documents
  • Restrict message content and attachments according to data-sensitivity policies
  • Advance the history checkpoint only after all required processing succeeds

Common Gmail data objects used in integrations

ObjectTypical UseCommon target systemsMartini handling
MessageRepresents an individual email with headers, body parts, labels, metadata, and possible attachment references.Salesforce, ServiceNow, Zendesk, Jira, HubSpot, databases, internal APIsMartini retrieves the required message format, parses MIME parts and encoded content, maps business fields, applies filtering and idempotency rules, and routes the result.
ThreadGroups related messages into a conversation for context-aware synchronization and activity tracking.Salesforce, HubSpot, ServiceNow, Zendesk, collaboration platformsMartini can use thread IDs as correlation keys, combine related messages according to business rules, and preserve conversation context in the target system.
LabelApplies system or user-defined mailbox classifications used to filter, route, or mark processed messages.Gmail workflows, CRM and ticketing systems, internal processing storesMartini can query, add, or use labels as workflow criteria and can apply a processing label after successful downstream handling.
DraftStores an unsent message prepared for later editing or sending.Gmail, approval workflows, CRM and service applicationsMartini can map an application request into Gmail draft content or use draft-related API operations within an authorized workflow.
AttachmentRepresents a file part associated with a Gmail message and retrievable through the attachment resource.Document repositories, ServiceNow, Salesforce, NetSuite, storage servicesMartini retrieves attachment data, handles encoding and MIME metadata, validates file rules, routes content, and records attachment IDs to prevent duplicates.
HistoryRecords mailbox changes from a prior history ID and supports incremental synchronization.Synchronization state stores, databases, CRM and ticketing workflowsMartini persists the latest successfully processed history ID, retrieves affected changes, and initiates recovery or full synchronization when history expires.

Authentication and security considerations

OAuth 2.0 authorization

Gmail mailbox access requires OAuth 2.0 authorization. User authorization and refresh tokens support individual mailbox access, while Google Workspace service accounts can use domain-wide delegation when an administrator has configured the required delegated scopes.

Least privilege and secrets

Use the narrowest Gmail scopes that satisfy the workflow. Store client secrets, refresh tokens, and delegated credentials in protected Martini environment configuration rather than workflow logic.

Mailbox data protection

  • Restrict Martini API endpoints that expose Gmail operations.
  • Avoid writing message bodies, tokens, or attachment content to logs unnecessarily.
  • Apply retention and access controls to workflow payloads and error records.
  • Consider Google verification and Workspace administrative review for broad mailbox scopes.

Operational considerations for Gmail integrations

Quotas and pagination

Gmail applies project-level and user-level quotas. Handle rate-limit responses with backoff, control concurrency, request only the required message representation, and continue list operations until page tokens are exhausted.

Synchronization state

Persist history IDs independently of a single workflow execution and advance them only after successful processing. Build a full or scoped resynchronization path for expired history.

Notifications and MIME data

Mailbox-change notifications are signals rather than complete events. Renew watches before they expire and retrieve changes through Gmail history. Message structures can contain nested MIME parts, HTML and plain text, inline content, encoded values, and separate attachment resources.

Retries and idempotency

  • Use message, thread, attachment, and history IDs as correlation keys.
  • Protect downstream writes against duplicate notification and retry delivery.
  • Use exponential backoff for transient quota or transport failures.
  • Define an uncertain-outcome strategy for send operations.

Testing and compliance

Test delegated access, scope approval, watch renewal, history expiration, malformed MIME structures, attachment handling, quota responses, and Gmail sending restrictions. Treat mailbox content as sensitive business and personal data.

Why use Martini instead of scripts or point-to-point integrations?

Centralized orchestration

Martini coordinates Gmail API calls, notification handling, synchronization checkpoints, target-system writes, and recovery paths in workflows rather than scattering logic across individual scripts.

Reusable integration assets

Teams can expose controlled APIs, reuse authentication and transformation logic, and apply consistent business rules for message processing, attachment routing, outbound sending, and CRM or service synchronization.

Maintainable data transformation

Martini provides mappings and workflow logic for variable Gmail message structures, MIME content, labels, threads, and attachments while allowing custom JVM-compatible logic when specialized processing is required.

Operational control

Centralized error handling, retries, logging, checkpoint management, and environment configuration make it easier to operate Gmail integrations than isolated scripts or tightly coupled point-to-point flows.

Frequently asked questions

How can Gmail be integrated with enterprise systems?

Gmail can be integrated through the Gmail REST API using OAuth 2.0. Enterprise workflows can retrieve and send messages, work with threads, labels, drafts, history, and attachments, and use selected mailbox-change notifications through Google Cloud Pub/Sub followed by Gmail history queries.

Can Martini integrate with Gmail?

Yes. Martini can consume the Gmail REST API, orchestrate OAuth-authorized requests, process messages and attachments, maintain incremental synchronization state, and expose APIs for downstream applications. It can also coordinate Gmail mailbox-change notifications through a Google Cloud Pub/Sub-based design when the required permissions and messaging endpoint are available.

Do I need a connector to integrate Gmail with Martini?

No. A dedicated Gmail connector is not required. Martini can integrate with Gmail using the Gmail REST API, OAuth 2.0, Gmail history synchronization, attachment resources, and the documented mailbox-change notification model.

Is there any extra Lonti cost to integrate Gmail with Martini?

Lonti does not charge an additional per-connector or per-vendor fee to integrate Gmail with Martini. Integrations are subject to the provisioned capacity of the Martini environment. Separate costs may apply from Google, cloud infrastructure, Pub/Sub, or other third-party systems depending on subscriptions, usage, quotas, and deployment choices.

Which Gmail integration methods should be used?

The Gmail REST API is the primary integration method. Use OAuth 2.0 with the narrowest suitable scopes, history-based synchronization for incremental processing, attachment resources for message files, and HTTP batch requests selectively where grouping calls is useful. Gmail GraphQL and SOAP APIs were not confirmed.

Does Gmail provide webhooks or event notifications?

Gmail provides limited push-style mailbox-change notifications through users.watch and Google Cloud Pub/Sub. The notification contains a mailbox identifier and history ID, not the full message event, so the integration must call Gmail history APIs. Watch registrations expire and require renewal.

How should Gmail synchronization work?

Perform an initial synchronization, store the resulting history ID, and use history.list for later changes. Persist the newest history ID only after downstream processing succeeds. If Gmail reports that the history is unavailable or expired, run a full or appropriately scoped resynchronization.

How are Gmail errors, retries, and duplicates handled?

Martini can apply retry and error-handling workflows for transient failures such as quota responses, use exponential backoff, and control concurrency. Message IDs, thread IDs, attachment IDs, and history IDs should be stored as correlation and idempotency keys. Sending requires special care because a timeout can occur after Gmail accepts a request.