> 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-1.md).

# Exchange

## Microsoft 365 (Exchange Online) — Microsoft Graph

Connect appRules to an Exchange Online mailbox via the Microsoft Graph API. Supports reading messages and folders, sending mail, creating drafts, replying, forwarding, moving, copying, flagging, and the full set of Graph-backed message operations through the Email connector.

For on-premises Exchange or non-Microsoft IMAP servers, see the Generic IMAP page.

### Prerequisites

Before you can connect appRules to a Microsoft 365 mailbox, you need an **Entra ID (Azure AD) app registration** in your tenant. The next section walks you through creating it in the Azure portal.

#### Step 1 — Register an application in Entra ID (Azure portal)

You do this once per application. The result is a Client ID, a Client Secret, and a set of permissions the application can request from users.

1. Sign in at [portal.azure.com](https://portal.azure.com) with an account that can create app registrations (Global Administrator, Cloud Application Administrator, or Application Administrator).
2. Navigate to **Entra ID** (formerly Azure Active Directory) → **App registrations** → **+ New registration**.
3. Fill in the form:
   * **Name**: `appRules Email` (or any name; shown to users on the consent screen).
   * **Supported account types**: `Accounts in this organizational directory only (<your tenant> - Single tenant)` for most cases. Use the multi-tenant option only if you'll let users from other tenants sign in.
   * **Redirect URI**: pick `Web` from the dropdown and enter `http://localhost:33333` (must match the `Callback URL` you'll use in the connection string).
4. Click **Register**. On the Overview page, copy the **Application (client) ID** and **Directory (tenant) ID**. You'll need them later.

#### Step 2 — Create a client secret

1. In the registration you just created, go to **Certificates & secrets** → **Client secrets** → **+ New client secret**.
2. Give it a description (`appRules Secret`), pick an expiry (24 months is common), click **Add**.
3. **Copy the Value column immediately** — it's hidden after you leave the page. This is your **Client Secret**.

#### Step 3 — Grant the Microsoft Graph API permissions

The permissions you add here determine what the connector can do. Pick the set that matches how you'll authenticate:

**For delegated access (OAuth with refresh token — Path A, recommended for single-user mailboxes):**

1. Go to **API permissions** → **+ Add a permission** → **Microsoft Graph** → **Delegated permissions**.
2. Search for and tick:
   * `offline_access` — required so Microsoft returns a refresh token
   * `User.Read` — read the signed-in user's profile
   * `Mail.ReadWrite` — read and modify messages and folders
   * `Mail.Send` — send mail
   * `MailboxSettings.Read` — read mailbox settings (optional but typical)
3. Click **Add permissions**.

**For app-only access (Client Credentials — Path B, for service accounts and shared mailboxes):**

1. **+ Add a permission** → **Microsoft Graph** → **Application permissions**.
2. Search for and tick:
   * `Mail.ReadWrite` — read and modify any mailbox the app is granted access to
   * `Mail.Send` — send mail from any mailbox the app is granted access to
3. Click **Add permissions**.
4. **Click "Grant admin consent for \<tenant>"** — application permissions require a tenant administrator to approve them before they take effect. This button is above the permissions table.

*Application permissions by default grant access to **every** mailbox in the tenant. To scope that to a specific mailbox, create an* [*Application Access Policy*](https://learn.microsoft.com/en-us/graph/auth-limit-mailbox-access) *through PowerShell after setup — recommended for anything beyond a proof of concept.*

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

By the end of the Azure setup you should have:

| From Azure              | Goes into the connection string as |
| ----------------------- | ---------------------------------- |
| Application (client) ID | `OAuth Client Id`                  |
| Directory (tenant) ID   | `Tenant Id`                        |
| Client secret Value     | `OAuth Client Secret`              |
| Redirect URI            | `Callback URL`                     |

For **app-only** access you also need to decide which mailbox to act on: set `User Principal Name` to that mailbox's email address.

For **delegated** access you obtain the **refresh token** interactively via the **OAuth Configuration** window the first time you connect (next section). After that, access tokens are refreshed automatically.

### 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** | `MicrosoftGraph`                                                     | Selects the Microsoft Graph backend. This is the default. |
| **Auth Scheme**    | `OAuth`, `OAuthClientCredentials`, `OAuthPassword`, or `AccessToken` | Which authentication flow to use. See the paths below.    |

#### Path A — Delegated access with a refresh token (most common)

For a single user's mailbox where a human has signed in once to grant consent.

| Keyword                 | Description                                                                                                  |
| ----------------------- | ------------------------------------------------------------------------------------------------------------ |
| **Auth Scheme**         | `OAuth`                                                                                                      |
| **OAuth Client Id**     | Application (Client) ID of the Entra ID app registration.                                                    |
| **OAuth Client Secret** | Client secret from the same app registration.                                                                |
| **OAuth Refresh Token** | Refresh token obtained through the initial authorization flow.                                               |
| **Tenant Id**           | The tenant GUID or verified domain. Use `common` for a multi-tenant app that supports any Microsoft account. |
| **Callback URL**        | Must match a redirect URI configured on the app registration. Default: `http://localhost:33333`.             |

#### Path B — App-only access with client credentials

For a service that reads or sends mail without a user in the loop. The app registration must have **application** (not delegated) Graph permissions, and an administrator must have granted consent.

| Keyword                 | Description                                                                                                                              |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **Auth Scheme**         | `OAuthClientCredentials`                                                                                                                 |
| **OAuth Client Id**     | Application (Client) ID.                                                                                                                 |
| **OAuth Client Secret** | Client secret.                                                                                                                           |
| **Tenant Id**           | The specific tenant GUID or verified domain. `common` is **not valid** for client credentials — Microsoft requires a concrete tenant.    |
| **User Principal Name** | The mailbox to act on, e.g. `sales@yourco.com`. Required because without a user in the loop the `/me` endpoint cannot resolve a mailbox. |

#### Path C — Pre-obtained access token (diagnostics)

Useful for tests when you already have a short-lived bearer token.

| Keyword                 | Description                                                    |
| ----------------------- | -------------------------------------------------------------- |
| **Auth Scheme**         | `AccessToken`                                                  |
| **OAuth Access Token**  | A valid bearer token for the Graph API.                        |
| **User Principal Name** | Optional; only needed if the token is for an app-only context. |

#### Path D — Resource Owner Password Grant (legacy, discouraged)

Microsoft discourages this flow because it can't support MFA. Included for completeness.

| Keyword                 | Description                     |
| ----------------------- | ------------------------------- |
| **Auth Scheme**         | `OAuthPassword`                 |
| **OAuth Client Id**     | Application (Client) ID.        |
| **OAuth Client Secret** | Client secret.                  |
| **Tenant Id**           | Tenant GUID or verified domain. |
| **User**                | The user's full email address.  |
| **Password**            | The user's password.            |

#### Optional — common

| Keyword                 | Default   | Description                                                                                                   |
| ----------------------- | --------- | ------------------------------------------------------------------------------------------------------------- |
| **API Version**         | `v1.0`    | Microsoft Graph API version. `beta` is accepted but not recommended for production.                           |
| **Timeout**             | `60`      | HTTP timeout in seconds.                                                                                      |
| **User Principal Name** | *(empty)* | For delegated auth, leave empty to use the `/me` endpoint. For app-only access, required (names the mailbox). |

#### 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 Microsoft Graph

These parameters appear elsewhere in the Email connector but have no effect on Microsoft Graph connections and should be left out: `Host`, `Port`, `Use SSL`, `SMTP Host`, `SMTP Port`, `SMTP Use SSL`, `Default Folder`, `Use POP3`, `POP3 Host`, `POP3 Port`.

### Example connection strings

**Delegated access with a refresh token — single user mailbox:**

```
Email Provider=MicrosoftGraph;
Auth Scheme=OAuth;
Tenant Id=common;
OAuth Client Id=12345678-1234-1234-1234-123456789abc;
OAuth Client Secret=abcDEF~xxxxxxxxxxxxxxxxxxxxxxxxxxx;
OAuth Refresh Token=0.AXoA...xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
Callback URL=http://localhost:33333;
Log Level=1
```

**App-only access — service reading a shared mailbox:**

```
Email Provider=MicrosoftGraph;
Auth Scheme=OAuthClientCredentials;
Tenant Id=contoso.onmicrosoft.com;
OAuth Client Id=12345678-1234-1234-1234-123456789abc;
OAuth Client Secret=abcDEF~xxxxxxxxxxxxxxxxxxxxxxxxxxx;
User Principal Name=support@contoso.com;
Log Level=1
```

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

```
Email Provider=MicrosoftGraph;
Auth Scheme=AccessToken;
OAuth Access Token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsInuxxxxxx...;
Log Level=2
```

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

For delegated access, 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**, **Tenant Id**, 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 Microsoft Graph.
   * **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 app registration requires it.
3. Click **Get Token**. The portal starts a local HTTP listener on the callback URL, opens a popup to Microsoft's login page, and waits for the redirect. Sign in with the 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 Microsoft does not return a refresh token (rare for Microsoft accounts, common when scopes don't include `offline_access`), the form raises a message explaining how to re-authorize. Make sure `offline_access` is in the Scopes list.

For app-only (client credentials) access, no interactive flow is needed — the connector gets a token directly from the tenant's token endpoint on each connection open. You do not use the OAuth Configuration window.

### Schema

A Microsoft Graph connection exposes three virtual tables:

* **Messages** — all Graph-standard columns are mapped: `Id`, `Subject`, `Body`, `BodyPreview`, `From`, `To/Cc/Bcc Recipients`, `ReceivedDateTime`, `SentDateTime`, `IsRead`, `IsDraft`, `Importance`, `HasAttachments`, `ConversationId`, `ParentFolderId`, `InternetMessageId`, `Categories`, `FlagStatus`. Gmail-specific columns `ThreadId`, `LabelIds`, and `Snippet` are not populated.
* **Folders** — Exchange mail folders, including well-known folders (`inbox`, `drafts`, `sentitems`, `deleteditems`, `junkemail`, `archive`, `outbox`) and user-created folders, including nested folders addressed as `Parent/Child` paths.
* **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 mail folder
* `UPDATE Messages` — mark as read/unread, change importance, set categories, flag or unflag, move to another folder via `ParentFolderId`
* `DELETE FROM Messages` — moves the message to Deleted Items

Stored procedures: `SendMail`, `Reply`, `ReplyAll`, `Forward`, `MarkAsRead`, `MarkAsUnread`, `FlagMessage`, `MoveMessage`, `CopyMessage`, `CreateFolder`, `DownloadAttachment`, `ListFolders`, `GetUserInfo`, `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_client` on connection open** — Client ID or Client Secret is wrong, or the app registration is in a different tenant than the one you specified.
* **`invalid_grant` on connection open** — refresh token is expired or has been revoked (e.g. the user changed their password, or the token wasn't used for 90 days). Re-run the authorization flow.
* **`AADSTS50020` or `AADSTS70016`** — the user is in a tenant that doesn't trust your app registration (for personal Microsoft accounts with a single-tenant app). Either set `Tenant Id=common` or re-register the app as multi-tenant.
* **`403 Forbidden` on a specific operation** — the app registration lacks the required Graph permission for that operation, or admin consent hasn't been granted. Check the app registration's API permissions page.
* **403 on client-credentials access** — the `Mail.ReadWrite` and `Mail.Send` permissions must be granted as **Application** permissions (not Delegated) and an administrator must have granted tenant consent.
* **`User Principal Name` ignored or misreporting** — only honored for app-only access. For delegated access, the signed-in user's mailbox is used.
* **Throttling (429) during large exports** — Graph limits per-tenant and per-mailbox request rates. Lower the parallelism, and if you have one, retry after the `Retry-After` header the connector logs at level 1.


---

# 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-1.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.
