> For the complete documentation index, see [llms.txt](https://docs.appstrategy.com/apprules-r-documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.appstrategy.com/apprules-r-documentation/platform/platform-features/system-settings/data-sources/connection-settings/emailsystems/gmail.md).

# Gmail

## Gmail

Connect appRules to a Gmail mailbox via the Gmail REST API. Supports reading messages and folders (labels), sending mail, creating drafts, moving/copying messages between labels, and the common message-level operations through the Email connector.

For Google Workspace accounts where OAuth is impractical, Gmail can also be reached via **IMAP + SMTP** using the Generic IMAP path with a Google App Password. See the IMAP page for that configuration.

### Prerequisites

Before you can connect appRules to a Gmail mailbox, you need a **Google Cloud project** with the Gmail API enabled and an OAuth 2.0 client registered. The next section walks you through setting that up in the Google Cloud Console.

#### Step 1 — Create (or pick) a Google Cloud project

1. Open [console.cloud.google.com](https://console.cloud.google.com).
2. In the top bar, click the project selector → **New Project** (or pick an existing one if you have one for this).
3. Give it a name (`appRules Email` is fine) and create it.

#### Step 2 — Enable the Gmail API

1. Left menu → **APIs & Services** → **Library**.
2. Search for `Gmail API` → click the result → click **Enable**.
3. Wait a few seconds for the enablement to complete.

#### Step 3 — Configure the OAuth consent screen

This is the sign-in prompt your users see when they authorize the connector.

1. Left menu → **APIs & Services** → **OAuth consent screen**.
2. **User Type**:
   * `Internal` — if you're on Google Workspace and only users in your own Workspace organization will connect. No Google verification needed.
   * `External` — if the mailbox is a personal Gmail account, or if users outside your Workspace will connect. Requires Google verification for production use of sensitive scopes (see note below).
3. Fill in the required fields:
   * **App name**: `appRules Email` (shown to users on the sign-in screen).
   * **User support email**: pick yours from the dropdown.
   * **Developer contact information**: your email.
4. **Scopes page**: click **Add or Remove Scopes** and add `https://mail.google.com/` (full mailbox access — needed for read + send
   * modify). For read-only use, add `https://www.googleapis.com/auth/gmail.readonly` instead. Both are classed by Google as **sensitive** scopes, which matters for the publishing step below.
5. **Test users page** (External only): add every Gmail address that will authorize while the app is in "Testing" status. Without this, users outside the test list get an "access blocked" error.
6. **Publishing status**:
   * **Testing** — works, but refresh tokens expire after **7 days**. Fine for development; painful in production because the connector will stop working weekly until re-authorized.
   * **In production** — refresh tokens don't expire. To move an app with sensitive scopes to production, Google requires app verification (video demo + security review). Internal Workspace apps skip this.

#### Step 4 — Create the OAuth 2.0 client

1. Left menu → **APIs & Services** → **Credentials** → **+ Create Credentials** → **OAuth client ID**.
2. **Application type**: `Web application`.
3. **Name**: `appRules Email Client` (shown only in the Cloud Console).
4. **Authorized redirect URIs**: click **+ Add URI** and enter `http://localhost:33333` **exactly as written** (no trailing slash). This must match the `Callback URL` you'll use in the connection string.
5. Click **Create**. Google shows you the **Client ID** (ends in `.apps.googleusercontent.com`) and the **Client secret** (starts with `GOCSPX-`).
6. **Copy both immediately** — the secret can be retrieved later but it's easier to copy now.

#### Step 5 — Collect what you'll paste into the connection string

By the end of the Google setup you should have:

| From Google Cloud       | Goes into the connection string as |
| ----------------------- | ---------------------------------- |
| Client ID               | `OAuth Client Id`                  |
| Client secret           | `OAuth Client Secret`              |
| Authorized redirect URI | `Callback URL`                     |

You obtain the initial **refresh token** interactively via the **OAuth Configuration** window the first time you connect (next section). After that, access tokens are refreshed automatically — as long as the app is Published (not Testing), per Google's 7-day rule for Testing-mode tokens.

### Connection parameters

Keywords are case-insensitive, and both spaced and unspaced forms are accepted (`OAuth Client Id` and `OAuthClientId` work the same).

#### Required — identifying the provider

| Keyword            | Value                    | Description                                                                                                                        |
| ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| **Email Provider** | `Gmail`                  | Selects the Gmail API backend.                                                                                                     |
| **Auth Scheme**    | `OAuth` or `AccessToken` | How to authenticate. `OAuth` uses a refresh token (recommended). `AccessToken` uses a short-lived bearer token (diagnostics only). |

#### Required — OAuth with refresh token (`Auth Scheme = OAuth`)

| Keyword                 | Description                                                                      |
| ----------------------- | -------------------------------------------------------------------------------- |
| **OAuth Client Id**     | Client ID from Google Cloud Console (format: `<id>.apps.googleusercontent.com`). |
| **OAuth Client Secret** | Client secret from the same OAuth client credential.                             |
| **OAuth Refresh Token** | Refresh token obtained through the initial authorization flow.                   |

#### Required — pre-obtained access token (`Auth Scheme = AccessToken`)

| Keyword                | Description                                                               |
| ---------------------- | ------------------------------------------------------------------------- |
| **OAuth Access Token** | A valid bearer token for the Gmail API. Short-lived (typically one hour). |

#### Optional

| Keyword          | Default                                | Description                                                                                                                  |
| ---------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| **Callback URL** | `http://localhost:33333`               | OAuth redirect URI; must match what's configured on your Google Cloud OAuth client.                                          |
| **OAuth Scopes** | *(empty → `https://mail.google.com/`)* | Space-delimited scope list. Use a narrower scope like `https://www.googleapis.com/auth/gmail.readonly` for read-only access. |
| **Timeout**      | `60`                                   | HTTP timeout in seconds.                                                                                                     |

#### Logging

| Keyword                 | Default                                                                    | Description                                                                                                |
| ----------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| **Log File**            | `%APPDATA%\appStrategy\PortalData\Default\Logs\Connectors\Email_Debug.log` | Path to the log file.                                                                                      |
| **Log Level**           | `0`                                                                        | `0` off, `1` connection and statements, `2` one line per HTTP request, `3` also values and request bodies. |
| **Log Max Size MB**     | `100`                                                                      | Roll the log file at this size (`0` = unlimited).                                                          |
| **Log Compress**        | `True`                                                                     | gzip closed log files in the background.                                                                   |
| **Log Max Line Length** | `16384`                                                                    | Truncate overlong lines (`0` = unlimited).                                                                 |
| **Log Max Total MB**    | `0`                                                                        | Total kept size of closed logs, oldest deleted first.                                                      |
| **Log Retention Days**  | `0`                                                                        | Delete closed logs older than N days.                                                                      |

#### Advanced — proxy, firewall, SSL

These configure the underlying `HttpClient`. Typically not needed for a direct Internet connection, but accepted when present.

| Keyword                                                                          | Default         | Description                                                                                        |
| -------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------- |
| **Proxy Auto Detect**                                                            | `True`          | Honor the system proxy.                                                                            |
| **Proxy Server**, **Proxy Port**                                                 | *(empty)*, `80` | Explicit HTTP proxy.                                                                               |
| **Proxy User**, **Proxy Password**, **Proxy Exceptions**                         | *(empty)*       | Proxy auth and bypass list.                                                                        |
| **Firewall Type**                                                                | `NONE`          | `TUNNEL`, `SOCKS4`, `SOCKS5`, or `HTTP`.                                                           |
| **Firewall Server**, **Firewall Port**, **Firewall User**, **Firewall Password** | *(empty)*       | Firewall configuration.                                                                            |
| **SSL Server Cert**                                                              | *(empty)*       | `*` trusts any certificate; a PEM string, file path, or thumbprint pins that specific certificate. |

#### Not applicable to Gmail

These parameters appear elsewhere in the Email connector but have no effect on Gmail connections and should be left out: `Tenant Id`, `User Principal Name`, `API Version`, `Host`, `Port`, `Use SSL`, `SMTP Host`, `SMTP Port`, `SMTP Use SSL`, `Default Folder`, `Use POP3`, `POP3 Host`, `POP3 Port`.

### Example connection strings

**Standard — OAuth with refresh token:**

```
Email Provider=Gmail;
Auth Scheme=OAuth;
OAuth Client Id=1234567890-abc123.apps.googleusercontent.com;
OAuth Client Secret=GOCSPX-xxxxxxxxxxxxxxxxxxxx;
OAuth Refresh Token=1//0g-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
Callback URL=http://localhost:33333;
Log Level=1
```

**Read-only — narrower scope:**

```
Email Provider=Gmail;
Auth Scheme=OAuth;
OAuth Client Id=1234567890-abc123.apps.googleusercontent.com;
OAuth Client Secret=GOCSPX-xxxxxxxxxxxxxxxxxxxx;
OAuth Refresh Token=1//0g-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
OAuth Scopes=https://www.googleapis.com/auth/gmail.readonly;
Log Level=1
```

**Diagnostic — pre-obtained access token:**

```
Email Provider=Gmail;
Auth Scheme=AccessToken;
OAuth Access Token=ya29.a0AfH6SMBxxxxxxxxxxxxxxxxxxxxxxxxx;
Log Level=2
```

### Getting a refresh token (first-time setup)

The portal provides an **OAuth Configuration** window that runs the authorization flow and fills in the tokens for you. You do not need to call any stored procedure, start a listener, or copy URLs between windows yourself.

1. Open the connection's **Configure Connection String** window and fill in **OAuth Client Id**, **OAuth Client Secret**, and **Callback URL** (default: `http://localhost:33333`). Set **Auth Scheme** to `OAuth`.
2. Open the **OAuth Configuration** window from that dialog.
   * **Authorization URL**, **Token Endpoint**, **Scopes**, **Prompt**, and **Access Type** are prefilled from the built-in provider definition for Gmail.
   * **Client Id**, **Client Secret**, and **Callback URL** are prefilled from the connection string you just entered.
   * **PKCE** is prefilled from the provider default; override only if your Google OAuth client is configured for it.
3. Click **Get Token**. The portal starts a local HTTP listener on the callback URL, opens a popup to Google's sign-in page, and waits for the redirect. Sign in with the Google account whose mailbox you want to connect to and consent to the requested scopes.
4. The popup closes automatically once the authorization code arrives. The portal exchanges it for an access token and a refresh token, writes both back to the connection string (`OAuth Access Token`, `OAuth Refresh Token`), and refreshes the Configure Connection String window.
5. Save the connection. From that point on, access tokens are refreshed automatically — you do not need to open the OAuth Configuration window again unless the refresh token is revoked.

If Google does not return a refresh token (common for Google — the token is only issued on the very first authorization, and only when the request includes `access_type=offline` and `prompt=consent`), the form raises a message explaining how to re-authorize. Make sure **Access Type** is `offline` and **Prompt** is `consent` before clicking Get Token again.

### Schema

A Gmail connection exposes three virtual tables:

* **Messages** — most Graph-standard columns are mapped from Gmail's message resource. Gmail-specific columns `ThreadId`, `LabelIds`, and `Snippet` are populated. Microsoft Graph-only columns `ConversationId`, `Categories`, `Importance`, and `FlagStatus` are not.
* **Folders** — Gmail labels, both system labels (`INBOX`, `SENT`, `TRASH`, `DRAFT`, `SPAM`, `STARRED`, `IMPORTANT`, `UNREAD`, `CATEGORY_*`) and user-created labels. The `Name`, `Type`, and `Id` columns reflect Gmail's label structure.
* **Attachments** — attachments of a given message. Requires a `MessageId` filter in the WHERE clause.

### Supported operations

* `SELECT` on Messages, Folders, Attachments
* `INSERT INTO Messages` — sends mail, or creates a draft when `IsDraft = true`
* `INSERT INTO Folders` — creates a user label
* `UPDATE Messages` — mark as read/unread, add or remove labels
* `DELETE FROM Messages` — moves the message to Trash (Gmail convention; not a hard delete)

Stored procedures: `SendMail`, `Reply`, `ReplyAll`, `Forward`, `MarkAsRead`, `MarkAsUnread`, `MoveMessage` (relabel), `DownloadAttachment`, `ListFolders`, `GetUserInfo`, `SetLabels` (Gmail-specific), `GetOAuthAuthorizationUrl`, `GetOAuthAccessToken`, `RefreshOAuthAccessToken`.

The three OAuth procedures are the low-level building blocks the OAuth Configuration window uses internally. For normal use, you don't call them yourself — use the window.

### Troubleshooting

* **`invalid_grant` on connection open** — refresh token expired or revoked. Re-run the authorization flow to get a fresh one. Google revokes refresh tokens when the user changes their password, hasn't used the token for 6 months, or the Cloud project is still in "Testing" OAuth status (refresh tokens expire after 7 days in that mode).
* **`invalid_client`** — Client ID or Client Secret doesn't match a credential in your Google Cloud project.
* **`insufficient_scope` on a specific operation** — the refresh token was issued for a narrower scope than the operation requires. Re-authorize with `https://mail.google.com/` or the specific scope needed.
* **403 on SELECT from Messages** — the Gmail API isn't enabled for the Cloud project, or the OAuth consent screen hasn't been configured for the required scopes.
* **Connection opens but no messages come back** — check `Log Level=2` and look at the Gmail query URL: if it includes `labelIds=INBOX` but you expected other labels, review your WHERE clause. Gmail uses label-based filtering, so `WHERE ParentFolderId = 'SENT'` is how you'd read Sent Mail.
* **Pagination surprises on large folders** — Gmail paginates with `pageToken` rather than `$top/$skip`. Very large SELECTs will take several round-trips; use `LIMIT N` to cap.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.appstrategy.com/apprules-r-documentation/platform/platform-features/system-settings/data-sources/connection-settings/emailsystems/gmail.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
