Skip to main content

Gmail Component

Manage Messages in Google's email service

Component key: google-gmail

Description

Gmail is Google's email service. This component allows you to fetch and filter and manage messages, and send new messages from a Google Gmail account.

API Documentation

This component was built using the Gmail API Documenetation.

Documentation for the Node.js client used in this component can be found at https://googleapis.dev/nodejs/googleapis/latest/gmail/index.html

Most actions in this component have a Gmail User ID input. You can safely leave this input blank, and the default value, me will be used, indicating that the user who authenticated is the user whose Gmail account your integration will use.

Use labels to organize messages

Gmail uses labels in place of folders to organize messages. Messages in a user's inbox have a label of INBOX. You can apply custom labels to a message (so, you can loop only over messages with a particular label, etc).

Receiving notifications from Gmail

Gmail supports push notifications to let you know when a new message arrives in a user's inbox. Behind the scenes, this uses Google Cloud Pub/Sub to deliver the notifications. In order to revieve notifications when new messages are received, you will need to set up a Pub/Sub topic and subscription, and then configure Gmail to send notifications to that topic. The steps below will walk you through this process.

  1. Create a Google Cloud IAM service account from https://console.cloud.google.com/iam-admin/serviceaccounts and grant the service account the Pub/Sub Admin role. Ensure that this IAM role exists in the same project as your Gmail OAuth app (see OAuth 2.0 connection below).
  2. Generate a new key for the service account, and download the JSON file. Take note of the private_key, project_id and client_email values in the JSON file - these will be used for creating the Pub/Sub topic and subscription.
  3. Create a new Pub/Sub topic using the Google Cloud Pub/Sub component's Create Topic action.
  4. Create a new Pub/Sub subscription using the Google Cloud Pub/Sub component's Create Webhook Subscription action. Use the topic created in the previous step as the Topic Name input. For the webhook URL, choose a sibling flow of the webhook creation flow. The sibling flow will receive the webhook notifications.
  5. Use this component's Create Push Notification action. This will instruct Gmail to send notifications to the Pub/Sub topic created in step 3.

Some notes about the above steps:

  • Subscription and topic names need to be unique. You can use the current instance's ID (available from the trigger payload) as a unique identifier for the topic and subscription names.
  • The Pub/Sub topic and subscription must be created in the same project as the Gmail OAuth app.
  • Push notification watch requests expire after 7 days. You'll need to periodically refresh the watch request. You can do that by calling the setup flow from another flow on a schedule.

The examples repo has an example integration that you can import that demonstrates how to set up Gmail push notifications.

Example Integration

Connections

OAuth2

The Gmail component authenticates requests through the Google Cloud Platform (GCP) OAuth 2.0 service. You'll need to create a GCP OAuth 2.0 app so your integration can authenticate and perform Gmail tasks on your customers' behalf.

To create a Gmail OAuth 2.0 app, first make sure you have a Google Developer account - you can sign up at https://console.cloud.google.com/. Then:

  1. Open up the Gmail API console - https://console.cloud.google.com/marketplace/product/google/gmail.googleapis.com
  2. You will be prompted to enable Gmail API for your project. Click ENABLE.
  3. On the sidebar, select APIs & Services and then Credentials.
  4. An OAuth 2.0 app includes a "Consent Screen" (the page that asks "Do you want to allow (Your Company) to access Gmail on your behalf?"). Click CONFIGURE CONSENT SCREEN.
    1. Your app will be externally available to your customers, so choose a User Type of External.
    2. Fill out the OAuth consent screen with an app name (your company or product's name), support email, app logo, domain, etc.
    3. You can ignore domains for now.
    4. On the next page, add any scopes relevant to your integration, like https://www.googleapis.com/auth/gmail.readonly and https://www.googleapis.com/auth/gmail.send.
    5. Enter some test users for your testing purposes. Your app will only work for those testing users until it is "verified" by Google. When you are ready for verification (they verify your privacy policy statement, etc), click PUBLISH APP on the OAuth consent screen. That'll allow your customers to authorize your integration to access their Gmail account.
  5. Once your "Consent Screen" is configured open the Credentials page from the sidebar again.
  6. Click +CREATE CREDENTIALS and select OAuth Client ID.
    1. Under Application type select Web application.
    2. Under Authorized redirect URIs enter Prismatic's OAuth 2.0 callback URL: https://oauth2.prismatic.io/callback for US based integrations.
      1. For integrations outside the US refer to this guide to find your region’s Callback URL.
    3. Click CREATE.
  7. Take note of the Client ID and Client Secret that are generated.
info

Make sure to publish your OAuth 2.0 app after you've tested it so users outside of your test users can authorize your integration to interact with Gmail on their behalf.

Now that you have a Client ID and Client Secret, add Gmail step to your integration in Prismatic. Open the Configuration Wizard Designer by clicking Configuration Wizard, select your Gmail Connection and enter your client ID and secret.

A note on scopes

You can keep the default Gmail scope, https://mail.google.com/. This will grant you full permission over your users' Gmail accounts.

If you would like to limit permissions, you can select a subset of scopes, like https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.send.

InputDefaultNotes
Authorize URL
string
/ Required
Hidden Field
authorizeUrl
https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent
The Authorization URL for Gmail
Client ID
string
/ Required
clientId
Your Gmail app's Client ID
Client Secret
password
/ Required
clientSecret
Your Gmail app's Client Secret
Scopes
string
/ Required
scopes
https://mail.google.com/
Space delimited listing of scopes. See https://developers.google.com/gmail/api/auth/scopes
Token URL
string
/ Required
Hidden Field
tokenUrl
https://oauth2.googleapis.com/token
The Token URL for Gmail

Triggers

Push Notification Webhook

Receive and validate webhook requests from Gmail for webhooks you configure. | key: pushNotificationWebhook

{
"payload": {
"headers": {
"Accept": "application/json",
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json",
"From": "noreply@google.com",
"Host": "hooks.prismatic.io",
"User-Agent": "APIs-Google; (+https://developers.google.com/webmasters/APIs-Google.html)",
"X-Amz-Cf-Id": "IfJGfd1Y6gtJX9BTs37_GnMRnliiMaMCxQ6EMM6dD1rqE7hMK12345==",
"X-Amzn-Trace-Id": "Root=1-648cba10-7ea5bdfd45f98ad327612345"
},
"queryParameters": null,
"rawBody": "<data (N bytes)>",
"body": {
"data": {
"message": {
"data": "<Base64 encoded data>",
"decodedData": {
"emailAddress": "",
"historyId": "123456"
},
"messageId": "8406082761012345",
"message_id": "8406082761012345",
"publishTime": "2023-06-16T19:37:52.276Z",
"publish_time": "2023-06-16T19:37:52.276Z"
},
"subscription": "projects/projectname-123456/subscriptions/SubscriptionName"
},
"contentType": "application/json"
},
"pathFragment": "",
"webhookUrls": {
"Flow 1": "https://hooks.prismatic.io/trigger/WEBHOOK_ID"
},
"webhookApiKeys": {
"Flow 1": [
"sample-api-key"
]
},
"invokeUrl": "https://hooks.prismatic.io/trigger/WEBHOOK_ID",
"executionId": "EXECUTION_ID",
"customer": {
"id": "testCustomerId",
"name": "Test Customer",
"externalId": "testCustomerExternalId"
},
"instance": {
"id": "testInstanceId",
"name": "Test Instance"
},
"user": {
"id": "testUserId",
"email": "testUserEmail@example.com",
"name": "Test User",
"externalId": "testUserExternalId"
}
}
}

Actions

Create Push Notification (Watch Request)

Enables the ability to send update notifications like new messages received. | key: createPushNotification

InputNotesExample
Connection
connection
/ Required
connection
The Connection to use for authorization.
 
Label ID
string
/ Required
Value List
labelIdsInput
System labels typically correspond to pre-defined elements in the Gmail web interface such as the inbox.
INBOX
Topic Name
string
/ Required
topicNameInput
 
projects/prismatic-123456/topics/prismatic-gmail
Gmail User ID (optional)
string
userIdInput
A user whose account to query (defaults to currently authenticated user)
 

Delete Push Notification (Stop Mailbox Updates)

Calls a stop notification. | key: deletePushNotification

InputNotes
Connection
connection
/ Required
connection
The Connection to use for authorization.
Gmail User ID (optional)
string
userIdInput
A user whose account to query (defaults to currently authenticated user)

Get Current User

Get metadata about the authenticated user | key: getCurrentUser

InputNotes
Connection
connection
/ Required
connection
The Connection to use for authorization.

{
"data": {
"emailAddress": "example@gmail.com",
"historyId": "1234567",
"messagesTotal": 12345,
"threadsTotal": 12345
}
}

Get Event History

Fetch events that have occurred in the mailbox since the specified startHistoryId. | key: getEventHistory

InputNotes
Connection
connection
/ Required
connection
The Connection to use for authorization.
History ID
string
/ Required
historyId
The history ID to start history from.
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)

Get Label by Name

Get a label (including ID) by its name | key: getLabelByName

InputNotes
Connection
connection
/ Required
connection
The Connection to use for authorization.
Label Name
string
/ Required
labelName
 
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)

Get Message

Get a message by ID | key: getMessageById

InputNotesExample
Connection
connection
/ Required
connection
The Connection to use for authorization.
 
Message ID
string
/ Required
messageId
 
1234abcd
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)
 

{
"data": {
"id": "1234abcd",
"threadId": "5678efgh",
"labelIds": [
"IMPORTANT",
"SENT",
"INBOX"
],
"message": {
"headers": {
"mime-version": "1.0",
"date": "2022-09-19T20:09:01.000Z",
"message-id": "<Test-message-id@mail.gmail.com>",
"subject": "Test Message",
"from": {
"value": [
{
"address": "example@gmail.com",
"name": "Example Example"
}
],
"html": "<span class=\"mp_address_group\"><span class=\"mp_address_name\">Example Example</span> &lt;<a href=\"mailto:example@gmail.com\" class=\"mp_address_email\">example@gmail.com</a>&gt;</span>",
"text": "Example Example <example@gmail.com>"
},
"to": {
"value": [
{
"address": "example@gmail.com",
"name": "Example Example"
}
],
"html": "<span class=\"mp_address_group\"><span class=\"mp_address_name\">Example Example</span> &lt;<a href=\"mailto:example@gmail.com\" class=\"mp_address_email\">example@gmail.com</a>&gt;</span>",
"text": "Example Example <example@gmail.com>"
},
"content-type": {
"value": "multipart/mixed",
"params": {
"boundary": "000000000000680fa005e90d488f"
}
}
},
"attachments": [],
"text": "Example email body",
"html": "<div dir=\"ltr\">Example email body<div><br></div></div>\n"
}
}
}

List Labels

List all labels within this account | key: listLabels

InputNotes
Connection
connection
/ Required
connection
The Connection to use for authorization.
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)

List Messages

Get a list of messages | key: listMessages

InputNotesExample
Connection
connection
/ Required
connection
The Connection to use for authorization.
 
Labels
string
Value List
labelIds
Show only messages with labels that match these label IDs
 
Page Token
string
pageToken
If you're looping over pages of results, this is the page token from the result of the previous 'list messages' step.
 
Query String
string
query
Only return messages matching the specified query. Supports the same query format as the Gmail search box.
from:someuser@example.com rfc822msgid:<somemsgid@example.com> is:unread
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)
 

{
"data": {
"messages": [
{
"id": "abcd1234",
"threadId": "efgh5678"
}
]
}
}

Raw Request

Send raw HTTP request to Google Gmail | key: rawRequest

InputDefaultNotesExample
Connection
connection
/ Required
connection
 
The Connection to use for authorization.
 
Data
string
data
The HTTP body payload to send to the URL.
{"exampleKey": "Example Data"}
Debug Request
boolean
debugRequest
false
Enabling this flag will log out the current request.
 
File Data
string
Key Value List
fileData
File Data to be sent as a multipart form upload.
[{key: "example.txt", value: "My File Contents"}]
File Data File Names
string
Key Value List
fileDataFileNames
File names to apply to the file data inputs. Keys must match the file data keys above.
 
Form Data
string
Key Value List
formData
The Form Data to be sent as a multipart form upload.
[{"key": "Example Key", "value": new Buffer("Hello World")}]
Header
string
Key Value List
headers
A list of headers to send with the request.
User-Agent: curl/7.64.1
Max Retry Count
string
maxRetries
0
The maximum number of retries to attempt.
 
Method
string
/ Required
method
The HTTP method to use.
 
Query Parameter
string
Key Value List
queryParams
A list of query parameters to send with the request. This is the portion at the end of the URL similar to ?key1=value1&key2=value2.
 
Response Type
string
/ Required
responseType
json
The type of data you expect in the response. You can request json, text, or binary data.
 
Retry On All Errors
boolean
retryAllErrors
false
If true, retries on all erroneous responses regardless of type.
 
Retry Delay (ms)
string
retryDelayMS
0
The delay in milliseconds between retries.
 
Timeout
string
timeout
The maximum time that a client will await a response to its request
2000
URL
string
/ Required
url
Input the path only (/v1/users/{userId}/messages), The base URL is already included (https://gmail.googleapis.com/gmail). For example, to connect to https://gmail.googleapis.com/gmail/v1/users/{userId}/messages, only /v1/users/{userId}/messages is entered in this field.
/v1/users/{userId}/messages
Use Exponential Backoff
boolean
useExponentialBackoff
false
Specifies whether to use a pre-defined exponential backoff strategy for retries.
 

Send Message

Send a new message | key: sendMessage

InputNotesExample
Attachments
string
Key Value List
attachments
Specify a file name as the key (i.e. 'my-file.pdf'), and the file as the value
 
BCC
string
Value List
bcc
 
 
CC
string
Value List
cc
 
 
Connection
connection
/ Required
connection
The Connection to use for authorization.
 
Dynamic Attachments
data
dynamicAttachments
An array of objects with 'key' and 'value' properties, where 'key' is the file name and 'value' is the binary file data. Typically used as a reference from a previous step. Ex. [{key: "my-attachment.pdf", value: <BINARY FILE DATA TO ATTACH>},{key: "another-attachment.xlsx", value: <BINARY EXCEL FILE DATA>}]
[{key: "my-attachment.pdf", value: <BINARY FILE DATA TO ATTACH>},{key: "another-attachment.xlsx", value: <BINARY EXCEL FILE DATA>}]
HTML body
string
html
For email clients that support HTML
 
Subject
string
/ Required
subject
 
 
Plain text body
string
text
For email clients that do not support HTML
 
To
string
/ Required
Value List
to
 
 
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)
 

Trash Message

Send a message to the trash | key: trashMessageById

InputNotesExample
Connection
connection
/ Required
connection
The Connection to use for authorization.
 
Message ID
string
/ Required
messageId
 
1234abcd
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)
 

Untrash Message

Remove a message from the trash | key: unTrashMessageById

InputNotesExample
Connection
connection
/ Required
connection
The Connection to use for authorization.
 
Message ID
string
/ Required
messageId
 
1234abcd
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)
 

Update Message Labels

Add or remove labels from a message | key: updateLabels

InputNotesExample
Labels to Add
string
Value List
addLabels
A list of labels to add (optional)
 
Connection
connection
/ Required
connection
The Connection to use for authorization.
 
Message ID
string
/ Required
messageId
 
1234abcd
Labels to Remove
string
Value List
removeLabels
A list of labels to add (optional)
 
Gmail User ID (optional)
string
userId
A user whose account to query (defaults to currently authenticated user)