Setting Up a Headless Gmail-to-Maildir Sync Container on a NAS with Telegram Webhook Notifications
Handing mailbox credentials to third-party cloud automation tools creates unnecessary security exposure, yet relying on slow email digests makes it easy to miss time-sensitive replies. Mirroring your inbox to a local Maildir volume on a NAS gives local scripts and AI agents fast, offline-capable access to plain-text message files while keeping every credential inside your own network.
In this tutorial, you will stand up a headless mbsync (isync) container that syncs Gmail over TLS into a NAS Maildir directory and pairs with a Python watcher to push filtered human replies straight to Telegram. To see how I use this exact pipeline to catch real-time professional messages without keeping distracted browser tabs open, read Automating Real-Time LinkedIn Notifications to Telegram with a NAS Maildir Watcher on Frizzle Tech Blog.
Prerequisites
To deploy this stack cleanly, prepare a Linux Docker host or NAS with persistent storage, a Git repository (on GitHub, GitLab, or self-hosted GitLab) to track your container files without committing secrets, a dedicated Gmail App Password, a Telegram Bot token from @BotFather, and optionally an AI coding agent like Antigravity, Claude Code, or Codex if you want to customize sender filter rules for your own workflows.
- A Linux server or NAS running Docker Engine and the Docker Compose plugin.
- A host Maildir directory owned by UID and GID
1000(for example,/path/to/mail/gmail) and a project folder at/path/to/git/maildir-watcher. - A 16-character Gmail App Password stored in
/path/to/git/maildir-watcher/secrets/gmail_app_password.txt(chmod 600) with IMAP enabled in Gmail settings. - A Telegram bot token and your numeric
chat_idfor receiving private notifications.
Step 1: Configure Headless IMAP-to-Maildir Sync with mbsync
Maildir stores every email as an individual file inside new/ and cur/ subdirectories, eliminating database lock contention when a sync tool writes new mail at the same moment a Python script or local AI agent reads it. Create /path/to/git/maildir-watcher/mbsyncrc configured for read-only upstream safety (Sync Pull), which downloads incoming mail locally without ever deleting messages from Gmail if a local file is moved:
IMAPAccount gmail
Host imap.gmail.com
Port 993
User your-address@gmail.com
PassCmd "cat /run/secrets/gmail_app_password"
TLSType IMAPS
CertificateFile /etc/ssl/certs/ca-certificates.crt
IMAPStore gmail-remote
Account gmail
MaildirStore gmail-local
SubFolders Verbatim
Path /maildir/
Inbox /maildir/INBOX
Channel gmail-inbox
Far :gmail-remote:
Near :gmail-local:
Patterns "INBOX"
Create Near
Expunge Near
Sync Pull
SyncState *
Setting Sync Pull and Create Near ensures the container operates strictly as a one-way local mirror during initial deployment, protecting your upstream cloud mailbox from accidental deletions.
Step 2: Build the Python Maildir Parser and Telegram Alert Daemon
Standard notifications become noisy when bulk newsletters trigger the same alert as a direct reply from an actual person. Create /path/to/git/maildir-watcher/watcher.py using Python's built-in email, sqlite3, and urllib.request modules so the container needs zero external Python packages:
#!/usr/bin/env python3
import email
from email import policy
import json
import os
import pathlib
import sqlite3
import time
import urllib.request
MAILDIR_ROOT = pathlib.Path(os.environ.get("MAILDIR_PATH", "/maildir/INBOX"))
STATE_DB = pathlib.Path(os.environ.get("STATE_DB_PATH", "/state/seen_messages.db"))
BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
ALLOW_SENDERS = ("messages-noreply@linkedin.com", "inmail-hit-reply@linkedin.com")
SKIP_SUBJECT_TERMS = ("job alert", "newsletter", "people you may know", "weekly digest")
def init_db() -> sqlite3.Connection:
STATE_DB.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(STATE_DB)
conn.execute("CREATE TABLE IF NOT EXISTS seen (msg_id TEXT PRIMARY KEY, ts INTEGER)")
conn.commit()
return conn
def send_telegram(text: str) -> None:
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = json.dumps({
"chat_id": CHAT_ID,
"text": text[:3900],
"disable_web_page_preview": True,
}).encode("utf-8")
req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=15) as resp:
resp.read()
def extract_plain_snippet(msg: email.message.EmailMessage) -> str:
body = msg.get_body(preferencelist=("plain",))
if body is None:
return ""
lines = [ln.strip() for ln in body.get_content().splitlines() if ln.strip()]
return "\n".join(lines[:6])[:500]
def scan_once(conn: sqlite3.Connection) -> None:
for sub in ("new", "cur"):
folder = MAILDIR_ROOT / sub
if not folder.is_dir():
continue
for fpath in folder.iterdir():
if not fpath.is_file():
continue
raw = fpath.read_bytes()
msg = email.message_from_bytes(raw, policy=policy.default)
msg_id = (msg.get("Message-ID") or fpath.name).strip()
if conn.execute("SELECT 1 FROM seen WHERE msg_id = ?", (msg_id,)).fetchone():
continue
sender = (msg.get("From") or "").lower()
subject = (msg.get("Subject") or "(no subject)").strip()
conn.execute("INSERT INTO seen (msg_id, ts) VALUES (?, ?)", (msg_id, int(time.time())))
conn.commit()
if ALLOW_SENDERS and not any(s in sender for s in ALLOW_SENDERS):
continue
if any(term in subject.lower() for term in SKIP_SUBJECT_TERMS):
continue
snippet = extract_plain_snippet(msg)
alert = f"New Direct Message\nFrom: {msg.get('From')}\nSubject: {subject}\n\n{snippet}"
send_telegram(alert)
if __name__ == "__main__":
db = init_db()
while True:
scan_once(db)
time.sleep(15)
Recording each Message-ID inside SQLite before dispatching guarantees that moving an email between new/ and cur/ (or restarting the container) never triggers duplicate alerts.
Step 3: Package the Sync Loop and Watcher in Docker Compose
Create /path/to/git/maildir-watcher/Containerfile on Debian Bookworm Slim with isync and python3 running under UID 1000:
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
isync ca-certificates python3 \
&& rm -rf /var/lib/apt/lists/* \
&& useradd -m -u 1000 -s /bin/sh mailrunner
COPY watcher.py /usr/local/bin/watcher.py
RUN chmod +x /usr/local/bin/watcher.py
USER mailrunner
Next, create /path/to/git/maildir-watcher/docker-compose.yml running mbsync on a two-minute loop alongside the watcher service:
services:
mbsync:
build: .
container_name: maildir-sync
restart: unless-stopped
secrets:
- gmail_app_password
volumes:
- ./mbsyncrc:/home/mailrunner/.mbsyncrc:ro
- /path/to/mail/gmail:/maildir
command: >
sh -c "while true; do mbsync -c /home/mailrunner/.mbsyncrc gmail-inbox; sleep 120; done"
telegram-watcher:
build: .
container_name: maildir-telegram-watcher
restart: unless-stopped
depends_on:
- mbsync
env_file:
- .env
volumes:
- /path/to/mail/gmail:/maildir:ro
- ./state:/state
command: ["python3", "/usr/local/bin/watcher.py"]
secrets:
gmail_app_password:
file: ./secrets/gmail_app_password.txt
Notice that telegram-watcher mounts /maildir read-only (:ro), enforcing clean least-privilege separation between mail ingestion and alert parsing.
Step 4: Test End-to-End Delivery and Verify Deduplication
Populate .env with TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID, pre-seed existing emails on first launch if desired, and bring the stack up:
cd /path/to/git/maildir-watcher
mkdir -p /path/to/mail/gmail state secrets
docker compose up -d --build
docker compose logs -f mbsync telegram-watcher
Verify that /path/to/mail/gmail/INBOX/cur populates with message files and check the SQLite ledger count:
sqlite3 /path/to/git/maildir-watcher/state/seen_messages.db "SELECT COUNT(*) FROM seen;"
Temporarily add a secondary personal email address to ALLOW_SENDERS, send yourself a test message, and confirm that Telegram delivers the formatted notification right after the next mbsync cycle completes. Restart telegram-watcher (docker compose restart telegram-watcher) and verify that zero duplicate messages are re-sent.
Hardware & Gear Used in This Guide
- Homelab NAS or Linux server: Multi-bay x86-64 NAS with RAID storage hosting the persistent Maildir tree
- Container host storage: Local SSD directory holding the SQLite Message-ID deduplication state file
- Network: Wired gigabit LAN with outbound HTTPS/IMAPS (
993and443) and zero inbound port forwards - Mobile client: iOS or Android phone running Telegram with notifications scoped to your private bot channel
What You Can Do Next
- Point a local LLM triage script at
/path/to/mail/gmail/INBOX/curto extract action deadlines into daily Markdown notes offline. - Add IMAP folder rules in
mbsyncrcto archive receipts or shipping updates into dedicated subdirectories. - Read Automating Real-Time LinkedIn Notifications to Telegram with a NAS Maildir Watcher on Frizzle Tech Blog for the full story behind building this distraction-free messaging workflow.
Later,
SteveO
