gptmail

v0.2.0 Email automation for gptme agents with shared communication utilities packages/gptmail View on GitHub

gptmail

Email and agent-to-agent messaging for autonomous AI agents. gptmail gives a gptme agent (or any agent that can run shell commands) a mailbox it can read, reply to, and keep track of: real email over your existing mail setup (mbsync + msmtp), plus email-free messaging between agent workspaces over SSH. Every message is a plain Markdown file in the agent's git workspace, so the agent can read it with ordinary file tools and you can review it in a diff.

Status: beta (Development Status :: 4 - Beta). The email commands and gptmail agent messaging are used daily by long-running gptme agents. The background watcher (gptmail.watcher) is experimental — see Running unattended.

Contents

Why gptmail

An agent that runs for weeks needs to talk to people and other agents, and it has to answer every message exactly once, even across restarts and parallel sessions. gptmail handles that:

Bring your own. gptmail is one well-integrated option, not a requirement. gptme agents work fine with any email client, chat bridge or message bus. Related alternatives in this repo:

Pairs with gptodo. gptodo is the task tracker from the same agent stack. A typical agent uses gptodo for "what should I work on" and gptmail for "who am I talking to and what do I owe them".

Install

The package name is gptmail. It installs one console script, gptmail, and requires Python 3.10 or newer.

# As a standalone CLI tool, from the git repo subdirectory
uv tool install "git+https://github.com/gptme/gptme-contrib#subdirectory=packages/gptmail"
# or
pipx install "git+https://github.com/gptme/gptme-contrib#subdirectory=packages/gptmail"

# Inside a gptme-contrib checkout (gptmail is a uv workspace member)
uv sync

# From an agent workspace that vendors gptme-contrib as a git submodule
uv pip install -e gptme-contrib/packages/gptmail

Optional extra: gptmail[oauth] adds Flask/Werkzeug/python-dotenv for the OAuth callback server in communication_utils.auth. The Twitter script uses it; plain email does not.

Outbound secret scanner (needed by gptmail agent send). Inter-agent sends run the scanner and fail closed when it is missing — nothing is delivered. The scanner is the gptme-redact distribution (import name redact), exposed as gptmail[secrets]. Until gptme-redact is on PyPI, install it from git alongside the CLI:

uv tool install --force \
  "gptmail @ git+https://github.com/gptme/gptme-contrib.git#subdirectory=packages/gptmail" \
  --with "gptme-redact @ git+https://github.com/gptme/gptme-contrib.git#subdirectory=packages/gptme-redact"

A later uv tool install/uv tool upgrade without that --with drops it again. gptmail agent doctor reports whether the scanner is importable, so the failure shows up as a check rather than as a mysteriously blocked send.

Do not add a bare redact dependency. PyPI redact 0.1.1 is an unrelated config-template renderer (Feng Zhou): installing it would satisfy the name and then fail the import.

External tools. Email delivery shells out to msmtp. Fetching mail is done by mbsync (isync), which writes a local Maildir that gptmail sync-maildir imports. gptmail agent needs git, ssh and scp.

Note: run gptmail from inside the agent's git workspace. It finds the workspace with git rev-parse --show-toplevel, keeps all mail under it, and loads <workspace>/.env at startup. Variables already set in the environment take precedence over .env.

Quickstart: email

cd ~/my-agent                                    # the agent's git workspace
mkdir -p email/{inbox,sent,archive,drafts,filters}

cat >> .env <<'EOF'
AGENT_EMAIL=agent@example.com
AGENT_EMAIL_NAME=My Agent
# who the agent may send to
EMAIL_SEND_ALLOWLIST=you@example.com
# whose mail it should answer (comments must be on their own line)
EMAIL_ALLOWLIST=you@example.com
EOF

# Write and send a message (send goes through msmtp)
gptmail compose you@example.com "Hello" "First message from your agent."
#   -> Created draft: <uuid>
gptmail send "<uuid>"

# Fetch and import incoming mail, then see what needs an answer
mbsync -a
gptmail sync-maildir                             # imports inbox + sent
gptmail check-unreplied                          # exits 1 if anything is unreplied

# Answer a message (threads correctly and quotes the original), then send it
gptmail reply "<message-id>" "Thanks, on it."
gptmail send "<reply-draft-id>"

# Or mark a message as handled without replying
gptmail mark-no-reply "<message-id>" --reason "informational"

The five folders under email/ must exist; gptmail refuses to start without them. Leave EMAIL_SEND_ALLOWLIST unset and send only allows the agent's own address and built-in example.com placeholder addresses. Everything else is refused.

Quickstart: agent-to-agent messaging

Each agent workspace gets a messages/ directory with an inbox/ and an outbox/. send writes the message to your outbox and copies it into the recipient's remote inbox with scp.

  1. Create a registry in each workspace at messages/agents.yaml:

    alice:
      ssh: alice@alice-host        # any ssh target; ~/.ssh/config aliases work
      workspace: /srv/alice        # remote workspace root; mail lands in <workspace>/messages/inbox/
    bob:
      ssh: bob@bob-host
      workspace: /srv/bob
    dana:
      delivery: pull-only          # e.g. a human on a laptop with no inbound SSH
    
  2. Send, read and reply:

    export AGENT_NAME=alice                       # defaults to $USER
    gptmail agent status                          # self, registry, inbox/outbox/pending counts
    gptmail agent send bob "Deploy done" "v1.2 is live."
    echo "long body" | gptmail agent send bob "Report"   # body from stdin
    gptmail agent list                            # unread inbox messages (* = unread)
    gptmail agent read <file.md> --thread         # marks it read
    gptmail agent reply <file.md> "Thanks!"       # threaded via in_reply_to, marks original replied
    gptmail agent pending                         # what you still owe a reply to
    

If delivery fails, send exits non-zero and the outbox copy is stamped delivered: false.

Waiting for the reply. send prints the message ID and the command that waits for its reply. --watch runs that wait in the same call. Background the command from an agent harness and its completion delivers the reply ID to the sending session:

gptmail agent send bob "Release check" "Is v1.2 ok?" --watch --timeout 2h
# stdout ends with the reply ID; then: gptmail agent read <id>
gptmail agent watch --thread <message-id> --once --pull --timeout 2h

watch --thread fires only on a message whose in_reply_to chain reaches the given ID, so a direct reply or a reply to a reply counts. Unrelated messages from the same agent are ignored. A reply that already exists fires immediately. Replies pushed into the local inbox are matched as well. Push and pull publish complete files atomically; read/reply metadata updates retain the receiver-local arrival time used for the final deadline scan. Delivery resets filesystem mtime on the receiving host; incoming YAML arrival fields are not trusted. The timestamp is sampled immediately before atomic publication, not atomically with it: suspension between stamping and linking can make a post-deadline publication count as timely. The timeout bounds waiting and network operations; it is not a strict publication-order guarantee across paused processes. SSH push publication requires python3 on the peer (no remote gptmail installation or GNU coreutils is required). On timeout the command exits 124.

Pull-only recipients. A recipient that cannot accept inbound SSH (for example a person on a laptop) is marked delivery: pull-only. Messages to it stay in the sender's outbox, and the recipient fetches them:

gptmail agent pull --as dana                   # fetch messages addressed to dana from every SSH-reachable agent
gptmail agent pending --as dana                # which of those still need a reply
gptmail agent watch --once --pull              # block until a new message arrives, then pull it

pull, watch and pending --fleet run uv run gptmail agent pending --for <you> --json on each remote agent over SSH. Each remote workspace therefore needs gptmail available through uv run.

Receive-only recipients. The default push runs mkdir, scp and a remote cleanup command, so a sender needs an ordinary login — and the recipient cannot pin that login to one command. delivery: receive-only replaces the whole push with a single ssh invocation that streams the message into a receiver on stdin:

ssh recipient 'gptmail agent receive'  < message.md   # what `send` runs, nothing else

On the recipient, pin each sender's key to that one command. restrict disables port forwarding, agent forwarding, PTYs and ~/.ssh/rc, so the key can do nothing but deliver mail; --expect-sender binds the key to a specific agent so a leaked key cannot post as a different one:

# ~/.ssh/authorized_keys on the recipient (deployment is the recipient operator's)
command="gptmail agent receive --workspace /srv/bob --expect-sender alice",restrict ssh-ed25519 AAAA... alice

Replace /srv/bob with the recipient's absolute workspace path. SSH starts in its login home, not necessarily the workspace; --workspace avoids cwd and git discovery entirely. The sender still requests only gptmail agent receive: sshd supplies the workspace and sender binding from the forced command, never from client-requested arguments.

Register the peer on the sender side. Only ssh is required: the receiver chooses its own inbox, so the sender never needs to know (or write) a remote path. Add receive_command when gptmail needs uv run or an absolute executable path (e.g. /home/bob/.local/bin/gptmail agent receive). Requests accept those two receive forms, with optional absolute paths for uv and gptmail; arbitrary wrapper names and shell expressions are refused. The forced command can still use an operator-owned wrapper independently of the client's request:

bob:
  ssh: bob@bob-host
  delivery: receive-only
  # receive_command: uv run gptmail agent receive   # when the receiver uses uv

What the receiver enforces (see transport/receive.py): one bounded message (4 MiB by default), valid frontmatter without YAML aliases (including optional fields and merge keys, to prevent expansion in later mailbox readers), a plain sender token, a body, an optional sender binding and an addressee check, then an atomic no-clobber publication with a filename derived from the validated fields — never from a client-supplied path. The addressee check compares To against the agent name (AGENT_NAME, falling back to the login name); when those differ, set AGENT_NAME in the forced command (command="AGENT_NAME=bob gptmail agent receive --workspace /srv/bob --expect-sender alice",restrict). A client-requested command other than the receive verb is refused, so ssh recipient 'ls' fails with receive-only endpoint: refused command 'ls' instead of arriving as an empty message. gptmail agent receive is also safe to run by hand for a smoke test (echo … | gptmail agent receive).

Mailbox scope. Receive-only sending currently supports the default mailbox. A named --mailbox fails delivery explicitly rather than silently placing the exchange in the default inbox. Custom receiver mailbox routes require separate operator-pinned endpoints and are not implemented by this sender.

Replies and migration. Replies already travel as ordinary messages: reply sends a message back to the original sender. New sends carry a logical message_id (the sender's outbox filename); replies use that ID, while the receiver still chooses its own safe local filename. Thread watches and ancestor reads recognize the logical ID as well as local filenames. With both directions receive-only there is nothing to pull. That is the reply-by-push migration — stop pulling from a receive-only peer; pull, watch --pull and pending --fleet skip such registry entries automatically (the forced command exposes no shell to read their outbox). Sequential push/pull redelivery recognizes a sender's logical ID and retains the existing read/replied stamps. This is not an exactly-once protocol: concurrent mixed-transport arrivals or an old sender without a logical ID can still duplicate; stop legacy polling when switching a direction to push-only delivery. Migrate one side at a time: the sender keeps working against a legacy recipient, and a migrated recipient still accepts legacy SCP pushes until you remove the old key.

Monitoring that shares the login. The forced command replaces the recipient's usable shell for that key, so every other consumer of the same login needs its own key with its own forced command, or a published file to read. In this fleet the shared-login SSH consumers are scripts/monitoring/agent-census.sh, scripts/monitoring/agent-standup-check.py (service status and journal reads), scripts/monitoring/alice-metrics-collect.sh, and scripts/monitoring/proxmox-vm-health.py. The operator owns deployment and revoking the old key; do not repoint monitoring credentials at a mail key.

How it works

Email workspace layout

<workspace>/
├── .env                      # optional; loaded at startup without overriding the environment
└── email/
    ├── inbox/  sent/  archive/  drafts/  filters/   # required (filters/ is reserved)
    ├── locks/                # reply-tracking state (email.json) + per-message processing locks
    ├── processed_state.txt
    └── .sync_state_<folder>.json   # incremental maildir import bookkeeping

Each message is one file named after its Message-ID (<id> with @ replaced by _at_, plus .md). The file holds RFC 822-style headers, a blank line, then a Markdown body. On send, gptmail renders the body to multipart/alternative (plain text + HTML) and pipes it to msmtp. A body that is already HTML is sent as-is. The file moves from drafts/ to sent/ only after delivery succeeds.

Receiving. gptmail does not speak IMAP itself. mbsync syncs your provider into a local Maildir (default ~/.local/share/mail/gmail/INBOX and .../Sent), and gptmail sync-maildir imports new messages into email/inbox and email/sent. Duplicates are skipped. export-maildir / import-maildir convert between the Markdown folders and Maildir, for example to read the agent's mail in mutt or neomutt.

What counts as "unreplied". A message in inbox/ (add -f archive to also scan the archive) is unreplied when all of these hold:

Sending a reply marks the original replied automatically.

Outbound secret gate. Before sending, send scans both the draft and the final semantic message: decoded/unfolded headers, default sender, and decoded plain/HTML alternatives after rendering, including HTML character-reference decoding and text extraction across markup. This catches literals reconstructed by header folding, RFC2047 decoding or Markdown rendering, before msmtp delivery or sent/reply state advances. Header decoding tolerates invalid encodings without changing the wire value. HTML text extraction is a conservative additional representation, not a browser/CSS visibility model. Scanner exceptions refuse with a generic error rather than printing their payloads. It uses the optional redact package if importable. A critical finding blocks the send and is logged to state/outbound-redact-blocks.jsonl. If redact is not installed, gptmail logs a warning and sends normally.

Agent messaging layout

<workspace>/messages/
├── agents.yaml               # registry: name -> {ssh, workspace}, {ssh, delivery: receive-only}, or {delivery: pull-only}
├── inbox/   outbox/          # default mailbox
├── mailboxes/<name>/{inbox,outbox}/   # optional named mailboxes (--mailbox <name>)
└── .tracking/                # shared reply-tracking state (channel "agent")

Messages are named YYYYMMDD-HHMMSS-ffffff-<sender>-<subject>.md, and that filename is the message ID. Each file has YAML frontmatter: from, to, timestamp, subject, read, mailbox, and optionally in_reply_to, reply_expected: false (set by --no-reply), replied: true and delivered: false. pending scans the files directly, so it gives the right answer on any host without shared state. Inbox messages older than the reply window (7 days by default) stop counting as pending. --include-stale shows them again.

Both transports implement the gptmail.transport.Transport protocol and share one ConversationTracker. Each tracked message records its channel ("email" or "agent").

Command reference

Run gptmail --help or gptmail <command> --help for full option details.

Email (gptmail <command>)

Command What it does
compose TO SUBJECT [CONTENT] [--from ADDR] Create a draft. No CONTENT opens $EDITOR; - reads the body from stdin (use this for large bodies).
send MESSAGE_ID Deliver a draft via msmtp (recipient must pass EMAIL_SEND_ALLOWLIST) and move it to sent/.
reply MESSAGE_ID [CONTENT] [--from ADDR] Create a threaded reply draft (In-Reply-To/References, quoted original). Accepts \n escapes; no CONTENT opens $EDITOR.
list [FOLDER] List messages in a folder (default inbox).
read MESSAGE_ID [--thread | --thread-only] Show a message, the whole thread, or just its structure.
thread MESSAGE_ID [--structure] [--stats] Show the conversation thread, its outline, or statistics.
archive MESSAGE_ID Move a message to archive/.
check-unreplied [-f FOLDER ...] List unreplied mail from allowlisted senders; exits 1 if any are found.
mark-no-reply MESSAGE_ID [--reason TEXT] Mark a message handled without replying.
list-completed [--status all|replied|no_reply_needed] Show reply-tracking history.
check-completion-status MESSAGE_ID Debug the tracker entry for one message.
process-unreplied [--dry-run] [-f FOLDER ...] Run gptme --non-interactive once per unreplied email so the agent answers it (see below).
check-complexity [--threshold N] [--mark-complex] Score unreplied mail for length, questions, sensitive keywords and decision requests; optionally mark complex mail as no-reply-needed so automatic replies skip it.
sync-maildir [FOLDER] Import from the external Maildir (default all = inbox + sent).
export-maildir FOLDER DEST / import-maildir SOURCE FOLDER Convert between Markdown folders and a Maildir (FOLDER may be all).

Agent messaging (gptmail agent <command>)

Command What it does
send TO SUBJECT [CONTENT] [--no-reply] [--force] [--mailbox NAME] Send to one agent (body from stdin if CONTENT is omitted). --no-reply marks it informational. A send whose subject already went to the same agent in the last hour is skipped (exit 0) unless --force. --watch [--timeout 2h] blocks until the threaded reply arrives.
broadcast SUBJECT [CONTENT] [--no-reply] [--mailbox NAME] Send to every agent in the registry except yourself.
list [FOLDER] [-a/--all] [--mailbox NAME | --all-mailboxes] List messages (inbox shows unread only unless --all).
read MESSAGE_ID [--thread] [--mailbox NAME] Print a message and mark it read.
reply MESSAGE_ID [CONTENT] [--mailbox NAME] Reply to the sender. Skips (exit 0) if the message is already marked replied.
ack MESSAGE_ID [--mailbox NAME] Mark an inbox message handled without replying (stamps replied: true and read: true), so it leaves pending but stays in list.
pending [--as ID] [--include-stale] [--mailbox NAME | --all-mailboxes] Inbox messages awaiting your reply.
pending --for NAME [--fleet] [--json] Messages addressed to NAME in your outbox (with --fleet, in every registered agent's outbox).
receive [--workspace PATH] [--mailbox NAME] [--expect-sender NAME] [--max-bytes N] Receive one message on stdin and publish it atomically to the inbox. The recipient side of the receive-only transport; safe to pin as a forced command (command="gptmail agent receive",restrict). Refuses a foreign client command, input over --max-bytes (default 4 MiB) or invalid frontmatter.
pull [--as ID] [--from NAME] [--json] [--dry-run] [--notify-cmd CMD] Fetch messages addressed to you from every SSH-reachable agent's outbox, or only NAME with --from. Thread watches pull only the matching sender, so unrelated offline peers cannot delay delivery. --notify-cmd runs CMD with NEW_COUNT and SUMMARY set.
watch [--to NAME] [--from A,B] [--interval SECS] [--once] [--pull] Poll agents' outboxes and print one line per new message. Works with systemd/launchd or a terminal.
status [--mailbox NAME | --all-mailboxes] Identity, registry and inbox/outbox/pending counts.
doctor Check that this install can deliver: reports whether the outbound secret scanner send requires is importable.

ChatGPT bridge (gptmail chatgpt-bridge)

A remote MCP server (HTTP/SSE) that lets a ChatGPT chat read the agent's replies. Each chat maps to its own mailbox (cgpt-<hash>), and the exposed tools (<agent-name>_status, <agent-name>_replies) are read-only. It needs the bridge extra:

uv pip install -e 'gptme-contrib/packages/gptmail[bridge]'   # or add --with to the uv tool install above
CHATGPT_BRIDGE_TOKEN=... gptmail chatgpt-bridge --host 0.0.0.0 --port 8080 \
  --messages-dir ~/my-agent/messages --agent-name myagent

Every option also reads a CHATGPT_BRIDGE_* variable (HOST, PORT, MESSAGES_DIR, AGENT_NAME, SEND_INSTRUCTIONS, TOKEN). Without a token the server only binds a loopback address; it refuses any other host.

scripts/agent-msg.py at the repo root is a compatibility shim for the older agent-msg.py command surface. It maps list --needs-reply to pending and passes every other command through to gptmail agent.

Configuration

All configuration is through environment variables or <workspace>/.env.

Variable Used by Meaning
AGENT_EMAIL email (required) The agent's address: default sender and "self" for reply filtering.
AGENT_EMAIL_NAME email Display name for the From header.
AGENT_EMAIL_ALIASES email Comma-separated extra addresses that also count as the agent.
EMAIL_SEND_ALLOWLIST send Comma-separated recipients or bare domains allowed for outbound mail; * allows all. +tag suffixes are ignored when matching. Fails closed.
EMAIL_ALLOWLIST unreplied detection Comma-separated senders or domains whose mail should be answered; * allows all senders except the agent itself.
MAILDIR_INBOX, MAILDIR_SENT sync-maildir External Maildir paths (defaults under ~/.local/share/mail/gmail/).
MAILDIR_<NAME> sync-maildir <name> Map additional folders, for example MAILDIR_ARCHIVE.
EDITOR compose, reply Editor used when no content is given (default vim).
GPTME_WORKSPACE watcher Workspace root for the background watcher.
AGENT_NAME agent This agent's name (default $USER, lowercased).
AGENT_MSG_REPLY_WINDOW_DAYS agent pending Reply window in days (default 7; 0 disables the age cutoff).
AGENT_MSG_NO_REPLY_SUBJECT_PATTERNS agent pending Newline-separated, case-insensitive regexes. Matching subjects never count as pending.

The same patterns can live in messages/no-reply-subject-patterns (one regex per line; lines that are # or start with # are comments), merged with the variable. Prefer the file: it is read by every agent pending caller, so a dispatcher or unit that does not carry the environment variable cannot disagree with the one that does.

send passes -a gmail to msmtp when the sender address contains gmail.com, and uses msmtp's default account otherwise.

Running unattended

The supported path is the CLI on a schedule (cron, a systemd timer, or the agent's own run loop):

mbsync -a && gptmail sync-maildir && gptmail process-unreplied

process-unreplied takes a per-message lock, so overlapping runs never handle the same email twice. For each unreplied email it runs gptme --no-confirm --non-interactive, with a prompt telling the agent to read the email file and then either gptmail reply + gptmail send or gptmail mark-no-reply. That prompt calls uv run python3 -m gptmail …, so the workspace must be able to run gptmail through uv. Use --dry-run to preview.

Experimental watcher. python -m gptmail.watcher runs the same cycle every 30 seconds. once runs a single cycle and one handles a single email. It currently assumes source-checkout conventions:

Set GPTME_WORKSPACE so it finds the right workspace. Prefer the scheduled CLI command above unless your setup matches these assumptions.

Credentials

Keep mail passwords out of plaintext files and out of the repo. On a server, the Unix password manager pass works well. Store the password once:

pass init "agent@example.com"          # needs a GPG key for that identity
pass insert email/agent-account

Then point mbsync and msmtp at it:

# ~/.mbsyncrc
IMAPAccount gmail
Host imap.gmail.com
User agent@gmail.com
PassCmd "pass email/agent-account"
SSLType IMAPS

# ~/.msmtprc
account gmail
host smtp.gmail.com
port 587
from agent@gmail.com
auth on
user agent@gmail.com
passwordeval "pass email/agent-account"
tls on
tls_starttls on

Python API

from gptmail.lib import AgentEmail

mail = AgentEmail("/path/to/workspace", "agent@example.com")  # or rely on AGENT_EMAIL
draft_id = mail.compose("you@example.com", "Subject", "Markdown body")
mail.send(draft_id)

for item in mail.get_unreplied_emails():          # oldest first
    print(item.sender, item.subject, item.message_id)

Transports for code that should work over either channel:

from gptmail.transport.email import EmailTransport  # wraps AgentEmail
from gptmail.transport.agent import AgentTransport  # filesystem inbox/outbox, no email imports

AgentTransport writes only local files. Delivery is a deliver(path, recipient) -> bool callback you inject; the CLI's callback uses SSH/SCP. Sending (including CLI reply and broadcast) requires the workspace redact scanner. The complete rendered message, including subject and reply metadata, is checked before its outbox file is created or delivery is called. Critical findings, missing scanner, and scanner errors refuse with a payload-free ValueError; blocked metadata is recorded under <messages_dir>/../state/outbound-redact-blocks.jsonl. This also applies to local-only outboxes, which may be synced independently. Standalone installations without that workspace scanner can still read/list messages but cannot send. This guard is defense in depth, not recipient authentication or a same-user credential boundary. Shared building blocks (rate limiting, file locks, the ConversationTracker, OAuth/token helpers, retry and structured logging) live in gptmail.communication_utils.

Development

cd packages/gptmail
make test        # pytest
make typecheck   # mypy
make format      # ruff

The tests in tests/ are the best behaviour reference. For example, test_send_recipient_allowlist.py covers the allowlist rules, and the test_agent_*_no_email_imports.py tests enforce that gptmail agent never imports the email stack. Historical design notes are in src/gptmail/DESIGN.md.