Files
dify-plugin-sdks/python/examples/gmail_trigger

Gmail Trigger (Push + History)

Overview

  • Gmail Trigger is a Dify provider that receives Gmail push notifications via Cloud Pub/Sub and emits concrete events based on Gmail History:
    • gmail_message_added (new messages)
    • gmail_message_deleted (deleted messages)
    • gmail_label_added (labels added to messages)
    • gmail_label_removed (labels removed from messages)
  • Dispatch verifies/auths the push, pulls the history delta once, and splits changes for events to consume.
  • Note: API Key is NOT supported for Gmail API access. Use OAuth (gmail.readonly) only.

Prerequisites

Step-by-step Setup

  1. Create a Pub/Sub topic

    • Name: projects/<PROJECT_ID>/topics/<TOPIC_NAME>
    • Grant Gmail publisher role:
      • gcloud pubsub topics add-iam-policy-binding projects/<PROJECT_ID>/topics/<TOPIC_NAME> \ --member=serviceAccount:gmail-api-push@system.gserviceaccount.com \ --role=roles/pubsub.publisher
  2. Install the plugin in Dify

  • Options:
    • If packaged as .difypkg, import it in Difys Plugin Center (Plugins → Import).
    • For local run during development, ensure the runtime installs dependencies in requirements.txt.
  1. Configure OAuth in the provider (one-time)
  • In Google Cloud Console → APIs & Services → Credentials → Create Credentials → OAuth client ID
    • Application type: Web application
    • Authorized redirect URIs: Copy the redirect URI shown by Dify when setting up OAuth for this provider
  • Back in Dify, enter Client ID/Secret; click “Authorize” to complete OAuth (gmail.readonly)
  • The constructor validates the token via users/me/profile
  1. Create a Gmail subscription in Dify
  1. Create a Pub/Sub push subscription to Difys endpoint
    • After the Dify subscription exists, create a push subscription on your topic with the Dify endpoint:
      • gcloud pubsub subscriptions create <SUB_NAME> \ --topic=projects/<PROJECT_ID>/topics/<TOPIC_NAME> \ --push-endpoint="https://<YOUR_DIFY_HOST>/api/plugin/triggers/<SUBSCRIPTION_ID>" \ --push-auth-service-account=<YOUR_SA_EMAIL> \ --push-auth-token-audience="https://<YOUR_DIFY_HOST>/api/plugin/triggers/<SUBSCRIPTION_ID>"
    • If you set require_oidc=true, the push subscription must use OIDC; set --push-auth-service-account and match oidc_audience exactly.

Where To Get OIDC Values

  • oidc_audience
    • Use the exact webhook endpoint URL shown in the Dify subscription details (Endpoint). Example:
      • https://<your-dify-host>/api/plugin/triggers/<subscription-id>
    • The YAML field includes a URL to Google docs for the audience claim: see the OIDC token reference.
  • oidc_service_account_email
    • The service account used by the Pub/Sub push subscription (set via --push-auth-service-account).
    • Find it under Google Cloud Console → IAM & Admin → Service Accounts, or via:
      • gcloud iam service-accounts list --format='value(email)'
    • The YAML field links to the Service Accounts console page.

How It Works

  • Dispatch (trigger)
    • Optionally verifies OIDC bearer from Pub/Sub push (iss/aud/email)
    • Decodes message.data to get historyId/emailAddress
    • Calls users.history.list(startHistoryId=...) once to gather deltas
    • Splits changes per family and stores pending batches in Dify storage
    • Returns the list of concrete event names for Dify to execute
  • Events
    • Read the pending batch for their family
    • gmail_message_added fetches full message metadata (headers, attachments meta)
    • Output matches the event YAML output_schema

Event Outputs (high-level)

  • gmail_message_added
    • history_id: string
    • messages[]: id, threadId, internalDate, snippet, sizeEstimate, labelIds, headers{From,To,Subject,Date,Message-Id}, has_attachments, attachments[]
  • gmail_message_deleted
    • history_id: string
    • messages[]: id, threadId
  • gmail_label_added / gmail_label_removed
    • history_id: string
    • changes[]: id, threadId, labelIds

Lifecycle & Refresh

  • Create: users.watch with topicName, optional labelIds/labelFilterAction
  • Refresh: users.watch again before expiry (Gmail watch is time-limited). If expiration not provided, plugin targets ~6 days
  • Delete: users.stop

Testing

  • Send an email to the watched mailbox (INBOX). You should see gmail_message_added
  • Mark read/unread (UNREAD label removed/added) triggers label events
  • Delete an email triggers gmail_message_deleted
  • Tip: You can view recent deliveries in Pub/Sub subscription details; Dify logs/console will show trigger and event traces.

Troubleshooting

  • Nothing triggers: ensure topic exists, Gmail has publisher role on the topic, and push subscription points to Dify endpoint
  • 401/403 at dispatch: OIDC settings mismatch; verify service account and audience
  • historyId out of date: plugin resets checkpoint to the latest notification and skips the batch
  • OAuth issues: re-authorize the provider; token is validated by users/me/profile

References