Skip to main content
Glama
README.md
# email_mcp

Supports multiple accounts m365 and gmail and runs an MCP so you can have more than one M365 account tied into Claude.  This is 100% AI authored.

`email_mcp` is a terminal (curses) app that:

- connects to **any number of email accounts**, including several of the same
  type (e.g. 3 Microsoft 365 tenants + 2 Gmail accounts)
- logs in with **OAuth 2.0 + PKCE in a real browser window driven by
  Playwright**, captures the tokens, refreshes them automatically and **prompts
  you to re-authenticate** when a refresh token expires or is revoked
- polls every account for new mail in the background
- runs an embedded **MCP server** (streamable HTTP) so Claude can read, search,
  send and reply to mail and read/create calendar events across all accounts

```
┌ Status ───────────────────────────────────────────────────────────────────────┐
│ MCP: http://127.0.0.1:8750/mcp   Polling every 300s · next in 212s            │
│ Label        Type    Email                    State          Unread  Last check│
│ work         m365    me@corp.com              ok                 12  1m ago    │
│ client-co    m365    me@client.com            needs_reauth        -  2h ago    │
│ personal     google  me@gmail.com             ok                  3  1m ago    │
└───────────────────────────────────────────────────────────────────────────────┘
┌ Actions ──────────────────┐┌ Log ─────────────────────────────────────────────┐
│ [a] Add account           ││ 10:02:11 INFO New mail [work] from Bob: Q4 plan   │
│ [r] Re-authenticate       ││ 10:02:12 WARN Account client-co needs re-auth…   │
│ [d] Remove account        ││                                                  │
│ [c] Check mail now        ││                                                  │
│ [p] Pause / resume polling││                                                  │
│ [i] Set poll interval     ││                                                  │
│ [m] MCP connection info   ││                                                  │
│ [l] Clear log             ││                                                  │
│ [q] Quit                  ││                                                  │
└───────────────────────────┘└──────────────────────────────────────────────────┘
```

## Requirements

- Python 3.10+ (developed on 3.13)
- **A Python virtual environment is required.** The app refuses to start from
  the system interpreter so its dependencies (MCP SDK, Playwright, httpx) never
  get mixed into your system Python. See [Setup](#setup).
- A desktop session (X11/Wayland/macOS/Windows): the login step opens a visible
  browser window. The MCP server itself can run headless once accounts are added.
- An OAuth app registration for each provider you want to use (instructions in
  [`exports.example`](exports.example)).

## Setup

### Quick start: `run.sh`

On macOS/Linux, `run.sh` does the whole setup for you:

```bash
cp exports.example exports
```

Edit `exports` (see below), then:

```bash
./run.sh
```

On first run it creates `.venv`, installs `requirements.txt` and Playwright's
Chromium, then starts the app inside the venv. Later runs reinstall only when
`requirements.txt` changes. Arguments pass through, e.g. `./run.sh --headless`.

### Manual setup

```bash
git clone https://github.com/skychair/email_mcp.git
```

```bash
cd email_mcp
```

Create and activate the virtual environment (required):

```bash
python3 -m venv .venv
```

```bash
source .venv/bin/activate
```

On Windows use `.venv\Scripts\activate`. Then install the dependencies and the
Playwright browser:

```bash
pip install -r requirements.txt
```

```bash
playwright install chromium
```

Every later run needs the venv activated first (`source .venv/bin/activate`).

## Configuration: the `exports` file

All configuration lives in environment variables stored in a file named
`exports` in the repo root. That file holds secrets and is **git-ignored**;
[`exports.example`](exports.example) is the committed template with every
option documented, including step-by-step notes for registering the Microsoft
Entra and Google Cloud OAuth clients.

```bash
cp exports.example exports
```

Then edit `exports`. The app reads it automatically at start-up (use
`--exports PATH` for a different file). You can also `source exports` in your
shell; variables already set in the environment take precedence over the file.

**Microsoft 365 needs no setup.** Leave `MS_CLIENT_ID` blank and the app signs
you in with Microsoft's built-in public client (the same "Microsoft Graph
Command Line Tools" client the official Graph CLI uses). You log in as a normal
user in the browser window and the app captures the tokens — no app
registration. Some organizations restrict this client; if the first login shows
"Need admin approval", a tenant admin must approve it or you register your own
app and set `MS_CLIENT_ID`.

**Google does require a one-time OAuth client** (a free "Desktop app" client in
the Google Cloud console); there is no shareable public client for Gmail. The
steps are in [`exports.example`](exports.example).

| Variable | Default | Purpose |
| --- | --- | --- |
| `MS_CLIENT_ID` | built-in public client | Set only to use your own Entra app instead |
| `MS_TENANT` | `common` | `common`, `organizations`, `consumers` or a tenant id |
| `MS_CLIENT_SECRET` | – | Only for confidential (web) app registrations |
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | – | Google "Desktop app" OAuth client |
| `OAUTH_REDIRECT_PORT` | `8765` | Loopback port in the registered redirect URI |
| `AUTH_TIMEOUT_SECONDS` | `300` | How long to wait for a browser login |
| `PLAYWRIGHT_BROWSER_CHANNEL` | bundled Chromium | e.g. `chrome` or `msedge` |
| `MCP_HOST` / `MCP_PORT` | `127.0.0.1` / `8750` | MCP server bind address |
| `MCP_AUTH_TOKEN` | – | Optional bearer token required by the MCP server |
| `POLL_INTERVAL_SECONDS` | `300` | Background new-mail check interval (min 30) |
| `EMAIL_MCP_DATA_DIR` | `~/.local/share/email_mcp` | Tokens, browser profiles, log file |
| `LOG_LEVEL` | `INFO` | Log verbosity |

The same OAuth client is used for every account of that provider, which is how
you can add several M365 or Google accounts. For multiple M365 tenants, register
the Entra app as multi-tenant and keep `MS_TENANT=common` (or `organizations`);
each tenant's admin may need to consent to the app.

## Running

```bash
python -m email_mcp
```

- **Add account** (`a`): pick Microsoft 365 or Google, give the account a label
  (e.g. `work`, `client-co`), then sign in in the browser window that opens. The
  window closes by itself once the tokens are captured. Repeat for as many
  accounts as you like, of either type.
  - For Microsoft 365 you also choose a **sign-in method**:
    - **OAuth** (default): normal token-based sign-in. Best when your tenant lets
      users consent to apps.
    - **Browser session**: for tenants that block app consent entirely (the
      sign-in shows "Approval required" / "Need admin approval" even for
      Microsoft's own tools). You just sign in to Outlook/Office on the web as a
      normal user — no app consent, no admin approval — and the app rides that
      signed-in session, refreshing it headlessly as needed. It captures a
      separate token from Outlook (mail/calendar) and office.com (OneDrive/
      SharePoint) and uses whichever has the scope a request needs. The log
      prints what the session grants, e.g.
      `browser session grants: mail=yes calendar=yes files=yes send=no`.
      The session also needs an occasional re-sign-in (press `r`). Accounts in
      this mode show as `m365·b` in the status panel.
    - **Mail on browser-session accounts:** some tenants hand out mail access
      only to Microsoft's own internal apps, not the public Graph API (the log
      shows `mail=no`). For those, mail is read by **scraping Outlook on the
      web** — the app opens your signed-in Outlook inbox and reads the message
      list it loads. This is **read-only** (listing and previews; `send_email`,
      `reply_to_email` and `mark_read` aren't available) and best-effort: it
      relies on Outlook's internal page data, so it can break if Microsoft
      changes Outlook. Reading full message bodies falls back to the preview;
      open the message in Outlook for the whole thing.
- **Re-authenticate** (`r`): when a refresh fails (password change, revoked
  consent, expired refresh token) the account turns `needs_reauth` and the app
  pops up a prompt offering to open the login browser. You can postpone it and
  use `r` later. Each account keeps its own browser profile, so re-logins
  usually only need a click.
- **Check mail now** (`c`), **pause/resume polling** (`p`), **set poll interval**
  (`i`), **MCP connection info** (`m`), **remove account** (`d`), **quit** (`q`).
- Arrow keys/Enter also work; PgUp/PgDn scroll the log, End jumps to the latest.

To run only the MCP server and poller without the UI (for example as a service
once your accounts are set up):

```bash
python -m email_mcp --headless
```

In headless mode accounts that need re-authentication are logged; start the
TUI to log in again.

## Connecting Claude

The MCP server listens while the app is running at
`http://127.0.0.1:8750/mcp` (streamable HTTP). Add it to Claude Code:

```bash
claude mcp add --transport http email-mcp http://127.0.0.1:8750/mcp
```

If you set `MCP_AUTH_TOKEN`, pass it as a header:

```bash
claude mcp add --transport http email-mcp http://127.0.0.1:8750/mcp --header "Authorization: Bearer $MCP_AUTH_TOKEN"
```

For Claude Desktop or other clients, point an HTTP MCP connection at the same URL.

### Tools

| Tool | What it does |
| --- | --- |
| `list_accounts` | Accounts with provider, email, auth state, unread count |
| `list_messages` | Recent inbox mail across all accounts (or one); `unread_only`, `query` (Gmail search / Microsoft KQL), `limit` |
| `get_message` | Full plain-text body, headers and attachment list |
| `send_email` | Send plain-text mail from a chosen account (to/cc/bcc) |
| `reply_to_email` | Reply or reply-all to a message |
| `mark_read` | Mark a message read or unread |
| `check_new_mail` | Poll now and return mail that arrived since the previous check |
| `list_events` | Calendar events across accounts for a date range |
| `create_event` | Create a calendar event (with optional attendees/invitations) |
| `list_drives` | OneDrive(s) available to each Microsoft 365 account |
| `list_sharepoint_sites` | SharePoint sites and their shared document libraries |
| `list_files` | Browse a OneDrive / library folder (or files shared with you) |
| `search_files` | Search file names and contents in OneDrive / a library |
| `read_file` | Read a file's text (text and Word `.docx`; others give a download URL) |

The file tools (OneDrive and SharePoint document libraries) are **read-only** and
**Microsoft 365 only**; Google accounts are skipped. `list_drives`,
`list_sharepoint_sites`, `read_file` and friends return a `drive_id`/`item_id`
pair per file — pass the same `drive_id` and `account` back to read it. Use
`drive_id="shared"` in `list_files` for files others have shared with you.

**No admin approval needed.** The Graph scopes for files (`Files.Read.All`,
`Sites.Read.All`) require admin consent in many tenants, so by default the app
does **not** request them at sign-in. Instead, file tools reuse your own
signed-in browser session (per account, headless) to obtain a short-lived Graph
token the Microsoft web apps already use — the same access you have in your
browser, with no admin approval and no extra consent. If your tenant does allow
users to consent to those scopes, you can set `MS_EXTRA_SCOPES="Files.Read.All
Sites.Read.All"` in `exports` to use Graph directly instead.

`account` arguments accept the account id, label or email address. Results
from multi-account tools are tagged with `account_id`/`account` and include a
per-account `errors` list, so one broken account never hides the others.

## Security notes

- Tokens are stored in `EMAIL_MCP_DATA_DIR/accounts.json` with mode `600`
  (directory `700`), outside the repo by default.
- The MCP server binds to `127.0.0.1` by default. Anyone who can reach it can
  read and send mail as you, so set `MCP_AUTH_TOKEN` if you change `MCP_HOST`
  or share the machine.
- `exports` and `.claude/` are git-ignored; never commit real client secrets.

## Troubleshooting

- **Google says "This browser or app may not be secure"**: set
  `PLAYWRIGHT_BROWSER_CHANNEL=chrome` (requires Google Chrome installed) so a
  regular Chrome build is used for the login.
- **`AADSTS50011` redirect URI mismatch**: register exactly
  `http://localhost:<OAUTH_REDIRECT_PORT>/` under "Mobile and desktop
  applications" in the Entra app.
- **`AADSTS7000218` / client secret required**: enable "Allow public client
  flows" in the Entra app's Authentication page, or set `MS_CLIENT_SECRET`.
- **File tools report the browser session expired**: the saved session that
  backs OneDrive/SharePoint access timed out. Press `r` in the app to
  re-authenticate the account, which refreshes the browser session too.
  SharePoint shared libraries require a work/school account; personal Microsoft
  accounts have OneDrive only.
- **Google refresh tokens expire after 7 days**: that happens while the OAuth
  consent screen is in "Testing"; publish the app (it can stay unverified for
  personal use) to get long-lived tokens.
- Logs are also written to `EMAIL_MCP_DATA_DIR/email_mcp.log`.

## Development

```bash
pip install -r requirements-dev.txt
```

```bash
python -m pytest
```