---
title: "Connect flows · Workwae"
description: "Hosted or headless sign-in for Gmail, Microsoft 365 in every cloud and any IMAP server, with your OAuth apps or ours and reconnects that keep the account."
url: https://workwae.com/features/connect
---

1. [Features](https://workwae.com/features/)
2. Connect flows

Connect flows

# Connect a mailbox in one step.

Send users to a hosted page, or keep your own interface while Workwae runs OAuth, for Gmail, every Microsoft 365 cloud and any IMAP server.

[Request early access](https://workwae.com/early-access/) [Read the connect guide](https://docs.workwae.com/guides/connect)

connect.tsconnect.py

```ts
// One link: Google, Microsoft or any IMAP mailbox
const session = await workwae.connectSessions.create({
  redirectUri: "https://app.example.com/mail/connected", // allowlisted first, under Settings
  providers: ["google", "microsoft", "imap"],
  externalRef: user.id,
  loginHint: user.email,
  state: csrfToken,
  options: { calendarEnabled: true, contactsEnabled: true },
});

return redirect(session.url);

// The browser comes back to your redirect URI
// ?status=success&account_id=<id>&state=<your state>
// ?status=error&error=access_denied&state=<your state>
```

```python
# One link: Google, Microsoft or any IMAP mailbox
session = workwae.connect_sessions.create(
    redirect_uri="https://app.example.com/mail/connected",  # allowlisted first, under Settings
    providers=["google", "microsoft", "imap"],
    external_ref=user.id,
    login_hint=user.email,
    state=csrf_token,
    options={"calendar_enabled": True, "contacts_enabled": True},
)

return redirect(session.url)

# The browser comes back to your redirect URI
# ?status=success&account_id=<id>&state=<your state>
# ?status=error&error=access_denied&state=<your state>
```

What you get

## Every way to get a mailbox connected, and the checks around it.

Browser flows return the user to a redirect URI on your allowlist, and `account.connected` announces the account to your webhooks.

### Hosted connect page

Google and Microsoft buttons and an IMAP and SMTP form, on a single-use link that can prefill the address and lasts 60 seconds to 24 hours (one hour by default).

### Headless OAuth

Your own provider picker, with Workwae handling the callback, token exchange and account.

### Refresh-token import

A [refresh token](https://workwae.com/glossary#refresh-token) from your own Google or Microsoft app connects with no user interaction.

### Your OAuth apps or ours

Use Workwae's apps or your own, which shows your name on consent and leaves you the grant; Google apps can push Gmail changes instead of being polled.

### Every Microsoft cloud

Worldwide (including GCC), [GCC High](https://workwae.com/glossary#gcc-high), [DoD](https://workwae.com/glossary#dod) and 21Vianet, with every sign-in and call in the account's own cloud.

### IMAP and SMTP

A password or XOAUTH2 sign-in, with servers found from the address and the login checked before anything is stored.

### Only the scopes you use

Calendar and contacts permissions only when enabled and in your plan, and shared mailbox permissions only when you ask.

### A redirect allowlist

Users return only to up to 50 allowlisted URIs, https except for localhost, matched on origin and path.

### A Continue page, once, in one browser

Each OAuth sign-in opens on a page naming your workspace, provider and account, whose Continue, accepted only from Workwae's origin, works once and binds that browser with an HttpOnly cookie.

### The address comes from the provider

The address is asked of the provider with the new grant, never taken from an ID token email claim another directory's administrator can set.

### No takeover of existing accounts

A link without an account id refuses a mailbox you already have (`account_exists`), and a reconnect must use the same mailbox (`account_mismatch`).

### Your API key stays on your server

The hosted page uses only its session token, rate limited per session, and credentials are sealed with keys held in Vault.

What your user sees

## Walk through the hosted connect flow.

Step through the pages your user sees, next to what your app and your webhooks receive. The screens follow the product's own wording; the workspace name, address and ids are examples.

This is the Google path. Microsoft asks for Microsoft Graph permissions in its own cloud, and IMAP replaces step 2 with a form for the mailbox password. Turn on JavaScript to switch between them.

### Pick a provider

Your server creates a session and sends the user's browser to its `url`. The page offers the sign-ins you listed in `providers`, under your workspace's name, and prefills `loginHint`.

Example Mail

Connect your mailbox

Example Mail is asking for access to your mailbox. Sign in with your email provider, or enter your email address and password.

Continue with Google

Continue with Microsoft

or use your email password

Email address ada@example.com

Continue

A sign-in is approved on your provider's page, and you can revoke it there at any time.

A password is checked with your mail servers, then stored encrypted and used only to keep this mailbox connected.

By connecting, you allow Workwae to access this account as described in our Privacy Policy. See also our Terms of Service.

The user chooses Continue with Google.

Example Mail

Connect your mailbox

Example Mail is asking for access to your mailbox. Sign in with your email provider, or enter your email address and password.

Continue with Google

Continue with Microsoft

or use your email password

Email address ada@example.com

Continue

A sign-in is approved on your provider's page, and you can revoke it there at any time.

A password is checked with your mail servers, then stored encrypted and used only to keep this mailbox connected.

By connecting, you allow Workwae to access this account as described in our Privacy Policy. See also our Terms of Service.

The user chooses Continue with Microsoft.

Example Mail

Connect your mailbox

Example Mail is asking for access to your mailbox. Sign in with your email provider, or enter your email address and password.

Continue with Google

Continue with Microsoft

or use your email password

Email address ada@example.com

Continue

A sign-in is approved on your provider's page, and you can revoke it there at any time.

A password is checked with your mail servers, then stored encrypted and used only to keep this mailbox connected.

By connecting, you allow Workwae to access this account as described in our Privacy Policy. See also our Terms of Service.

The user types an address and presses Continue. The page looks up the mail servers for it.

connect.ts

```ts
const session = await workwae.connectSessions.create({
  redirectUri: "https://app.example.com/mail/connected",
  providers: ["google", "microsoft", "imap"], // what the page offers
  externalRef: user.id, // "user_42"
  loginHint: user.email, // prefills the sign-in and the IMAP form
  state: csrfToken,
  options: { calendarEnabled: true },
});

return redirect(session.url);
```

connect.ts

```ts
const session = await workwae.connectSessions.create({
  redirectUri: "https://app.example.com/mail/connected",
  providers: ["google", "microsoft", "imap"], // what the page offers
  oauthAppIds: { microsoft: gccHighApp.id }, // your app, registered in GCC High
  externalRef: user.id, // "user_42"
  loginHint: user.email, // prefills the sign-in and the IMAP form
  state: csrfToken,
  options: { calendarEnabled: true },
});

return redirect(session.url);
```

connect.ts

```ts
const session = await workwae.connectSessions.create({
  redirectUri: "https://app.example.com/mail/connected",
  providers: ["google", "microsoft", "imap"], // what the page offers
  oauthAppIds: { microsoft: dodApp.id }, // your app, registered in DoD
  externalRef: user.id, // "user_42"
  loginHint: user.email, // prefills the sign-in and the IMAP form
  state: csrfToken,
  options: { calendarEnabled: true },
});

return redirect(session.url);
```

response

```jsonc
// session
{
  "id": "3c9d5e7f-1a2b-4c6d-8e0f-2a4b6c8d0e1f",
  "url": "https://app.workwae.com/connect/<token>",
  "expiresAt": "2026-05-04T10:30:00.000Z"
}
```

Workwae's own Microsoft app signs in only in the clouds Workwae runs one in. For GCC High and DoD, register your own app in that cloud and pass it as `oauthAppIds`.

The link works once and lasts one hour unless you set `ttlSeconds` (60 seconds to 24 hours).

### Approve accessEnter the password

The browser goes to a Continue page on Workwae's API origin, which names your workspace, the provider and the data shared. Continue works once and ties the sign-in to this browser. Then the provider asks for consent to the scopes Workwae requests.

The form looks up the servers from the address, then asks for the password. The login is checked against the servers before anything is stored.

Connect your account

Workwae, on behalf of Example Mail, asks to connect your Google mailbox. Continue only if you started this yourself.

**Workwae** asks for access to this mailbox on behalf of **Example Mail**. Workwae can do the following in it, when Example Mail's application or you ask it to:

- Email: read and search messages and attachments; send mail and manage drafts; change labels and read state; move messages to the trash. Workwae cannot permanently delete messages.
- Calendars: see your calendar list, read, create, change and cancel events, respond to invitations, and check free/busy times.

Workwae keeps an index of each message (subject, sender, recipients and a short snippet) so mail can be listed and searched. It stores message bodies and attachments, encrypted, only if Example Mail's settings keep them; stored content that has not been fetched through the API for 30 days is deleted. Example Mail receives this data through Workwae.

To revoke access, open your Google Account permissions, or ask Example Mail to disconnect the mailbox.

Continue with Google

By connecting, you allow Workwae to access this account as described in our Privacy Policy. See also our Terms of Service.

Workwae's Continue page. The only thing that leads on to Google is its button.

Google's own screen

Scopes requested

Identity

- `openid`
- `email`
- `profile`

Mail

- `https://www.googleapis.com/auth/gmail.modify`

Calendar, because the session sets `calendarEnabled`

- `https://www.googleapis.com/auth/calendar.events`
- `https://www.googleapis.com/auth/calendar.calendarlist.readonly`
- `https://www.googleapis.com/auth/calendar.freebusy`

Google writes this screen. A user can untick a permission there; Workwae then ends the sign-in with `scope_denied`.

Connect your account

Workwae, on behalf of Example Mail, asks to connect your Microsoft mailbox. Continue only if you started this yourself.

**Workwae** asks for access to this mailbox on behalf of **Example Mail**. Workwae can do the following in it, when Example Mail's application or you ask it to:

- Email: read and search messages and attachments; send mail; manage drafts, folders and flags.
- Calendars: read and write events and free/busy times, and read the mailbox time zone.

Workwae keeps an index of each message (subject, sender, recipients and a short snippet) so mail can be listed and searched. It stores message bodies and attachments, encrypted, only if Example Mail's settings keep them; stored content that has not been fetched through the API for 30 days is deleted. Example Mail receives this data through Workwae.

To revoke access, open your Microsoft account app permissions, or ask Example Mail to disconnect the mailbox.

Continue with Microsoft

By connecting, you allow Workwae to access this account as described in our Privacy Policy. See also our Terms of Service.

Workwae's Continue page, the same in every Microsoft cloud.

Microsoft's own screen

Permissions requested

Identity

- `openid`
- `email`
- `profile`
- `offline_access`
- `User.Read`

Mail

- `Mail.ReadWrite`
- `Mail.Send`

Calendar, because the session sets `calendarEnabled`

- `Calendars.ReadWrite`
- `MailboxSettings.Read`

Microsoft writes this screen. Each scope is requested against that cloud's own Graph host, shown in the authorize URL.

Microsoft's own screen

Permissions requested

Identity

- `openid`
- `email`
- `profile`
- `offline_access`
- `User.Read`

Mail

- `Mail.ReadWrite`
- `Mail.Send`

Calendar, because the session sets `calendarEnabled`

- `Calendars.ReadWrite`
- `MailboxSettings.Read`

Microsoft writes this screen. Each scope is requested against that cloud's own Graph host, shown in the authorize URL.

Example Mail

Connect your mailbox

Example Mail is asking for access to your mailbox. Sign in with your email provider, or enter your email address and password.

ada@example.comChange

Your name Optional. Shown as the sender name on mail sent from this account.

Password ••••••••••••

Server settings for example.com were found in the domain's autoconfig file.

**Server settings**

IMAP serverimap.example.com

Port993

SecuritySSL/TLS

User name ada@example.com Leave empty to sign in with the email address.

Send mail through an SMTP server

SMTP serversmtp.example.com

Port465

SecuritySSL/TLS

User name ada@example.com Leave empty to sign in with the email address.

Save a copy of sent mail to the Sent folder

Calendar and contacts (CalDAV/CardDAV)

Calendar and contacts servers for example.com were found in the domain's well-known DAV addresses.

Connect mailbox

A password is checked with your mail servers, then stored encrypted and used only to keep this mailbox connected.

By connecting, you allow Workwae to access this account as described in our Privacy Policy. See also our Terms of Service.

The same page, after Continue found the servers. Open Server settings to see what was found.

Workwae to Google

```text
https://accounts.google.com/o/oauth2/v2/auth
  ?client_id=<Workwae's Google app>
  &response_type=code
  &redirect_uri=https://api.workwae.com/connect/callback/google
  &scope=openid email profile
         https://www.googleapis.com/auth/gmail.modify
         https://www.googleapis.com/auth/calendar.events
         https://www.googleapis.com/auth/calendar.calendarlist.readonly
         https://www.googleapis.com/auth/calendar.freebusy
  &state=<single-use key>
  &code_challenge=<S256 challenge>
  &code_challenge_method=S256
  &access_type=offline
  &prompt=consent
  &include_granted_scopes=true
  &login_hint=ada@example.com
```

Workwae to Microsoft

```text
https://login.microsoftonline.com/common/oauth2/v2.0/authorize
  ?client_id=<Workwae's Microsoft app>
  &response_type=code
  &redirect_uri=https://api.workwae.com/connect/callback/microsoft
  &scope=openid email profile offline_access
         https://graph.microsoft.com/User.Read
         https://graph.microsoft.com/Mail.ReadWrite
         https://graph.microsoft.com/Mail.Send
         https://graph.microsoft.com/Calendars.ReadWrite
         https://graph.microsoft.com/MailboxSettings.Read
  &state=<single-use key>
  &code_challenge=<S256 challenge>
  &code_challenge_method=S256
  &response_mode=query
  &login_hint=ada@example.com
```

Workwae to Microsoft, GCC High

```text
https://login.microsoftonline.us/<authority>/oauth2/v2.0/authorize
  ?client_id=<your app's client id>
  &response_type=code
  &redirect_uri=https://api.workwae.com/connect/callback/microsoft
  &scope=openid email profile offline_access
         https://graph.microsoft.us/User.Read
         https://graph.microsoft.us/Mail.ReadWrite
         https://graph.microsoft.us/Mail.Send
         https://graph.microsoft.us/Calendars.ReadWrite
         https://graph.microsoft.us/MailboxSettings.Read
  &state=<single-use key>
  &code_challenge=<S256 challenge>
  &code_challenge_method=S256
  &response_mode=query
  &login_hint=ada@example.com
```

Workwae to Microsoft, DoD

```text
https://login.microsoftonline.us/<authority>/oauth2/v2.0/authorize
  ?client_id=<your app's client id>
  &response_type=code
  &redirect_uri=https://api.workwae.com/connect/callback/microsoft
  &scope=openid email profile offline_access
         https://dod-graph.microsoft.us/User.Read
         https://dod-graph.microsoft.us/Mail.ReadWrite
         https://dod-graph.microsoft.us/Mail.Send
         https://dod-graph.microsoft.us/Calendars.ReadWrite
         https://dod-graph.microsoft.us/MailboxSettings.Read
  &state=<single-use key>
  &code_challenge=<S256 challenge>
  &code_challenge_method=S256
  &response_mode=query
  &login_hint=ada@example.com
```

Google back to Workwae

```text
https://api.workwae.com/connect/callback/google
  ?code=<code>
  &state=<single-use key>
```

Microsoft back to Workwae

```text
https://api.workwae.com/connect/callback/microsoft
  ?code=<code>
  &state=<single-use key>
```

Server lookup

```jsonc
// What the page's server lookup returns
{
  "source": "autoconfig",
  "imap": { "host": "imap.example.com", "port": 993, "security": "tls", "user": "ada@example.com" },
  "smtp": { "host": "smtp.example.com", "port": 465, "security": "tls", "user": "ada@example.com" },
  "oauth": null,
  "dav": {
    "source": "well-known",
    "calendarUrl": "https://dav.example.com/",
    "contactsUrl": "https://dav.example.com/"
  }
}
```

Workwae's Google app asks for `gmail.modify` unless `mailEnabled` is off or `mailPermissions` is `read_send` or `read` (then `gmail.readonly`, plus `gmail.send` for `read_send`), never the full `https://mail.google.com/` scope. Calendar scopes are asked only because `calendarEnabled` is on and your plan includes calendars; contacts only with `contactsEnabled`.

Calendar permissions are asked only because `calendarEnabled` is on and your plan includes calendars. `Contacts.ReadWrite` needs `contactsEnabled`, and the `.Shared` mailbox permissions need `sharedMailboxesEnabled`.

The callback returns to Workwae, not to your app. Workwae takes the mailbox address from the provider with the new grant, never from an ID token claim, and refuses a mailbox you already have unless the session names its `accountId`.

The page calls Workwae with the session token, never your API key. If the address belongs to Google or Microsoft and you offered that sign-in, the form offers to sign in with it instead. A refused login shows in the form and the user can try again.

### Back in your app

The browser returns to your `redirectUri` with the outcome in the query string, which you check against your `state`. On success, `account.connected` announces the same account to your webhook endpoints.

Your page at redirectUri

The query your page reads

**status**

success

**account_id**

6f1c2a4e-8b3d-4e5f-9a7b-1c2d3e4f5a6b

**state**

csrf-token

Check state against what you sent, then keep account_id.

Your app renders this page. Workwae adds only the query string.

Your page at redirectUri

The query your page reads

**status**

error

**error**

access_denied

**state**

csrf-token

The user declined the consent screen. Nothing was connected; show your own message.

Your app renders this page. Workwae adds only the query string.

Your page at redirectUri

The query your page reads

**status**

error

**error**

scope_denied

**state**

csrf-token

The user unticked a permission the account needs. Nothing was connected; send a new link.

Your app renders this page. Workwae adds only the query string.

redirect URL

```text
https://app.example.com/mail/connected
  ?status=success
  &account_id=6f1c2a4e-8b3d-4e5f-9a7b-1c2d3e4f5a6b
  &state=csrf-token
```

redirect URL

```text
https://app.example.com/mail/connected
  ?status=error
  &error=access_denied
  &state=csrf-token
```

redirect URL

```text
https://app.example.com/mail/connected
  ?status=error
  &error=scope_denied
  &state=csrf-token
```

account.connected

```jsonc
// POST to your webhook endpoint
{
  "id": "1001",
  "type": "account.connected",
  "accountId": "6f1c2a4e-8b3d-4e5f-9a7b-1c2d3e4f5a6b",
  "createdAt": "2026-05-04T09:31:00.000Z",
  "data": {
    "email": "ada@example.com",
    "provider": "gmail",
    "cloud": null,
    "externalRef": "user_42",
    "reauthorized": false
  }
}
```

account.connected

```jsonc
// POST to your webhook endpoint
{
  "id": "1001",
  "type": "account.connected",
  "accountId": "6f1c2a4e-8b3d-4e5f-9a7b-1c2d3e4f5a6b",
  "createdAt": "2026-05-04T09:31:00.000Z",
  "data": {
    "email": "ada@example.com",
    "provider": "graph",
    "cloud": "global",
    "externalRef": "user_42",
    "reauthorized": false
  }
}
```

account.connected

```jsonc
// POST to your webhook endpoint
{
  "id": "1001",
  "type": "account.connected",
  "accountId": "6f1c2a4e-8b3d-4e5f-9a7b-1c2d3e4f5a6b",
  "createdAt": "2026-05-04T09:31:00.000Z",
  "data": {
    "email": "ada@example.com",
    "provider": "graph",
    "cloud": "gcc-high",
    "externalRef": "user_42",
    "reauthorized": false
  }
}
```

account.connected

```jsonc
// POST to your webhook endpoint
{
  "id": "1001",
  "type": "account.connected",
  "accountId": "6f1c2a4e-8b3d-4e5f-9a7b-1c2d3e4f5a6b",
  "createdAt": "2026-05-04T09:31:00.000Z",
  "data": {
    "email": "ada@example.com",
    "provider": "graph",
    "cloud": "dod",
    "externalRef": "user_42",
    "reauthorized": false
  }
}
```

account.connected

```jsonc
// POST to your webhook endpoint
{
  "id": "1001",
  "type": "account.connected",
  "accountId": "6f1c2a4e-8b3d-4e5f-9a7b-1c2d3e4f5a6b",
  "createdAt": "2026-05-04T09:31:00.000Z",
  "data": {
    "email": "ada@example.com",
    "provider": "imap",
    "cloud": null,
    "externalRef": "user_42",
    "reauthorized": false
  }
}
```

connect.ts

```jsonc
const s = await workwae.connectSessions.get({ sessionId });
// s
{
  "id": "3c9d5e7f-1a2b-4c6d-8e0f-2a4b6c8d0e1f",
  "status": "failed",
  "error": "access_denied",
  "accountId": null,
  "email": null,
  "mcpKeyId": null,
  "mcpKeySkipped": null,
  "expiresAt": "2026-05-04T10:30:00.000Z",
  "createdAt": "2026-05-04T09:30:00.000Z"
}
```

connect.ts

```jsonc
const s = await workwae.connectSessions.get({ sessionId });
// s
{
  "id": "3c9d5e7f-1a2b-4c6d-8e0f-2a4b6c8d0e1f",
  "status": "failed",
  "error": "scope_denied",
  "accountId": null,
  "email": null,
  "mcpKeyId": null,
  "mcpKeySkipped": null,
  "expiresAt": "2026-05-04T10:30:00.000Z",
  "createdAt": "2026-05-04T09:30:00.000Z"
}
```

No `account.connected` event is sent, since nothing was connected. The session records the failure.

No `account.connected` event is sent, since nothing was connected. The session records the failure.

`reauthorized` is `true` when the session named an existing `accountId` and the account took the new sign-in.

Leave out `redirectUri` and the user ends on a Workwae page instead. Read the outcome with `connectSessions.get`.

Build it

## Reconnect an account when its grant is revoked

Listen for `account.reauth_required` and send the user a reconnect link for the same account.

- The session signs in to the account's own provider, cloud, OAuth app and mail access, and the account keeps its id.
- Password accounts get the IMAP form for a new password; the stored servers stay.
- On success the account is active again and `account.connected` arrives with `reauthorized: true`.
- Headless works too: pass `accountId``account_id` to an OAuth start and the account's address becomes the sign-in hint.
- Without a redirect URI, the user ends on a Workwae confirmation page and you read the outcome from the session.

reconnect.tsreconnect.py

```ts
// In your webhook handler
if (event.known && event.type === "account.reauth_required") {
  const { url } = await workwae.connectSessions.create({
    accountId: event.accountId,
    providers: ["google", "microsoft", "imap"],
    redirectUri: "https://app.example.com/mail/connected",
    ttlSeconds: 86_400,
  });
  // e.g. "invalid_grant"
  await emailUser(event.data.externalRef, url, event.data.reason);
}

// Without a redirect URI, follow the session
const s = await workwae.connectSessions.get({ sessionId });
// s.status: "pending" | "completed" | "failed"
if (s.status === "failed") console.warn(s.error);

// Everything still waiting on a user
const { items } = await workwae.accounts.list({
  status: "reauth_required",
});
```

```python
# In your webhook handler
if not isinstance(event, UnknownEvent) and event.type == "account.reauth_required":
    link = workwae.connect_sessions.create(
        account_id=event.account_id,
        providers=["google", "microsoft", "imap"],
        redirect_uri="https://app.example.com/mail/connected",
        ttl_seconds=86_400,
    )
    # e.g. "invalid_grant"
    email_user(event.data.external_ref, link.url, event.data.reason)

# Without a redirect URI, follow the session
s = workwae.connect_sessions.get(session_id=session_id)
# s.status: "pending" | "completed" | "failed"
if s.status == "failed":
    print(s.error)

# Everything still waiting on a user
items = workwae.accounts.list(status="reauth_required").items
```

Build it

## Your own app, in a government cloud

Register your Microsoft app for its cloud once, then start headless sign-ins from your own interface.

- Register the callback `https://api.workwae.com/connect/callback/microsoft` (or `/google`) with the provider.
- `authority` is your directory id, or `common` for any directory.
- `authorizeUrl``authorize_url` is the Continue page; redirect the user's own browser to it.
- A refresh token your app already holds connects with `accounts.create`, no browser needed.
- An app cannot be deleted while accounts still use it.

gcc-high.tsgcc-high.py

```ts
const app = await workwae.oauthApps.create({
  provider: "microsoft",
  cloud: "gcc-high",
  name: "Example Mail",
  clientId: process.env.ENTRA_CLIENT_ID!,
  clientSecret: process.env.ENTRA_CLIENT_SECRET!,
  authority: process.env.ENTRA_DIRECTORY_ID!,
});

const { authorizeUrl } = await workwae.oauthAuthorizations.create({
  provider: "microsoft",
  oauthAppId: app.id,
  redirectUri: "https://app.example.com/mail/connected",
  externalRef: user.id,
  state: csrfToken,
  options: { calendarEnabled: true },
});

// Already hold a refresh token from your app?
const account = await workwae.accounts.create({
  provider: "microsoft",
  refreshToken,
  oauthAppId: app.id,
  externalRef: user.id,
});
```

```python
import os

app = workwae.oauth_apps.create(
    provider="microsoft",
    cloud="gcc-high",
    name="Example Mail",
    client_id=os.environ["ENTRA_CLIENT_ID"],
    client_secret=os.environ["ENTRA_CLIENT_SECRET"],
    authority=os.environ["ENTRA_DIRECTORY_ID"],
)

authorization = workwae.oauth_authorizations.create(
    provider="microsoft",
    oauth_app_id=app.id,
    redirect_uri="https://app.example.com/mail/connected",
    external_ref=user.id,
    state=csrf_token,
    options={"calendar_enabled": True},
)
authorization.authorize_url

# Already hold a refresh token from your app?
account = workwae.accounts.create(
    provider="microsoft",
    refresh_token=refresh_token,
    oauth_app_id=app.id,
    external_ref=user.id,
)
```

Build it

## Connect any IMAP mailbox

Look the servers up from the address, steer Google and Microsoft mailboxes to their own sign-in, and connect the rest with a password.

- `source` says where the settings came from: `provider`, `autoconfig`, `ispdb`, `srv` or `mx`.
- `oauth` names Google or Microsoft when their sign-in reaches the mailbox; prefer it over a password.
- `autodiscovery_failed` is the cue to ask the user for the servers.
- Login errors name the server that refused, so you can tell the user whether IMAP or SMTP needs another password.
- Google over IMAP needs your own Google OAuth app and `mailAccess: "imap"`; Microsoft works with either app.

imap.tsimap.py

```ts
import { isApiError } from "@workwae/sdk";

try {
  const found = await workwae.autoconfig.lookup({ email });
  // Google or Microsoft hosts it: offer that sign-in
  if (found.oauth) return offerSignIn(found.oauth);
} catch (error) {
  if (!isApiError(error, "autodiscovery_failed")) throw error;
  return askForServers(email);
}

// Servers left out: found again, then checked by logging in
const account = await workwae.imapAccounts.create({
  email,
  password: appPassword,
  externalRef: user.id,
});

// Later: the server refused the password; the user sent a new one
await workwae.imapSettings.update({
  accountId: account.id,
  password: newPassword,
});
```

```python
from workwae import APIError

try:
    found = workwae.autoconfig.lookup(email=email)
    # Google or Microsoft hosts it: offer that sign-in
    if found.oauth:
        return offer_sign_in(found.oauth)
except APIError as error:
    if error.code != "autodiscovery_failed":
        raise
    return ask_for_servers(email)

# Servers left out: found again, then checked by logging in
account = workwae.imap_accounts.create(
    email=email,
    password=app_password,
    external_ref=user.id,
)

# Later: the server refused the password; the user sent a new one
workwae.imap_settings.update(
    account_id=account.id,
    password=new_password,
)
```

Reference

## Permissions, clouds, status and errors.

**What each connection asks for**

Workwae asks for the least it needs and checks the scopes granted, since users can untick permissions on Google's consent screen.

| Connection | OAuth app | Permissions requested | Calendar and contacts |
| --- | --- | --- | --- |
| Google, Gmail API | Workwae's or yours | `gmail.modify` (read-only connections: `gmail.readonly`, plus `gmail.send` to send), plus `calendar` and `contacts` when those are on | Google Calendar and Google Contacts |
| Microsoft 365, Graph | Your own app registration per cloud, or Workwae's where we run one | `User.Read`, `Mail.ReadWrite`, `Mail.Send` (read-only connections: `Mail.Read`, plus `Mail.Send` to send); `Calendars.ReadWrite` and `MailboxSettings.Read` with calendar; `Contacts.ReadWrite` with contacts; the `.Shared` variants for shared mailboxes | Outlook calendars and contacts |
| Google over IMAP and SMTP | Yours only | `https://mail.google.com/`, which Workwae's app never asks for; through it the start is refused with `google_imap_requires_own_app` | Mail only |
| Microsoft over IMAP and SMTP | Workwae's or yours | `IMAP.AccessAsUser.All` and `SMTP.Send` on the cloud's Exchange host, plus Graph `User.Read` to read the address. The mailbox must allow IMAP and SMTP AUTH. | Mail only |
| IMAP and SMTP with a password | None | The address and password, checked by logging in to each server | [CalDAV](https://workwae.com/glossary#caldav) and [CardDAV](https://workwae.com/glossary#carddav), discovered or given |

**Microsoft clouds**

| Value | Cloud |
| --- | --- |
| `global` | Microsoft 365 worldwide, including GCC (moderate). The default. |
| `gcc-high` | US Government GCC High |
| `dod` | US Government DoD |
| `china` | Microsoft 365 operated by 21Vianet |

- Tokens do not cross clouds, so each cloud needs its own app registration: your own app registration per cloud, or Workwae's where we run one (`microsoftCloud` picks it).
- Personal Microsoft accounts (outlook.com) exist only in `global`.
- In 21Vianet, Graph has no message delta yet, so mail runs over IMAP and SMTP with Microsoft sign-in.

**IMAP server autodiscovery**

| Order | Source |
| --- | --- |
| 1 | A built-in table of known providers |
| 2 | The domain's own autoconfig file |
| 3 | The Mozilla ISPDB |
| 4 | DNS SRV records (RFC 6186 and 8314) |
| 5 | MX records: Google or Microsoft MX means that provider, with a hint to sign in with it |

- CalDAV and CardDAV are found from the provider table, `/.well-known` and DNS SRV, then resolved to the user's calendars and address books with the login.
- Every lookup and mail server connection refuses private and loopback addresses, and plaintext logins are refused.
- A stored password is never sent to a new server: changing a host or login needs the password in the same request.

**Account status**

Every account reports a `status` and a `statusReason`; you set two statuses and the platform sets two.

| Status | Set by | What it means |
| --- | --- | --- |
| `active` | You, or a successful reconnect | The account syncs and sends. |
| `paused` | You | Its sync stops until you set it back to `active`. |
| `reauth_required` | Workwae | The provider refused the grant (access revoked, a password changed, or the app restricted by an administrator), or an IMAP server refused the stored password; calls that need the grant answer `account_reauth_required`, and a reconnect or new password clears it. |
| `disabled` | Workwae | The platform stopped the account. It cannot be set through the API. |

**Why a connect can fail**

A failed attempt returns to your redirect URI with `status=error` and a code; treat an unknown code as a failure, since new ones may be added. The full list is in the [connect guide](https://docs.workwae.com/guides/connect#hosted).

| Code | Meaning |
| --- | --- |
| `access_denied` | The user declined the consent screen. |
| `scope_denied` | The user unticked a permission the account needs. |
| `account_exists` | The mailbox is already connected. Send a reconnect link for it instead. |
| `account_mismatch` | A reconnect signed in with a different mailbox than the account being reconnected. |
| `session_used`, `session_expired` | The link was already completed, or opened after it expired. |
| `missing_refresh_token` | The provider issued no refresh token. The user may need to remove the app's earlier grant first. |
| `google_imap_requires_own_app` | Google over IMAP was asked for through Workwae's app. Use your own Google OAuth app. |
| `plan_limit_accounts` | Your plan's account limit is reached. |

**Can an administrator connect a whole domain without each user signing in?**

Yes, with an organization connection: Google Workspace domain-wide delegation or a Microsoft app with [admin consent](https://workwae.com/glossary#admin-consent). See [organization connections](https://workwae.com/features/organizations).

**Can we move accounts from EmailEngine without asking users to sign in again?**

Yes, the migration copies accounts with their refresh tokens, so they keep working with the same OAuth app. See [migrating from EmailEngine](https://workwae.com/migrate/emailengine).

Early access

## Let users bring their own mailbox.

Workwae is in early access; tell us what you are building, and read the connect guide in the meantime.

[Request early access](https://workwae.com/early-access/) [Read the connect guide](https://docs.workwae.com/guides/connect)
