Tmail: Building a Private Email System for AI Agents on Tailscale
Hook
What if your AI agents could email each other, but the emails never touched the internet? Tmail treats SMTP as an IPC mechanism, not a federated protocol, and the architecture is surprisingly clever.
Context
AI agents need to communicate. While function calling and chat APIs dominate the current landscape, they have limitations: ephemeral conversations that disappear when sessions end, no standard way to inspect message history, and minimal control over who talks to whom. Email, by contrast, offers persistent message storage, universal debugging tools, and mature client libraries in every language.
The problem is that traditional email servers assume internet delivery. They're designed for federated networks where anyone can theoretically email anyone else. For organizations running AI agents in production—research agents coordinating with coding agents, monitoring bots sending alerts to action bots—this openness is a liability. You need a private, auditable communication channel where an administrator explicitly controls relationships. Tmail solves this by building an email server that deliberately rejects all internet mail, uses Tailscale for authentication and encryption, and bridges SMTP/IMAP with the Model Context Protocol (MCP) that AI platforms like Claude understand.
Technical Insight
Tmail's architecture has three layers, each solving a specific problem. At the core is Stalwart Mail Server running in Docker, handling standard SMTP (port 465) and IMAP (port 993) protocols. Stalwart is compiled from source with JMAP support disabled to reduce attack surface. The mail server container exposes these ports only on a private Docker bridge network (172.30.240.0/28), making them invisible to the host.
The second layer is where things get interesting: a Tailscale sidecar container that acts as the sole gateway to the mail server. Tailscale provides zero-trust networking through WireGuard tunnels and handles TLS termination using MagicDNS HTTPS certificates. This means you never deal with Let's Encrypt challenges, custom certificate authorities, or distributing self-signed certs across agent nodes. The Tailscale container simply requests a cert for your hostname (like tmail.your-tailnet.ts.net), and Tailscale's infrastructure handles validation and renewal.
Here's what the Docker Compose setup looks like for the server:
services:
stalwart:
build:
context: ./stalwart
networks:
mailnet:
ipv4_address: 172.30.240.2
volumes:
- stalwart-data:/opt/stalwart-mail
environment:
- STALWART_HOSTNAME=tmail.your-tailnet.ts.net
tailscale:
image: tailscale/tailscale:latest
environment:
- TS_AUTHKEY=${TS_AUTHKEY}
- TS_HOSTNAME=tmail
- TS_EXTRA_ARGS=--advertise-tags=tag:tmail
volumes:
- tailscale-state:/var/lib/tailscale
networks:
- mailnet
ports:
- "443:443"
- "465:465"
- "993:993"
Notice that only the Tailscale container exposes ports to the host. The Stalwart container is completely isolated on the mailnet bridge network. Traffic flows like this: Tailscale peer → Tailscale container (TLS termination) → Stalwart container (plaintext on private network). This architecture uses Docker networks as security boundaries, avoiding complex firewall rules or iptables manipulation.
The third layer is the client-side MCP bridge. Each AI agent runs its own Docker stack containing a Tailscale gateway, the Himalaya CLI email client, and an event bridge for push notifications. The MCP server itself runs as a stdio-based process that shells out to docker-compose commands. This design is brilliant in its simplicity: the only host-level dependency is Docker. You don't need Python, Node.js, Rust, or any language runtime installed.
Here's a simplified version of how the MCP server implements the "send email" tool:
import subprocess
import json
def send_email(to: str, subject: str, body: str) -> dict:
# Construct email as JSON for Himalaya
email_data = {
"to": [to],
"subject": subject,
"body": {"plain": body}
}
# Shell out to docker-compose to run Himalaya
result = subprocess.run(
["docker-compose", "exec", "-T", "himalaya",
"himalaya", "send", "--json"],
input=json.dumps(email_data).encode(),
capture_output=True
)
if result.returncode != 0:
return {"error": result.stderr.decode()}
return {"success": True, "message_id": result.stdout.decode()}
The event bridge is equally clever. It runs a persistent IMAP IDLE connection inside the Docker stack and surfaces new messages as Claude Code channel events. This converts email from a pull-based protocol into a push-based RPC mechanism. When a new message arrives, the bridge posts it to Claude's SSE (Server-Sent Events) channel with durable acknowledgment tracking, ensuring agents react to incoming mail without polling.
Agent-to-agent authorization is implemented through Stalwart's key-value lookup store rather than traditional mail groups or ACLs. An administrator creates explicit lookup keys like can-email.researcher@tmail.ts.net.coder@tmail.ts.net = true. This creates a sparse adjacency matrix of allowed relationships visible in Stalwart's web UI. An agent can only email another agent if this lookup key exists. This is fundamentally different from typical email routing—it's a relationship graph where connections are explicit and auditable.
On every startup, Tmail runs an idempotent baseline script that strips Stalwart to a known-safe state. It disables user Sieve scripts, removes mailing lists, turns off remote delivery, and deletes any hooks that might have been added. This prevents configuration drift and ensures the system remains locked down even if an administrator experiments with settings.
Gotcha
Stalwart 1.0.3 lacks server-wide disk quota defaults, which is a significant operational problem. You must manually set a 1GB quota on every account creation or risk unbounded storage consumption. If an agent gets stuck in a loop sending emails to itself, it can fill your disk. This should be a configuration flag, but it isn't.
Multi-recipient SMTP delivery has partial-success semantics that break typical transactional assumptions. If you send an email to three agents and one recipient is invalid, the other two will receive the message, but you'll get a partial error response. Agents expecting atomic delivery (all recipients succeed or all fail) will be surprised by this behavior.
The event bridge only supports Claude Code's SSE channel protocol. If you're using other AI platforms like OpenAI Assistants, Langchain agents, or AutoGPT, you'll need to implement custom polling or scheduling. This fragments the agent experience—Claude agents get push notifications while everyone else must poll.
Finally, there's a privacy consideration that's easy to overlook: Tailscale uses Let's Encrypt for MagicDNS HTTPS certificates, which means your tmail hostname (like tmail.your-company.ts.net) appears in Certificate Transparency logs forever. These logs are public and searchable. You're not exposing the server itself, but you are creating a permanent record that your organization uses this infrastructure.
Verdict
Use Tmail if you're running AI agents in a production Tailscale network and need a privileged, auditable communication channel separate from chat or function calling. It excels when you want persistent, inspectable agent-to-agent conversations with explicit administrator control over who talks to whom—think research agents coordinating with coding agents across long-running tasks that span hours or days. The Tailscale coupling gives you enterprise-grade zero-trust networking and mutual TLS without certificate management headaches. Skip it if you're on a different VPN platform, need internet email federation, want agents to self-organize communication without admin intervention, or can't tolerate your infrastructure topology appearing in Certificate Transparency logs. This isn't a general-purpose email server with MCP bolted on; it's an agent IPC system that happens to speak SMTP because email clients and libraries are ubiquitous, robust, and well-understood. For teams already invested in Tailscale who need structured agent communication, Tmail is the most elegant solution available.