# Connect a Gmail account

> Connect a personal Gmail account with an app password, or with Google sign-in through your own Google OAuth client.

Source: https://docs.posternmail.app/providers/gmail/

This page connects a personal `@gmail.com` or `@googlemail.com` account. For your own domain on
Google, read [Google Workspace](https://docs.posternmail.app/providers/google-workspace/) as well. There are two ways:

| | App password (IMAP) | Sign in with Google (Gmail API) |
|---|---|---|
| Setup | 2 minutes, per account | about 15 minutes, once per Hub; then one click per account |
| You need | 2-Step Verification on the Google account | A Google Cloud project and a Hub opened over `https://` (or `localhost`) |
| The Hub uses | IMAP (`imap.gmail.com`) and SMTP (`smtp.gmail.com`) | The Gmail API |
| New mail | IMAP IDLE on the inbox, checks every 2 minutes | IMAP IDLE as a doorbell, checks every 10 seconds |
| Labels | Shown as folders | Real labels: a message can be in several at once |
| Good for | Most people | Accounts without app passwords (Advanced Protection), several Gmail accounts, a whole family |

Start with the app password if you are unsure. You can switch later: remove the mailbox and add
it again the other way.

> [!NOTE]
> Postern ships no shared Google app. Each Hub uses its own OAuth client, created by the Hub's
> admin in their own Google Cloud project. Your tokens only ever go between Google and your Hub
> (and your own devices).

## Option A: App password

### What you need

- 2-Step Verification turned on for the Google account.
- An account without Advanced Protection. Google does not offer app passwords with Advanced
  Protection, and may hide them for accounts that use only security keys. Use
  [Option B](https://docs.posternmail.app/providers/gmail/#option-b-sign-in-with-google) then.

### 1. Turn on 2-Step Verification

Open <https://myaccount.google.com/signinoptions/twosv> (Google Account → **Security** →
**2-Step Verification**) and follow the steps.

> **Check:** the **Security** page shows **2-Step Verification: On**.

> **If it did not work:** for a work or school account, your admin may have to allow 2-Step
> Verification. See [Google Workspace](https://docs.posternmail.app/providers/google-workspace/).

### 2. Create an app password

1. Open <https://myaccount.google.com/apppasswords>. Sign in again if Google asks.
2. Enter a name such as `Postern` and click **Create**.
3. Copy the 16-character password. The spaces in it do not matter.

Google's help: <https://support.google.com/accounts/answer/185833>.

> **Check:** Google shows the password in a yellow box, and the name appears in the list of app
> passwords.

> **If it did not work:** "The setting you are looking for is not available for your account"
> means 2-Step Verification is off, your account uses Advanced Protection, or your admin
> turned app passwords off. Use [Option B](https://docs.posternmail.app/providers/gmail/#option-b-sign-in-with-google).

### 3. Add the mailbox

1. In Postern open **Settings → Mailboxes → Add mailbox**.
2. Pick **Google** and type your Gmail address.
3. If your Hub has Google sign-in set up, the button says **Sign in with Google** and opens
   Google. To use the app password instead, pick **Other**, type the address and click
   **Continue**, then choose **Use a password**. Without Google sign-in on the Hub, the dialog
   goes straight to the password form.
4. Paste the app password into **App password**, optionally fill **Your name on outgoing mail**
   and click **Connect**.

> **Check:** the dialog shows **you@gmail.com is connected** and a progress bar. In
> **Settings → Mailboxes** the mailbox shows **Gmail · Downloading mail, …% done**.

> **If it did not work:** **The sign-in was rejected** means Google did not accept the app
> password: create a new one and paste it without your normal password. If Google sent you a
> "Critical security alert", confirm it was you and try again.

### Server settings

The Hub fills these in. You only need them for another app or for checking.

| | Server | Port | Security |
|---|---|---|---|
| Incoming (IMAP) | `imap.gmail.com` | 993 | TLS |
| Outgoing (SMTP) | `smtp.gmail.com` | 465 | TLS |
| Username | your full Gmail address | | |

If you change your Google password, Google revokes all app passwords. The mailbox then shows
**The sign-in no longer works**: create a new app password and use **Reconnect**.

## Option B: Sign in with Google

You, as the Hub's admin, create a small OAuth client in Google Cloud that only your Hub uses.
It stays unverified, which is fine for personal use. Then everyone on your Hub can add Gmail
accounts with **Sign in with Google**.

### What you need

- A Google account to own the Google Cloud project (any account, it does not have to be the
  mailbox).
- Your Hub opened over `https://`, or on `localhost`. Google only redirects to such addresses.
  The address does not have to be reachable from the internet: a Tailscale address such as
  `https://hub.tailnet-1234.ts.net` works. Raw IP addresses and `http://192.168.1.20` do not.
  See [Reaching your Hub](https://docs.posternmail.app/reach/) and [HTTPS](https://docs.posternmail.app/reach/https/).
- `POSTERN_PUBLIC_URL` set to that address, so the redirect address stays the same however you
  open the Hub (see [Configuration](https://docs.posternmail.app/configuration/)). Without it, the Hub uses the address
  of the request.
- Admin rights on the Hub.

Google's console moves things around from time to time. The names below match the
**Google Auth Platform** pages; Google's own guide is at
<https://developers.google.com/workspace/guides/configure-oauth-consent>.

### 1. Create a project and enable the Gmail API

1. Open <https://console.cloud.google.com/> and sign in.
2. Open the project picker at the top and click **New project**. Name it `Postern Hub`, click
   **Create**, then select the new project.
3. Open **APIs & Services → Library**, search for **Gmail API**, open it and click **Enable**.

> **Check:** **APIs & Services → Enabled APIs & services** lists **Gmail API**.

> **If it did not work:** make sure the new project is selected in the project picker. Enabling
> an API can take a minute.

### 2. Configure the consent screen

Open **Google Auth Platform** (the menu entry was called **OAuth consent screen** before). If
it asks, click **Get started**.

1. **Branding:** app name `Postern Hub`, your email as the user support email and developer
   contact. Save.
2. **Audience:** user type **External**.
3. **Audience → Publishing status:** click **Publish app** and confirm, so the status reads
   **In production**. You do not need to submit the app for verification.
4. **Data Access → Add or remove scopes:** under **Manually add scopes**, paste
   `https://mail.google.com/` and click **Add to table**, then **Update** and **Save**.

> [!WARNING]
> Do not leave the app in **Testing** with test users. In Testing, Google ends every sign-in
> after 7 days: each Gmail mailbox then shows **The sign-in no longer works** once a week.
> Google documents this at
> <https://developers.google.com/identity/protocols/oauth2#expiration>.

The Hub asks for these scopes when someone signs in:

| Scope | Why |
|---|---|
| `https://mail.google.com/` | Full Gmail access: read, label, archive, send and delete for good. Narrower scopes cannot delete permanently. It also covers the IMAP connection the Hub uses for push. |
| `openid`, `email` | To learn which Gmail address signed in. |

`openid` and `email` need no entry on the **Data Access** page.

> **Check:** **Audience** shows **Publishing status: In production**, and **Data Access**
> lists `https://mail.google.com/` under restricted scopes.

> **If it did not work:** if **Publish app** is missing, you are on a Workspace project with
> user type **Internal**; that is fine for Workspace accounts only (see
> [Google Workspace](https://docs.posternmail.app/providers/google-workspace/)).

### 3. Create the OAuth client

1. In Postern, open **Settings → Admin** and find **Sign-in with Google and Microsoft**. Under
   **Google (Gmail)**, copy the redirect URI shown in step 4 (the copy button next to it).
2. In Google Auth Platform open **Clients → Create client**.
3. **Application type:** **Web application**. **Name:** `Postern Hub`.
4. **Authorized redirect URIs → Add URI:** paste the redirect URI. It is your Hub's address
   followed by `/api/v1/oauth/callback/google`, for example:

   ```text
   https://mail.example.com/api/v1/oauth/callback/google
   ```

   It must match exactly: `https`, host, port, path, no trailing slash.
5. Click **Create**. Copy the **Client ID** and the **Client secret** (or download the JSON:
   Google may not show the secret again later).

You do not need **Authorized JavaScript origins**.

> **Check:** **Clients** lists `Postern Hub` as a web application with your redirect URI.

> **If it did not work:** if the redirect URI in Postern starts with `http://` and is not
> `localhost`, set up HTTPS first. Google rejects such URIs.

### 4. Give the client to your Hub

Either paste it in the admin panel, or set it in the Hub's configuration. A value in the
configuration wins: the admin panel then shows **Set in the Hub's configuration** and its fields
are locked.

**In the admin panel:** **Settings → Admin → Sign-in with Google and Microsoft → Google
(Gmail)**: paste the **Client ID** and the **Client secret** and click **Save**. The secret is
stored encrypted with the Hub's key.

**In the configuration:**

**Docker Compose:**
Add the two variables to `~/postern/compose.override.yaml` (create the file if it does not
exist):

```yaml
services:
  hub:
    environment:
      POSTERN_GOOGLE_CLIENT_ID: "1234567890-abc.apps.googleusercontent.com"
      POSTERN_GOOGLE_CLIENT_SECRET: "GOCSPX-your-secret"
```

Apply it:

```sh
cd ~/postern && docker compose up -d
```
**Debian and Ubuntu, Fedora and RHEL and Raspberry Pi OS:**
Add the two variables to `/etc/postern/hub.env` (the file already has them commented out):

```sh
sudo nano /etc/postern/hub.env
```

```ini
POSTERN_GOOGLE_CLIENT_ID=1234567890-abc.apps.googleusercontent.com
POSTERN_GOOGLE_CLIENT_SECRET=GOCSPX-your-secret
```

Apply it:

```sh
sudo systemctl restart postern-hub
```
**Desktop app (built-in Hub):**
The desktop app manages its Hub's configuration, so use the admin panel. The built-in Hub runs
at `http://localhost:<port>`, which Google accepts. The redirect URI shown in the admin panel
contains that port. The app keeps the same port across restarts when it is free; if it ever has
to pick another one, add the new redirect URI to the Google client as well.

> **Check:** the admin panel shows **Google (Gmail)** with the chip **Set up** (or **Set in the
> Hub's configuration**).

> **If it did not work:** **Google sign-in wasn't saved. clientSecret is required** means you
> entered only the client ID. Paste the secret as well.

### 5. Add your Gmail account

1. **Settings → Mailboxes → Add mailbox**, pick **Google**, type your Gmail address and click
   **Sign in with Google**.
2. Google warns **Google hasn't verified this app**. This is expected: it is your own app. Click
   **Advanced**, then **Go to Postern Hub (unsafe)**.
3. Allow access to your Gmail (tick the checkbox if Google shows one) and click **Continue**.
4. Google sends you back to Postern, which shows **Mailbox connected. Your mail is downloading
   now.**

On the desktop app the Google page opens in your normal browser. That browser must be signed in
to your Hub's web app with the same Postern account. On iOS and Android, tap **Open the web
app** and add the mailbox there; it then appears on the phone by itself.

> **Check:** **Settings → Mailboxes** shows the address with **Gmail · Downloading mail, …%
> done**, then **Up to date**.

> **If it did not work:** see [Troubleshooting](https://docs.posternmail.app/providers/gmail/#troubleshooting).

Repeat step 5 for each Gmail account. Everyone on the Hub uses the same client.

## What the Hub does with Gmail

### With sign in with Google (Gmail API)

- **Folders and labels.** Gmail's labels are Postern folders. Inbox, Sent, Drafts, Spam, Trash,
  Starred and Important are recognized. A message can carry several labels. Gmail's category
  tabs (Promotions, Social, ...) are not shown as folders, and archived mail without a label
  lives only in All Mail.
- **Actions.** Archive removes the Inbox label. Tags are saved as Gmail labels. Permanent
  deletion works because of the full `https://mail.google.com/` scope. Gmail has no "answered"
  flag, so that state is not synced back.
- **Threads** come from Gmail's own conversation IDs.
- **New mail.** The Hub keeps one IMAP connection to `imap.gmail.com` open and waits for news in
  the inbox (Google's Pub/Sub push would need a Hub reachable from the internet). When it rings,
  or every 10 seconds, it asks the Gmail API for changes. If IMAP is turned off for the account,
  the 10-second checks continue on their own.
- **Sending** goes through the Gmail API. Gmail files the copy in Sent itself.
- **Devices.** The desktop and mobile apps sync Gmail directly with the same OAuth client. The
  Hub hands them the refresh token and the client ID and secret.

### With an app password (IMAP)

- Gmail labels appear as IMAP folders. **All Mail**, **Important** and **Starred** are not
  synced as folders, because they repeat mail from other folders. Archive moves a message to All
  Mail.
- Threads use Gmail's thread IDs (the `X-GM-THRID` extension).
- Gmail's SMTP server saves sent mail itself, so the Hub does not add a second copy.
- New mail: IMAP IDLE on the inbox, all folders checked every 2 minutes.

## Quota

Gmail meters API use per Google account: 15,000 units per minute per user. The Hub and every
device that syncs the same mailbox draw from that same budget, because they use the same OAuth
client. Postern paces itself so it rarely hits the limit:

| Who | Share of the per-user budget |
|---|---|
| The Hub | 60 % |
| Each desktop or mobile app | 30 % |

Opening a message, sending and other things you wait for go first; the first download and
background work wait their turn. When Google still answers "rate limit exceeded", the Hub pauses
(respecting Google's Retry-After), halves its pace and slowly speeds up again. You only see
**Gmail is limiting how fast this mailbox can sync. Syncing continues by itself; nothing needs
to be done.** when the throttling lasts 15 minutes or more.

`POSTERN_GMAIL_QUOTA_SHARE` overrides the share for the process that reads it, as a fraction of
the per-user limit (for example `0.8`; values above 1 count as 1). Set it on the Hub only when
you know no device syncs the same Gmail accounts; otherwise leave it alone.

Google's quota documentation: <https://developers.google.com/gmail/api/reference/quota>.

## Limits

- An unverified OAuth client can be used by at most **100 Google accounts** over its lifetime.
  That is plenty for a household. For an organization, use
  [an Internal app in Google Workspace](https://docs.posternmail.app/providers/google-workspace/).
- Everyone sees the **Google hasn't verified this app** warning once, when they connect.
- Google sign-in is not offered when the Hub is opened over plain `http://` on a LAN address.
  The dialog then offers the app password only.
- Google sign-in needs the Hub online: an app cannot start it while the Hub is unreachable
  ("Connecting Google needs your Hub, which can't be reached right now").

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| Google shows **Error 400: redirect_uri_mismatch** | The redirect URI in the Google client is not exactly the one in the admin panel. | Copy it again from **Settings → Admin** and add it to the client. Check `POSTERN_PUBLIC_URL`, port and `https`. |
| Google shows **Access blocked: … has not completed the Google verification process** | The app is still in **Testing** and you are not a test user. | Publish it (step 2). |
| The mailbox shows **The sign-in no longer works** after about a week | The app was in Testing when you connected. | Publish it, then **Reconnect** the mailbox. |
| **This way of signing in isn't set up on your Hub.** | No Google client on the Hub, or the Hub is not on `https://` or `localhost`. | Step 4, or set up HTTPS. The Hub's message is "Google sign-in isn't set up on this Hub" or "Google sign-in needs the Hub to be reachable over HTTPS (or on localhost). Use an app password with IMAP instead, or set up HTTPS." |
| **Couldn't connect the mailbox. Google sign-in was cancelled.** | You clicked **Cancel** on Google's page. | Start again. |
| **Couldn't connect the mailbox. Google rejected the sign-in. Check the app registration and try again.** | Google refused the code exchange: wrong client secret, or the client was deleted. | Paste the client ID and secret again. |
| **Couldn't connect the mailbox. This sign-in link has expired. Please try again.** | More than 10 minutes passed, or the link was used already. | Start again. |
| **Couldn't connect the mailbox. Sign in to the Hub with the account that started adding the mailbox, then try again.** | The browser that came back from Google is signed in to the Hub as someone else, or not at all (typical on the desktop app). | Sign in to the Hub's web app in that browser with your account, then start again. |
| **Couldn't connect the mailbox. The provider didn't grant offline access. Remove the app's access in your account settings and try again.** | Google did not hand out a refresh token. | Remove **Postern Hub** at <https://myaccount.google.com/permissions> and sign in again. |
| **Couldn't reconnect the mailbox. You signed in as … , but this mailbox is ….** | You picked another Google account on Google's page. | Reconnect and pick the right account. |
| Google shows **This app is blocked** or **admin_policy_enforced** | A Workspace admin blocks the app. | See [Google Workspace](https://docs.posternmail.app/providers/google-workspace/). |
| **The sign-in was rejected** with an app password | Wrong or revoked app password. | Create a new app password. |

To disconnect, remove the mailbox in Postern, then revoke access at
<https://myaccount.google.com/permissions> (for sign in with Google) or delete the app password
at <https://myaccount.google.com/apppasswords>.
