> 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/email.md).

# IMAP

## Generic IMAP + SMTP

Connect appRules to any standards-compliant IMAP server for reading and managing mail, and to an SMTP server for sending. Backed by **MailKit**. Suitable for self-hosted mail servers (Dovecot, Courier), on-premises Exchange via IMAP, hosted-mail providers, and cloud mailboxes reached with App Passwords or XOAUTH2.

For Microsoft 365 or Gmail via their native REST APIs — recommended when available — see the Microsoft Graph page or the Gmail page.

### Prerequisites

Before you can connect, you need:

* The **IMAP hostname and port** of your mail server (typically port 993 with SSL, or 143 with STARTTLS)
* The **SMTP hostname and port** if you intend to send mail (typically 587 with STARTTLS, 465 with implicit SSL, or 25 plain)
* Credentials for the mailbox, either:
  * A password (or App Password), for Basic auth, or
  * A pre-obtained **XOAUTH2 access token**, for OAuth auth

**Microsoft 365 note**: Microsoft disabled Basic auth over IMAP, POP3, and SMTP for most tenants in late 2022. To reach a Microsoft 365 mailbox via IMAP, use XOAUTH2 — obtain the access token through the Microsoft Graph OAuth flow, then pass it via `Auth Scheme=AccessToken` here.

**Gmail note**: Google disabled "less secure app" password access in 2022. To reach a Gmail mailbox via IMAP, generate an **App Password** on the Google account (requires 2-factor authentication) and use it as `Password`.

### Connection parameters

Keywords are case-insensitive, and both spaced and unspaced forms are accepted (`Use SSL` and `UseSsl` work the same).

#### Required — identifying the provider

| Keyword            | Value                    | Description                                                                                                      |
| ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| **Email Provider** | `IMAP`                   | Selects the generic IMAP + SMTP backend.                                                                         |
| **Auth Scheme**    | `Basic` or `AccessToken` | How to authenticate. `Basic` uses username and password. `AccessToken` uses an OAuth 2.0 bearer token (XOAUTH2). |

#### Required — Basic authentication (`Auth Scheme = Basic`)

| Keyword      | Description                                  |
| ------------ | -------------------------------------------- |
| **User**     | The mailbox user name or full email address. |
| **Password** | The account password or an App Password.     |

#### Required — OAuth 2.0 / XOAUTH2 (`Auth Scheme = AccessToken`)

| Keyword                | Description                                                    |
| ---------------------- | -------------------------------------------------------------- |
| **User**               | The mailbox email address (used in the XOAUTH2 handshake).     |
| **OAuth Access Token** | A valid bearer token the IMAP/SMTP server accepts via XOAUTH2. |

#### Required — transport

| Keyword     | Default      | Description                                                                                                                                      |
| ----------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Host**    | *(required)* | IMAP server hostname (e.g. `imap.gmail.com`, `outlook.office365.com`, `mail.example.com`).                                                       |
| **Port**    | `0` → auto   | IMAP server port. `0` resolves to 993 when `Use SSL=True`, or 143 when `Use SSL=False`.                                                          |
| **Use SSL** | `True`       | `True` connects with SSL on connect (implicit SSL, port 993). `False` connects plain and uses STARTTLS when the server advertises it (port 143). |

#### Required for sending — SMTP

Required only if you intend to `INSERT INTO Messages` (send mail). If omitted, the connection opens for read-only use.

| Keyword          | Default   | Description                                                                                             |
| ---------------- | --------- | ------------------------------------------------------------------------------------------------------- |
| **SMTP Host**    | *(empty)* | SMTP server hostname. Often the same as `Host`, but not always.                                         |
| **SMTP Port**    | `587`     | `587` for STARTTLS (recommended), `465` for implicit SSL, `25` for plain.                               |
| **SMTP Use SSL** | `True`    | `True` uses the mode implied by the port (SslOnConnect for 465, StartTls for 587). `False` sends plain. |

#### Optional

| Keyword            | Default | Description                                                        |
| ------------------ | ------- | ------------------------------------------------------------------ |
| **Default Folder** | `INBOX` | Folder used when a `SELECT ... FROM Messages` doesn't specify one. |
| **Timeout**        | `60`    | 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 IMAP/SMTP operation and per record written, `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.                                                                                                    |

#### Not applicable to IMAP

These parameters appear elsewhere in the Email connector but have no effect on IMAP connections and should be left out: `Tenant Id`, `User Principal Name`, `API Version`, `Callback URL`, `OAuth Client Id`, `OAuth Client Secret`, `OAuth Refresh Token`, `OAuth Scopes`, and all `Proxy *`, `Firewall *`, and `SSL Server Cert` keywords (the IMAP transport uses its own connection stack, separate from the REST `HttpClient`).

### Example connection strings

**Standard — IMAP + SMTP against a self-hosted or standards-compliant server:**

```
Email Provider=IMAP;
Auth Scheme=Basic;
Host=mail.example.com;
Port=993;
Use SSL=True;
SMTP Host=mail.example.com;
SMTP Port=587;
SMTP Use SSL=True;
User=alice@example.com;
Password=xxxxxxxx;
Default Folder=INBOX;
Log Level=1
```

**Read-only — no SMTP configured:**

```
Email Provider=IMAP;
Auth Scheme=Basic;
Host=mail.example.com;
Port=993;
Use SSL=True;
User=alice@example.com;
Password=xxxxxxxx;
Log Level=1
```

**Gmail via IMAP with an App Password:**

```
Email Provider=IMAP;
Auth Scheme=Basic;
Host=imap.gmail.com;
Port=993;
Use SSL=True;
SMTP Host=smtp.gmail.com;
SMTP Port=587;
User=you@gmail.com;
Password=xxxxxxxxxxxxxxxx;
Log Level=1
```

**Microsoft 365 via IMAP with XOAUTH2:**

```
Email Provider=IMAP;
Auth Scheme=AccessToken;
Host=outlook.office365.com;
Port=993;
Use SSL=True;
SMTP Host=smtp.office365.com;
SMTP Port=587;
User=you@yourco.com;
OAuth Access Token=eyJ0eXAiOiJKV1QiLCJhbGciOi...xxxxxxxxx;
Log Level=1
```

The access token must be obtained separately. The simplest route is to create a second connection using the Microsoft Graph provider, run the **OAuth Configuration** window on it to get a valid access token, then copy that token into the `OAuth Access Token` field of the IMAP connection. The token is short-lived (typically one hour), so this approach is practical for diagnostics and one-off work but not for long-running production IMAP connections against Microsoft 365 — for production use the Graph provider directly.

### Schema

An IMAP connection exposes three virtual tables:

* **Messages** — mapped from IMAP `FETCH ENVELOPE`, `FLAGS`, and body parts. Populated columns: `Id`, `Subject`, `Body`, `BodyPreview`, `From`, `To/Cc/Bcc Recipients`, `ReceivedDateTime`, `SentDateTime`, `IsRead`, `IsDraft`, `HasAttachments`, `ParentFolderId`, `InternetMessageId`, `FlagStatus`. Not populated (IMAP has no equivalent): `ConversationId`, `Categories`, `Importance`, `ThreadId`, `LabelIds`, `Snippet`.
* **Folders** — IMAP folders in the user's personal namespace, including the well-known `INBOX` and any user-created folders. Nested folders are addressed by their full path (e.g. `Archive/2025`).
* **Attachments** — attachments of a given message. Requires a `MessageId` filter in the WHERE clause. Fetched by walking the message's MIME structure.

#### Message identifiers

Message IDs are a composite string of the form `{folder}|{uidValidity}-{uid}` — for example `INBOX|1402557887-1821`. The `uidValidity` portion is set by the IMAP server when the folder is created and lets IDs survive across reconnects. You can use these IDs verbatim in UPDATE and DELETE statements.

### Supported operations

* `SELECT` on Messages, Folders, Attachments
* `INSERT INTO Messages` — sends mail via SMTP, or APPENDs to the Drafts folder when `IsDraft = true`
* `INSERT INTO Folders` — creates a mail folder
* `UPDATE Messages` — mark as read/unread (`isRead`), flag/unflag (`flagStatus`), move to another folder (`ParentFolderId`)
* `DELETE FROM Messages` — marks with `\Deleted` and expunges

Stored procedures: `SendMail`, `MarkAsRead`, `MarkAsUnread`, `FlagMessage`, `MoveMessage`, `CopyMessage`, `CreateFolder`, `DownloadAttachment`, `ListFolders`, `SetFlags` (IMAP-specific).

**Not supported on IMAP** (throw `FeatureNotSupportedException` with a clear message): `Reply`, `ReplyAll`, `Forward`, `GetUserInfo`, and all OAuth procedures. These require backend-specific endpoints the IMAP protocol does not provide. For reply/forward functionality from IMAP, build the response yourself and `INSERT INTO Messages`.

### WHERE clause support

The IMAP SEARCH command supports a narrower set of conditions than Microsoft Graph's `$filter`. The connector translates the following on the server side:

* `IsRead = true` / `IsRead = false`
* `HasAttachments = true`
* `Subject = 'text'` or `Subject LIKE '%text%'` → server-side `SUBJECT`
* `FromAddress = 'alice@example.com'` → server-side `FROM`
* `ToRecipients = 'bob@example.com'` → server-side `TO`
* `ReceivedDateTime >= '2026-01-01'` and the other comparison forms → server-side `SINCE`, `BEFORE`, `ON`

Any WHERE clause the translator doesn't recognize is **ignored** — the SELECT returns more rows rather than fewer. A warning is written to the log at level 1 so you can spot conditions that aren't being enforced server-side.

### Performance notes

* **`SELECT COUNT(*) FROM Messages`** uses a dedicated fast path: a single IMAP SEARCH returning the UID count, without fetching envelopes or bodies. Even on folders with thousands of messages this returns in well under a second.
* **`SELECT` with body columns** fetches only the text/plain and text/html body parts, leaving attachments on the server — a message with a 10 MB PDF attachment costs only its body bytes.
* **Idle timeouts**: some IMAP servers disconnect idle sessions after \~30 minutes. The transport reconnects on demand, so the first query after a long pause may take an extra moment.

### Troubleshooting

* **`Attempting to establish an SSL or TLS connection ... port 143 is typically reserved for plain-text connections`** — you set `Port=143` with `Use SSL=True`. Change to `Port=993` (keeping SSL), or to `Use SSL=False` (keeping port 143 with STARTTLS).
* **`Authentication failed`** against Microsoft 365 with Basic auth — M365 disabled Basic over IMAP in 2022. Switch to `Auth Scheme=AccessToken` with an XOAUTH2 token.
* **`Authentication failed`** against Gmail with your account password — Google disabled "less secure app" password access. Generate an App Password (requires 2FA) and use that as `Password`.
* **`FolderNotFoundException`** on SELECT — the folder name doesn't match anything in the user's personal namespace. Try `SELECT * FROM Folders` first to see what's there; nested folders use `/` separators (`Archive/2025`).
* **`SELECT COUNT(*)` is slow on an older build** — the fast path was added in the current build. Confirm you're running a build that has it: the log shows `[IMAP] INBOX: COUNT(*) via folder.Count = N` at level 1.
* **Empty `FromAddress` / `FromName` columns** — on older builds the translator rewrote column names to Graph paths that IMAP didn't recognize. Fixed in the current build. If you still see this, run with `Log Level=3` and check whether the envelope lines show the sender correctly.


---

# 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/email.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.
