# Outlook Mail Intelligence – Microsoft 365 (`badr_xba/outlook-mail-intelligence`) Actor

Read your Microsoft 365 work/school mailbox READ-ONLY via Microsoft Graph, with your organization's own Entra app: sign in on Microsoft's page with a short code (Mail.Read only), search, folders, JSON/CSV export, attachments, stats, duplicates, threads, phishing signs, new-mail checks. Free demo.

- **URL**: https://apify.com/badr_xba/outlook-mail-intelligence.md
- **Developed by:** [Badr Bouargan](https://apify.com/badr_xba) (community)
- **Categories:** Automation, AI
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.40 / 1,000 e-mail reads

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Outlook Mail Intelligence – Microsoft 365

> **For Microsoft 365 work/school accounts (your organization's own app).** This Actor reads a Microsoft 365
> business or school mailbox through an app that **your organization's administrator** creates in Microsoft Entra
> (about 5 minutes, free – see "For your administrator" below). Personal Microsoft accounts (Outlook.com, Hotmail,
> Live) are **not supported** in this version.

Turn **your Microsoft 365 mailbox** into clean, searchable data, **read-only**, through **Microsoft Graph**. You sign
in **on Microsoft's own page** with a short code: no password is ever typed into this Actor. Pick folders, dates,
senders or a search, and get one row per e-mail with its text, folder, attachments, category, conversation,
duplicate check and phishing warning signs, plus a mailbox report – and, if you want, an **AI summary with your own
OpenAI, Anthropic or Gemini key**.

**Try it first for free:** run it with an empty input and you get a **demo on a fictional mailbox** (14 invented
e-mails, clearly marked `demo: true`) in a few seconds – no Microsoft account, nothing charged.

> **Not affiliated with Microsoft.** Outlook, Microsoft 365, Microsoft Graph and Microsoft Entra are trademarks of
> Microsoft Corporation, used only to describe compatibility. No Microsoft or Outlook logo is used.

![Your Outlook mail, read-only, as clean data](https://api.apify.com/v2/key-value-stores/R1P4OnWyoV0LnGBin/records/outlookmail-01-cover.png)

### Who is it for?

- **Companies, schools and their teams** on Microsoft 365 who want invoices, orders, support tickets or client
  e-mails as a spreadsheet or JSON, without installing anything.
- **Developers and automation builders** who need Microsoft 365 mail in a pipeline (Apify API, webhooks, Make,
  Zapier, n8n) with a stable schema – including "only the new e-mails since the last run" on a schedule.
- **IT administrators** who want a read-only export they control: the app lives in their own directory, they grant
  and revoke it.

Each user reads **their own** mailbox (delegated permission): no access to colleagues' mailboxes.

### For your administrator: create the app (about 5 minutes, free)

The menu names below are written from Microsoft's documentation; Microsoft renames menus from time to time, so
look for the closest name if one differs.

1. Open the **Microsoft Entra admin center** (**entra.microsoft.com**) with an account allowed to register apps.
2. **Identity → Applications → App registrations → New registration**:
   - **Name:** for example `Mail export (Apify)`;
   - **Supported account types:** **Accounts in this organizational directory only (single tenant)**;
   - **Redirect URI:** leave empty (the code sign-in does not need one);
   - click **Register**.
3. **Authentication** → **Advanced settings** → **Allow public client flows** = **Yes** (this enables the device code
   sign-in) → **Save**.
4. **API permissions** → **Add a permission** → **Microsoft Graph** → **Delegated permissions** → tick **Mail.Read**
   (and **offline_access**) → **Add permissions**. Remove **User.Read** if it was added by default (not needed).
   Then click **Grant admin consent for <your organization>**.
5. Create **no client secret** and **no certificate**: the app is a public client.
6. On the app's **Overview** page, copy the **Application (client) ID** and the **Directory (tenant) ID** and give
   them to the users. Both are identifiers, not secrets.

**Conditional Access:** some organizations block the device code sign-in with a Conditional Access policy (the run
then ends with `CONDITIONAL_ACCESS_BLOCKED`). An administrator can exclude this app – or the users concerned – from
the policy that blocks the "device code flow", if your security rules allow it.

### How it works: connect once, then read

1. **Connect** (once, about 2 minutes). Run the Actor with **Mode = Connect**, the **Client ID** and **Tenant ID**
   from your administrator, and a **Connection passphrase** of your choice (at least 12 characters, typed in a
   secret field). The run's **status message** shows a short code, for example `K7QH-29XM`. Open
   **https://microsoft.com/devicelogin**, type the code, sign in with your work or school account (multi-factor
   included) and confirm. The run waits for you – up to **10 minutes** – then reads your
   Inbox in the same run. Keep the run timeout at the default (1,800 s): a connect run needs at least 20 minutes.
2. **Read** (every later run, or a schedule). Run with **Mode = Read** (or Auto), the same Client ID, Tenant ID and
   **passphrase**: no code, no sign-in. Use a saved **task** to keep your settings.
3. **Disconnect** when you are done (see "How to remove the access").

The connection is saved **encrypted with your passphrase** (AES-256-GCM, key derived with scrypt) in a key-value
store of **your own Apify account** (`outlook-mail-intelligence`). Microsoft renews the connection at each use; it
expires after a period without use (about 90 days by default, your organization may set it shorter). Your
passphrase is never stored: without it, the saved connection cannot be opened. Prefer nothing stored? Turn off
**Remember the connection**: the sign-in is then used for that one run only.

Several mailboxes? Give each one a different **Connection name**.

![Connect with a short code, on Microsoft's own page](https://api.apify.com/v2/key-value-stores/R1P4OnWyoV0LnGBin/records/outlookmail-02-connect-with-a-code.png)

### Permissions, explained

| Permission | Why | What it allows |
|---|---|---|
| `Mail.Read` (delegated) | To read your e-mails and attachments | Read the mail of the signed-in user only. Not send, not delete, not move, not change. |
| `offline_access` | So that later runs work without signing in again | Lets Microsoft give a refresh token. It gives **no access to any data** by itself. |

Nothing else is asked: no profile (`User.Read`), no contacts, no calendar, no write permission, no application
permission, never a password. Inside the Actor, an **allow-list** lets through only mail *read* requests on the
signed-in user's own mailbox and the sign-in to **your organization's tenant only**; every other request – send,
reply, forward, move, copy, delete, mark as read, other users – is **refused before it is sent**. Nothing is ever
marked as read.

### Input examples

Demo (no Microsoft account):

```json
{}
```

First connection, then read last month's invoices with their files:

```json
{
  "mode": "connect",
  "clientId": "00000000-0000-0000-0000-000000000000",
  "tenantId": "contoso.onmicrosoft.com",
  "tokenPassphrase": "<typed in the secret field>",
  "searchQuery": "subject:invoice hasAttachments:true",
  "downloadAttachments": true,
  "maxMessages": 200
}
```

Later runs, two folders, unread only, between two dates:

```json
{
  "mode": "read",
  "clientId": "00000000-0000-0000-0000-000000000000",
  "tenantId": "contoso.onmicrosoft.com",
  "tokenPassphrase": "<typed in the secret field>",
  "folders": ["Inbox", "Inbox/Clients"],
  "unreadOnly": true,
  "dateFrom": "2026-10-01",
  "dateTo": "2026-10-31"
}
```

Scheduled every hour, only the new e-mails: same as above with `"monitorNewOnly": true`.

**Folders** accept names (`Inbox`, `Sent Items`, `Archive`, `Junk Email`, `Deleted Items`, `Drafts`, your own
folders), paths (`Inbox/Clients`) or `All`. **Search (KQL)** is Microsoft's own search: `from:`, `to:`, `subject:`,
`hasAttachments:true`, `received>=2026-01-01`, quotes, `AND` / `OR`. Microsoft returns at most **1,000 results per
search**; the date, unread and sender filters are then applied to those results.

![One clean row per e-mail](https://api.apify.com/v2/key-value-stores/R1P4OnWyoV0LnGBin/records/outlookmail-03-email-rows.png)

### What you get

| Feature | What it does | Charged? |
|---|---|---|
| Read & search | Folders and subfolders, Microsoft search (KQL), date range, senders, subject words, unread only, with attachments only, newest first | per e-mail read |
| Export | Dataset (JSON, CSV, Excel, API) + a spreadsheet-safe `EMAILS_CSV` file | included |
| Attachments | Name, type, size for every file; optional saving to your key-value store with SHA-256 and per-file / per-run size limits | file saved |
| Mailbox report | Folders (Outlook's own totals and unread counts), top senders and domains, e-mails per month / weekday / hour, categories, attachments, duplicates | once per run |
| Duplicates | Same Message-ID or same content found twice (reported only, never deleted) | free |
| Conversations | Outlook's `conversationId` plus `References` / `In-Reply-To` | free |
| Phishing warning signs | Display name vs address, Reply-To mismatch, link text vs real link, links to IP addresses, risky / double extensions (`invoice.pdf.exe`), SPF / DKIM / DMARC fail. **Indicators only, never a verdict** | free |
| Category (rules) | Business, Personal, Invoices, Orders, Support, Marketing, Important, Other | free |
| New e-mails since the last run | Microsoft "delta" queries per folder, for scheduled runs | per new e-mail |
| AI summary + category | With **your own** OpenAI / Anthropic / Gemini key (optional, off by default) | per e-mail analysed |
| Demo mode | Fictional sample mailbox, no Microsoft account | never |

### Output

One dataset row per e-mail (`type: "email"`), for example:

```json
{
  "type": "email",
  "source": "outlook",
  "folder": "Inbox",
  "outlookId": "AAkALgAAAAAAHYQDEapmEc2byACqAC-EWg0A…",
  "conversationId": "AAQkADAwATM0MDAAMS1iNTcwLWI2NTEt…",
  "webLink": "https://outlook.office365.com/owa/?ItemID=…",
  "date": "2026-11-02T08:15:00Z",
  "from": {"name": "Northwind Supplies Billing", "email": "billing@northwind-supplies.example"},
  "subject": "Invoice INV-2026-1042 for October",
  "snippet": "Hello, Please find attached invoice INV-2026-1042 (amount due: EUR 1,240.00...",
  "attachments": [{"safeFilename": "invoice-INV-2026-1042.pdf", "size": 95, "sha256": "…", "riskyExtension": false}],
  "category": "Invoices",
  "importance": "normal",
  "phishingRiskLevel": "none",
  "duplicateOf": null,
  "isRead": false,
  "demo": false
}
```

Other rows: `attachment`, `ai-analysis`, `thread`, `duplicate-group`, `mailbox-report`. Ready-made views: **E-mails,
Phishing indicators, Attachments, AI summaries, Conversations and duplicates**. Files in the key-value store:
`MAILBOX_REPORT`, `EMAILS_CSV`, `FOLDERS`, `RUN_SUMMARY`, `FAILED_INPUTS`, and saved attachments (`att-…`). Demo rows
carry `demo: true`.

### Only the new e-mails, on a schedule

Turn on **Only new e-mails since the last run** and schedule the Actor (Apify → Schedules, for example every hour).
The first run returns the e-mails since **From date** (default: the last 24 hours) and saves a starting point per
folder, encrypted with your connection; each next run returns only what arrived since the previous run. This is
**not live monitoring**: one run = one check, as often as your schedule. If more new e-mails arrive than **Maximum
e-mails**, the next run continues. Microsoft search cannot be combined with this option.

![Only the new e-mails, run after run](https://api.apify.com/v2/key-value-stores/R1P4OnWyoV0LnGBin/records/outlookmail-04-new-mail-checks.png)

### Optional AI – with your own key

Choose OpenAI, Anthropic or Gemini and paste **your** API key in the secret field. Each analysed e-mail gets a short
summary, a category, key points, action items and an injection flag. The AI cost is billed by your AI provider.
Check your organization's rules before sending business e-mails to an AI provider.

E-mail content can contain hidden instructions ("ignore previous instructions…"). This Actor is built so that they
cannot do anything:

- the e-mail is sent as **data** inside a clearly delimited block, after removing hidden HTML text and invisible
  characters; addresses and phone numbers are masked by default;
- the AI has **no tools** – it can only answer with a small JSON object, which is **checked strictly** (any extra
  field, wrong value or free text is rejected and the rules category is kept);
- the answer is only stored as text in your results: it never triggers an action, never changes billing or the
  phishing signs; and the Actor itself can only read mail;
- e-mails that look like injection attempts are flagged (`aiPossiblePromptInjection`).

There is no shared or managed AI key: without your key, no AI call is made.

![AI summary with your own key](https://api.apify.com/v2/key-value-stores/R1P4OnWyoV0LnGBin/records/outlookmail-05-ai-your-key.png)

### Pricing

Pay per event – the current prices are on the **Pricing tab**. There is **no start fee**.

- **Charged:** each unique e-mail read, each attachment file saved, each e-mail analysed by AI (your key), one
  mailbox report per run.
- **Never charged:** demo e-mails, duplicates, conversations, duplicate groups, phishing signs, rules categories,
  disconnect runs, scheduled checks with no new e-mail, and runs that could not read the mailbox (sign-in declined
  or expired, admin consent missing, connection expired…).
- A connect run waits for your sign-in (up to 10 minutes, not charged): only the Apify compute time of that wait is used
  (default memory 256 MB), no event is charged for it.
- Your **Maximum cost per run** is respected: the run stops cleanly and keeps every row already delivered.
- Microsoft does not charge for reading your own mail through Microsoft Graph.

### When something goes wrong

The run still ends **SUCCEEDED** with a clear status message telling you what to do; `RUN_SUMMARY` shows
`status: "CUSTOMER_ERROR"` with the `errorCode`, and `FAILED_INPUTS` lists each problem. Nothing is charged.

| Code | What it means / what to do |
|---|---|
| `APP_REQUIRED` | Fill in **Client ID** and **Tenant ID** of your organization's app (see "For your administrator"). |
| `NOT_CONNECTED` | No saved connection under this name: run once with Mode = Connect. |
| `PASSPHRASE_REQUIRED` / `PASSPHRASE_WRONG` | Type your connection passphrase (12+ characters), the same one as when you connected. Lost it? Disconnect, then Connect again. |
| `DEVICE_CODE_EXPIRED` | Nobody entered the code within 10 minutes. Run Connect again and enter the new code right away. |
| `DEVICE_CODE_DECLINED` / `DEVICE_CODE_INVALID` | The sign-in was cancelled, or the code was not accepted. Run Connect again. |
| `CONNECT_NEEDS_MORE_TIME` | The run timeout is too short to wait for the sign-in: set at least 1,200 seconds. |
| `ADMIN_CONSENT_REQUIRED` | Admin consent for Mail.Read is missing: your administrator clicks **Grant admin consent** in the app's API permissions. |
| `CONDITIONAL_ACCESS_BLOCKED` | Your organization's Conditional Access blocks the device code sign-in. Ask your administrator (see above). |
| `ACCOUNT_NOT_IN_TENANT` / `AUTHORITY_MISMATCH` / `TENANT_NOT_FOUND` | Check **Tenant ID** and sign in with an account of that organization (personal accounts are not supported). |
| `APP_NOT_FOUND` / `PUBLIC_CLIENT_DISABLED` | Check **Client ID**, and that the app has **Allow public client flows = Yes**. |
| `TOKEN_EXPIRED_OR_REVOKED` / `RECONNECT_REQUIRED` | The saved connection expired or was revoked, or Microsoft asks for a new sign-in: run Connect again. |
| `PERMISSION_MISSING` | The Mail.Read permission is missing or was removed from the app. |
| `MAILBOX_NOT_FOUND` | This account has no mailbox that Microsoft Graph can read (no Exchange Online licence, on-premises mailbox…). |
| `THROTTLED` / `MICROSOFT_UNREACHABLE` | Microsoft's limits or servers: the Actor waited and retried (honouring Retry-After); rows already read are kept. Run again later. |
| `GRAPH_API_ERROR` / `AUTH_FAILED` | Another Microsoft refusal; the message gives its short code. Check the search and filters. |
| `STORAGE_UNAVAILABLE` | Your Apify key-value store did not answer in time. Run again. |
| `INVALID_INPUT` / `READ_ONLY_VIOLATION` | An input value is invalid (the field is named), or a non-read request was refused by the guard. |
| `FOLDER_NOT_FOUND` | A folder does not exist (your folders are listed); the other folders are still read. |
| `DELTA_TOKEN_INVALID` | The starting point of "new e-mails" was too old for Microsoft: a new one is taken (not an error). |

Turn on **failRunOnError** if you prefer a FAILED run (for scheduled monitoring). The run also stops cleanly before
its timeout.

### How long does it take?

The demo takes a few seconds. A connect run waits for your sign-in (usually 1–2 minutes, at most 15). Reading
depends on Microsoft's answer time and the size of the e-mails; start with the default 50 e-mails, then raise
**Maximum e-mails** (up to 10,000 per run). Default memory: 256 MB.

### How to remove the access

1. **In this Actor:** run **Mode = Disconnect** with the same Connection name. It deletes the saved encrypted
   connection (and the "new e-mails" starting point) from your key-value store. No passphrase needed.
2. **As a user:** at **https://myapps.microsoft.com**, open the app and revoke its permissions (if your organization
   allows it).
3. **As an administrator:** Entra admin center → **Enterprise applications** → the app → **Permissions** (revoke the
   consent) or **Properties → Delete**; deleting the app in **App registrations** stops every connection at once.
   Revoking a user's sessions also ends their saved connection.
4. **On Apify:** clear the passphrase and AI key from saved inputs and tasks, and delete the runs' datasets if you no
   longer need them.

![Safe to try: free demo, then your mailbox](https://api.apify.com/v2/key-value-stores/R1P4OnWyoV0LnGBin/records/outlookmail-06-safe-to-try.png)

### Privacy

- Your e-mails go from Microsoft directly to **your own** Apify run and are stored only in that run's dataset and
  key-value store (set a data retention period in your Apify settings if you want them deleted automatically).
- The app belongs to **your organization**; the saved connection stays in **your own** Apify account, encrypted with
  **your** passphrase. The Actor's developer has no app, no access and no copy.
- No copy is sent anywhere else, except to **your own** AI provider, only if you turn AI on. No tracking.
- Only mailboxes you are authorised to read, in line with your organization's policies, Microsoft's terms and the
  privacy rights of the people in your e-mails.

### Limits and honest notes

- Needs an app created by your organization's administrator (5 steps above); some organizations block the device
  code sign-in with Conditional Access.
- Personal Microsoft accounts (Outlook.com, Hotmail, Live) are not supported.
- A connect run must stay open while you sign in (up to 10 minutes); later runs need no sign-in until the connection
  expires or is revoked.
- Microsoft search returns at most 1,000 results per search; e-mails from online archives and on-premises-only
  mailboxes cannot be read.
- Each run reads up to 10,000 e-mails (newest first). "Only new e-mails" works per folder, between scheduled runs:
  it is not live monitoring.
- Statistics cover the e-mails read in the run (after your filters and limits), plus Outlook's own folder totals.
- Phishing signs are heuristics: a legitimate newsletter can show some of them, and a phishing e-mail can show none.
  They are never a malware or phishing verdict; no file is scanned or opened.
- Cloud attachments (links to OneDrive / SharePoint) and attached Outlook items are listed, not downloaded.

#### Not in this version

Personal accounts, Contacts, calendar events and full mailbox backups (.eml / archive) are not in this version.
Reading many mailboxes with an administrator's application permission (client secret or certificate) is not
supported either.

### FAQ

**Will my e-mails be marked as read?** No. The only permission is Mail.Read; `isRead` shows Outlook's state,
unchanged.

**Can it delete, send or move e-mails?** No. The permission does not allow it, and a guard refuses every
non-read request before it reaches Microsoft.

**Do I give my password to the Actor?** Never. You sign in on Microsoft's own page (microsoft.com/devicelogin); the
Actor only receives a connection that you or your administrator can remove at any time.

**Why does my organization need its own app?** So that your administrator controls everything: who may use it,
which permission it has, and when it is removed. No third-party app gets access to your organization's mail.

**Why a passphrase?** It encrypts the saved connection in your Apify storage, so that nobody can use it without the
passphrase – not even with access to the storage.

Not affiliated with Microsoft.

# Actor input Schema

## `mode` (type: `string`):

auto = demo when nothing is filled in, read when a passphrase is given (or a new sign-in when no connection is saved yet). demo = fictional sample mailbox (nothing charged). connect = sign in with your work or school account on microsoft.com/devicelogin with the short code shown in the status message (keep the run open up to 15 minutes), then read. read = use the saved connection. disconnect = delete the saved connection.

## `connectionName` (type: `string`):

A name for this mailbox connection, for example 'personal' or 'work' (several mailboxes = several names). Letters, digits, spaces and \_ . @ - only.

## `tokenPassphrase` (type: `string`):

A passphrase YOU choose (at least 12 characters). It encrypts your saved Microsoft connection (AES-256-GCM) in your own Apify key-value store. Use the same one for every run of this connection; it is never stored, logged or shown. Lost it? Run Disconnect, then Connect again.

## `rememberConnection` (type: `boolean`):

On (default): the connection is saved encrypted so that later and scheduled runs work without signing in again. Off: nothing is stored, the sign-in is used for this run only (a one-time export).

## `clientId` (type: `string`):

Required to connect and read (not for the demo). The Application (client) ID of the app your Microsoft 365 administrator registered in your organization's Microsoft Entra (single tenant, 'Allow public client flows' = Yes, delegated permission Mail.Read with admin consent). A GUID. Not secret; no client secret is needed. See the README section 'For your administrator'.

## `tenantId` (type: `string`):

Required to connect and read (not for the demo). Your organization's Directory (tenant) ID (a GUID, shown next to the Client ID in the app's Overview page) or one of its verified domains, for example contoso.onmicrosoft.com. Personal Microsoft accounts are not supported.

## `folders` (type: `array`):

Folders to read, by name: Inbox, Sent Items, Archive, Junk Email, Deleted Items, Drafts, your own folders, or a path like Inbox/Clients. 'All' = every folder. Empty = Inbox. A folder that does not exist is reported in FAILED_INPUTS with the list of your folders.

## `includeSubfolders` (type: `boolean`):

Also read the subfolders of the chosen folders (3 levels, 50 folders at most).

## `searchQuery` (type: `string`):

Optional. Microsoft's own search (like the Outlook search box), for example: from:billing@example.com hasAttachments:true, or subject:invoice received>=2026-01-01. Microsoft returns at most 1,000 results per search. The date, unread and sender filters below are then applied to those results.

## `fromAddresses` (type: `array`):

Optional. Only e-mails from these senders. Full addresses are filtered by Microsoft; partial text (a name or a domain) is filtered by the Actor.

## `subjectContains` (type: `array`):

Optional. Only e-mails whose subject contains one of these words.

## `dateFrom` (type: `string`):

Only e-mails received on or after this day (YYYY-MM-DD, UTC).

## `dateTo` (type: `string`):

Only e-mails received on or before this day (YYYY-MM-DD, UTC).

## `unreadOnly` (type: `boolean`):

Only e-mails not yet read. They stay unread: this Actor never marks anything as read.

## `hasAttachments` (type: `boolean`):

Only e-mails that have at least one attached file.

## `monitorNewOnly` (type: `boolean`):

For scheduled runs: each run returns only the e-mails that arrived in the chosen folders since the previous run (Microsoft delta queries; the starting point is saved encrypted with your connection). The first run returns the e-mails since 'From date' (default: the last 24 hours). This is not live monitoring: schedule the Actor (for example every hour).

## `maxMessages` (type: `integer`):

Maximum number of e-mails read in this run (newest first).

## `requestTimeoutSecs` (type: `integer`):

How long to wait for one Microsoft answer before retrying (busy or failing requests are retried up to 3 times, honouring Retry-After).

## `services` (type: `array`):

Free analyses added to the results: stats = mailbox report; duplicates = same e-mail found twice; threads = conversations; phishing = warning signs (indicators, never a verdict); classify = category by rules; attachments = one row per attachment (metadata).

## `includeBody` (type: `boolean`):

Add the plain text of each e-mail (bodyText). Turn off to keep only headers, snippet and analyses.

## `bodyMaxChars` (type: `integer`):

Longer texts are cut (bodyTruncated: true).

## `includeHtml` (type: `boolean`):

Add the raw HTML (bodyHtml). It is never rendered or executed by the Actor.

## `includeHeaders` (type: `boolean`):

Add a short list of headers (Reply-To, Return-Path, Authentication-Results, List-Unsubscribe, priority...).

## `exportCsv` (type: `boolean`):

Save the e-mail list as EMAILS_CSV in the key-value store (one line per e-mail, spreadsheet-safe).

## `downloadAttachments` (type: `boolean`):

Save attached files to the run's key-value store, with their SHA-256 (never opened or executed). Risky types (.exe, .js, .html, macros...) and cloud links are never saved: metadata only.

## `maxAttachmentMb` (type: `integer`):

Bigger files are listed but not saved (tooLarge).

## `maxTotalAttachmentsMb` (type: `integer`):

When reached, other files are listed but not saved (runCapReached).

## `aiProvider` (type: `string`):

Optional. Uses YOUR OpenAI, Anthropic or Gemini key: the AI cost is billed by your provider. E-mail text is sent as untrusted data; the AI has no tools and can only return a summary and a category.

## `aiApiKey` (type: `string`):

Your own API key for the chosen AI provider. Stored as a secret input; never logged or written to the results.

## `aiModel` (type: `string`):

Leave empty for a low-cost default model of the chosen provider.

## `aiLanguage` (type: `string`):

Language of the AI summaries, for example English or French.

## `maxAiEmails` (type: `integer`):

Cost guard for your AI account.

## `redactBeforeAi` (type: `boolean`):

E-mail addresses and phone numbers in the text are replaced by \[redacted] before sending to your AI provider.

## `connectionStoreName` (type: `string`):

Name of the key-value store in YOUR Apify account that keeps the encrypted connection and the monitoring starting point. Change it only if you want to keep connections apart.

## `failRunOnError` (type: `boolean`):

Off (default): the run ends SUCCEEDED with a clear message and FAILED_INPUTS (expired connection, admin consent needed, sign-in cancelled...). On: those problems end the run as FAILED (useful for scheduled monitoring).

## Actor input object example

```json
{
  "mode": "demo",
  "connectionName": "default",
  "rememberConnection": true,
  "includeSubfolders": false,
  "unreadOnly": false,
  "hasAttachments": false,
  "monitorNewOnly": false,
  "maxMessages": 50,
  "requestTimeoutSecs": 30,
  "services": [
    "stats",
    "duplicates",
    "threads",
    "phishing",
    "classify"
  ],
  "includeBody": true,
  "bodyMaxChars": 20000,
  "includeHtml": false,
  "includeHeaders": true,
  "exportCsv": true,
  "downloadAttachments": false,
  "maxAttachmentMb": 10,
  "maxTotalAttachmentsMb": 100,
  "aiProvider": "none",
  "aiLanguage": "English",
  "maxAiEmails": 25,
  "redactBeforeAi": true,
  "connectionStoreName": "outlook-mail-intelligence",
  "failRunOnError": false
}
```

# Actor output Schema

## `emails` (type: `string`):

Received date, folder, sender, subject, snippet, category, phishing signs, attachments, read state, link to Outlook.

## `security` (type: `string`):

Warning signs with their evidence (indicators only, never a verdict).

## `attachments` (type: `string`):

File name, type, size, SHA-256, risky type, saved file key.

## `ai` (type: `string`):

Summary, AI category, action items, injection attempts.

## `threads` (type: `string`):

Conversation groups and duplicate groups (nothing is deleted).

## `allFields` (type: `string`):

Every field of every row (JSON, CSV, Excel export).

## `mailboxReport` (type: `string`):

Folders, top senders and domains, e-mails per month / weekday / hour, categories, attachments, duplicates.

## `csv` (type: `string`):

One line per e-mail, spreadsheet-safe.

## `folders` (type: `string`):

Your Outlook folders and what was read in each requested folder.

## `runSummary` (type: `string`):

Status, mode, connection, counts, Microsoft calls, billing, AI usage, stop reason, failure codes. Contains no secret.

## `failedInputs` (type: `string`):

Problems with a stable code and what to do: APP_NOT_CONFIGURED, NOT_CONNECTED, DEVICE_CODE_EXPIRED, ADMIN_CONSENT_REQUIRED, TOKEN_EXPIRED_OR_REVOKED, FOLDER_NOT_FOUND, AI_KEY_INVALID...

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "mode": "demo"
};

// Run the Actor and wait for it to finish
const run = await client.actor("badr_xba/outlook-mail-intelligence").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "mode": "demo" }

# Run the Actor and wait for it to finish
run = client.actor("badr_xba/outlook-mail-intelligence").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "mode": "demo"
}' |
apify call badr_xba/outlook-mail-intelligence --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,badr_xba/outlook-mail-intelligence"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/a4eXZhvPzoXby8wgN/builds/MvJjETcfjhuw2SBgs/openapi.json
