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.
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.
- 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). - Generate a new key for the service account, and download the JSON file. Take note of the
private_key
,project_id
andclient_email
values in the JSON file - these will be used for creating the Pub/Sub topic and subscription. - Create a new Pub/Sub topic using the Google Cloud Pub/Sub component's Create Topic action.
- 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. - 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.
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:
- Open up the Gmail API console - https://console.cloud.google.com/marketplace/product/google/gmail.googleapis.com
- You will be prompted to enable Gmail API for your project. Click ENABLE.
- On the sidebar, select APIs & Services and then Credentials.
- 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.
- Your app will be externally available to your customers, so choose a User Type of External.
- Fill out the OAuth consent screen with an app name (your company or product's name), support email, app logo, domain, etc.
- You can ignore domains for now.
- On the next page, add any scopes releavant to your integration, like
https://www.googleapis.com/auth/gmail.readonly
andhttps://www.googleapis.com/auth/gmail.send
. - 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.
- Once your "Consent Screen" is configured open the Credentials page from the sidebar again.
- Click +CREATE CREDENTIALS and select OAuth Client ID.
- Under Application type select Web application.
- Under Authorized redirect URIs enter Prismatic's OAuth 2.0 callback URL:
https://oauth2.prismatic.io/callback
for US based integrations.- For integrations outside the US refer to this guide to find your region’s Callback URL.
- Click CREATE.
- Take note of the Client ID and Client Secret that are generated.
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.
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
.
Input | Default | Notes |
---|---|---|
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
Example Payload for Push Notification Webhook
{
"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
Input | Notes | Example |
---|---|---|
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
Input | Notes |
---|---|
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
Input | Notes |
---|---|
Connection connection / Required connection | The Connection to use for authorization. |
Example Payload for Get Current User
{
"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
Input | Notes |
---|---|
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
Input | Notes |
---|---|
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
Input | Notes | Example |
---|---|---|
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) |
Example Payload for Get Message
{
"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> <<a href=\"mailto:example@gmail.com\" class=\"mp_address_email\">example@gmail.com</a>></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> <<a href=\"mailto:example@gmail.com\" class=\"mp_address_email\">example@gmail.com</a>></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
Input | Notes |
---|---|
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
Input | Notes | Example |
---|---|---|
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) |
Example Payload for List Messages
{
"data": {
"messages": [
{
"id": "abcd1234",
"threadId": "efgh5678"
}
]
}
}
Raw Request
Send raw HTTP request to Google Gmail | key: rawRequest
Input | Default | Notes | Example |
---|---|---|---|
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
Input | Notes | Example |
---|---|---|
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
Input | Notes | Example |
---|---|---|
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
Input | Notes | Example |
---|---|---|
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
Input | Notes | Example |
---|---|---|
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) |