- Go 97.9%
- Ruby 1.8%
- Dockerfile 0.1%
- Shell 0.1%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| datasource | package | from | to | | ---------- | ------------------------------------------------------- | -------- | -------- | | go | github.com/aws/aws-sdk-go-v2 | v1.48.0 | v1.48.1 | | go | github.com/aws/aws-sdk-go-v2/config | v1.33.21 | v1.33.22 | | go | github.com/aws/aws-sdk-go-v2/credentials | v1.21.3 | v1.21.4 | | go | github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager | v0.5.11 | v0.5.13 | | go | github.com/aws/aws-sdk-go-v2/service/s3 | v1.116.0 | v1.116.1 | | go | github.com/aws/smithy-go | v1.28.9 | v1.28.10 | | go | modernc.org/sqlite | v1.62.0 | v1.63.0 | Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> |
||
| .github/workflows | ||
| charts/mailvault | ||
| cmd/mailvault | ||
| deploy/proton | ||
| docs | ||
| internal | ||
| scripts | ||
| .dockerignore | ||
| .editorconfig | ||
| .gitattributes | ||
| .gitignore | ||
| .golangci.yaml | ||
| AGENTS.md | ||
| CLAUDE.md | ||
| compose.proton.yaml | ||
| config.example.yaml | ||
| config.test.yaml | ||
| Dockerfile | ||
| go.mod | ||
| go.sum | ||
| LICENSE | ||
| Makefile | ||
| README.md | ||
| renovate.json | ||
| SECURITY.md | ||
| VERSION | ||
mailvault
Back up mail from multiple sources to multiple targets.
Read mail from IMAP or POP3 accounts and back it up to Maildir, mbox, or S3-compatible storage. Each invocation runs once, reports per-source and per-target results, and exits non-zero on failure.
Supported hosts are macOS, Linux, Windows, and the BSDs covered by the platform locking implementations. Other platforms fail closed when safe locking is unavailable. Press Ctrl+C to cancel an active sync and close its resources; successful delivery receipts remain available to the next run.
development
Requires Go (see go.mod) and golangci-lint.
make build # build dist/mailvault
make lint # gofmt check and golangci-lint
make test # unit tests
commands
Every command accepts --config <path> (default: ./config.yaml, then
~/.config/mailvault/config.yaml, then /etc/mailvault/config.yaml) and
--state-dir <directory> (default: ~/.local/share/mailvault). Commands that
produce reports also accept --json.
sync [--dry-run] [--force-fetch-all] [--refresh-flags] [--since <RFC3339>] [--until <RFC3339>] [--concurrency <n>] [--max-retries <n>] [--retry-delay <duration>]: back up the configured source-target pairs.verify <target>: check one target against the recorded SHA-256 hashes.repair --source <source> --target <target> --apply: rewrite missing or corrupt copies for one pair.restore --from <target> --source <imap-source> --folder <new-folder> [--dry-run] [--allow-unverified]: restore a backup into a new IMAP mailbox;restore resolvesettles an uncertain APPEND or mailbox setup.cleanup-state --older-than <duration> [--apply]: preview or prune old fetched-message metadata.validate-config: validate the configuration and test connectivity.list-sources/list-targets: print the configured sources or targets.list-folders --source <source>: print a source's selectable folders as YAML.auth login --source <source>: authorize one configured OAuth2 source.version: print the build version.
incremental backups
IMAP syncs search for message UIDs but download bodies only for UIDs without a
successful delivery receipt for the current target. Receipts include the source,
account/server identity, folder, and UIDVALIDITY, so new targets, changed accounts,
and reset mailboxes are scanned safely. Failed deliveries remain eligible for retry.
Newly labeled or moved messages may have new folder UIDs; content deduplication
prevents writing identical bytes again by default. Maildir preserve_folders: true
scopes delivery identities by folder so duplicate content is retained in each
preserved folder.
go run ./cmd/mailvault --config ./config.yaml sync
# Download all selected messages again; existing content is still deduplicated.
go run ./cmd/mailvault --config ./config.yaml sync --force-fetch-all
Older state has no trustworthy UIDVALIDITY receipts and needs one full scan after
this upgrade. Dry runs use existing receipts but never save new ones. Date filters
still apply, including with --force-fetch-all. Folder progress totals count the
pending server-search candidates, before exact date filtering and deduplication.
POP3 uses stable UIDL identifiers to skip successful deliveries. Servers that
explicitly reject UIDL fall back to full downloads and content deduplication.
When several messages share a UIDL, Mailvault downloads those messages on each
sync and deduplicates by content. Other UIDLs still use delivery receipts.
Malformed UIDL responses fail the sync rather than guessing message identities.
POP3 date filtering uses the sender's Date header after retrieval, so excluded
messages may need to be retrieved again on later filtered runs.
IMAP folder UIDVALIDITY, UIDNEXT, and available MODSEQ values are recorded as
server observations. Download decisions use per-target receipts, not a global
high-water mark that could skip failed deliveries or holes left by date filters.
IMAP sources retry the initial connection when the server is not yet reachable:
dial failures, refused or reset connections, TLS/STARTTLS handshakes, greetings
and logins that fail at the transport level or with NO [UNAVAILABLE] back off
from 1s, doubling up to 30s, for up to connect_retry_timeout (default 3m;
0s makes a single attempt). Each retry is logged to stderr. Credential
rejections and certificate errors fail immediately. Once the budget is spent the
sync fails and exits non-zero. This covers cold Proton Bridge starts and
NetworkPolicy controllers that drop a new Pod's first packets, so Kubernetes
deployments do not need a wait-for-network init container.
max_connections bounds the IMAP connection pool; downloads stream through
bounded batches and unbuffered channels. Compact sets of delivered UIDs are excluded by the
server search, preserving holes from failures and date filters. If the exclusion
would exceed 4 KiB, the client filters the search result locally instead.
The global max_message_bytes setting defaults to 16 MiB (16777216 bytes),
accepts integers from 1 through 512 MiB, and can be overridden with
MAILVAULT_MAX_MESSAGE_BYTES. It applies to IMAP/POP3 downloads, all backup
writes and repair writes, verification reads, and restore reads and APPENDs.
Oversized messages fail the operation without advancing their delivery receipt.
IMAP checks literal sizes before allocation; POP3 checks LIST before RETR and
counts actual decoded bytes even when LIST understates the size. A rejected
stream is disconnected rather than drained. POP3 requires a valid LIST response.
The source queues are unbuffered. Behind a blocked target, IMAP retains at most
max_connections + 2 raw message buffers (workers, retry relay, and target);
POP3 retains at most three. POP3 buffer growth and target encoding can use extra
memory, so size max_connections, max_message_bytes, and deployment memory
together. Mbox framing/escaping has a separate bounded encoded-record allowance
so it can verify messages at the raw byte limit. Unterminated mbox input must
leave one byte for its final newline within that limit. Lowering the setting can make
older, larger backups unreadable until the previous limit is restored. No mailbox
messages are deleted when a limit is exceeded.
Mail server listings have per-operation limits: max_listing_items defaults to
1,000,000 entries and max_listing_bytes defaults to 67,108,864 bytes (64 MiB).
Set these on an IMAP or POP3 source to accommodate larger trusted accounts;
omitted or zero values use the defaults, and negative values are rejected.
The item limit applies to all IMAP LIST entries (including non-selectable parents),
IMAP SEARCH candidate UIDs per folder, and the POP3 STAT count and UIDL rows.
The byte limit bounds each LIST, SEARCH, STAT or UIDL response, including protocol
framing; IMAP over TLS also counts TLS framing. Small fixed protocol/TLS read
buffers can be retained across commands. POP3 UIDL listings must contain unique
message numbers and visible ASCII identifiers of at most 70 characters.
An invalid or oversized listing closes the session and fails the operation without
using partial results. Restore destination checks use the same limits before
creating or appending to a mailbox. Large accounts that exceed a limit need an
explicit increase; listings are not silently truncated or paginated.
Downloads retry transient connection failures up to two times with a short backoff. Stable IMAP UIDs and POP3 UIDLs already streamed in the current run are excluded on reconnect. POP3 stops retrying after streaming a message that has no stable UIDL because sequence numbers can change on reconnect. Authentication and protocol errors fail immediately. Ctrl+C cancels retries.
verification and restore
Use mailvault verify <target> to check backup integrity, and
mailvault repair --source <source> --target <target> --apply to recover
missing or corrupt copies while retaining originals. See the
verification and repair guide.
Use mailvault restore --from <target> --source <imap-source> --folder <new-folder>
to restore into a separate mailbox. Preview with --dry-run; resumable restore
receipts prevent replaying acknowledged uploads. See the
restore guide, including uncertain upload recovery.
delivery state upgrades
Successful deliveries are tracked separately for each configured target name.
Existing databases are upgraded automatically with a new deliveries table;
old message records are preserved, but cannot prove which targets received mail.
The first sync after this upgrade therefore conservatively delivers existing
messages again. Maildir and mbox targets may receive duplicate copies on that
first run. Subsequent syncs use per-target delivery state to skip them.
Keep target names stable; a new target name is treated as a new destination.
Receipts and integrity manifests are also bound to the configured storage
location: the canonical local Maildir/mbox path or the S3 bucket, region,
endpoint, and prefix. Changing that location makes the next sync treat it as a
new destination and write messages there, including with --force-fetch-all.
Old files and state records are retained, but receipts and manifests from before
this upgrade or from another location cannot prove what is stored at the current
location. The first sync to each location therefore scans and delivers its
messages once; Maildir and mbox may gain duplicate copies, and S3 may receive
additional objects. Later runs use that location's own receipts.
content-identity upgrade
Delivery identities now use the SHA-256 of the actual raw message bytes, not
the sender-controlled Message-ID. Different content sharing an ID is preserved;
identical raw content is deduplicated per target even if envelope metadata differs.
Legacy mid: receipts cannot prove which content was delivered and are ignored.
The first sync after this upgrade can therefore redeliver previously backed-up
mail once; Maildir and mbox may gain duplicate copies. New content-hash receipts
make subsequent runs stable. Existing hash: receipts remain usable when they
are bound to the current destination; older receipts without destination
identity are ignored as described above.
overlapping writers
Writer invocations sharing a canonical state database path serialize through
<database>.sync.lock, held through state updates and resource finalization.
Symlink aliases resolve to the same lock. Process termination releases ownership;
the empty sidecar intentionally remains. Do not delete or replace it while any
writer is running. Waiting Go callers can cancel through their context.
Dry runs do not acquire or create writer locks. Separate state databases do not
coordinate deliveries, even if they point at the same backup destination.
Do not hard-link SQLite state databases under different filenames.
Within a writable store, one SQLite connection serializes folder observations,
message metadata, and receipt access across concurrent source-target pairs.
Network fetch/delivery concurrency remains unchanged (default: five). This avoids
in-process writers consuming one another's SQLite busy timeout. Pool waiters
honor their caller context; callers that need a whole-operation deadline must
supply one. An external SQLite lock waits up to five seconds per statement and
then reports SQLITE_BUSY; queued operations can each incur that wait. The
SQLite driver may finish its busy-handler wait before returning cancellation.
There is no unbounded retry or suppression of failed state writes.
Writable file databases explicitly use journal_mode=DELETE, with foreign keys
and a 5000 ms busy timeout applied whenever a connection opens. Rollback
journaling preserves compatibility without assuming WAL shared-memory support;
WAL still permits only one writer. The state volume must support SQLite locking
and durable local-filesystem semantics. Verify the deployed storage driver and
mount before changing journal mode or sharing a state volume across hosts.
Read-only opens do not change journal mode. Persistent lock failures remain
errors and must be investigated; never delete state, clear receipts, or remove
lock files to suppress them. This strategy does not establish which process held
a previously reported production lock.
pruning old metadata
cleanup-state previews fetched-message metadata older than a requested age.
Apply pruning explicitly with --apply; delivery and incremental UID receipts
are retained in either mode.
mailvault cleanup-state --older-than 720h
mailvault cleanup-state --older-than 720h --apply
authentication and storage behavior
- Omitted source settings default to implicit TLS, a 30-second connection
timeout, and a 60-second read timeout. Explicit
use_tls: falseand zero timeouts are preserved.start_tls: trueselects STARTTLS instead of implicit TLS whenuse_tlsis omitted, for both IMAP and POP3. Indexed environment overrides apply to existing configuration entries, for exampleMAILVAULT_SOURCES_0_HOST,MAILVAULT_SOURCES_0_USE_TLS=false, andMAILVAULT_SOURCES_0_READ_TIMEOUT=60s. List overrides use comma-separated values. Invalid boolean, integer, and duration overrides fail configuration loading. - POP3 supports implicit TLS (normally port 995) and STARTTLS/STLS (normally port 110). STARTTLS failures never fall back to plaintext authentication. Both TLS flags may be false for explicitly trusted local connections; enabling both together is rejected.
- POP3 date bounds use the sender-provided Date header, which may be inaccurate
and is not the server arrival date. Missing or invalid dates fail filtered
syncs.
--sinceis inclusive and--untilis exclusive. - IMAP timestamp bounds apply to server
INTERNALDATE, not the sender's Date header:--sinceis inclusive and--untilis exclusive. Calendar searches are widened for timezone offsets, then exact bounds are applied locally. Fractional RFC3339 bounds are rounded up to preserve comparisons against second-resolution arrival dates. Bounds resolving to Unix epoch zero are rejected because the source interface reserves zero for an absent bound. MissingINTERNALDATEfails filtering rather than silently including mail. - Sources accept either
password_reforoauth2, never both. Microsoft OAuth uses device login; Google uses desktop loopback login with PKCE. Both refresh automatically and store tokens in the OS keyring by default, with an explicit private token-file option for headless hosts. See OAuth setup. No client secret is needed for these public-client flows. - Credential references support
env:NAME,file:path, andkeyring:service:account. Relative file paths resolve from the configuration file's directory. Files must be regular files of at most 64 KiB; reads remain bounded if the file grows. Linux, macOS, and BSD reject final-component symlinks, require ownership by the effective user or root, and reject group/world write permissions. Windows supports ordinary drive and UNC filesystem paths, rejects device namespaces, named pipes, alternate data streams, and final-component reparse points (including symlinks), and checks the opened disk-file handle before reading. Windows ACLs remain operator-managed; restrict credential ACLs to trusted principals. Keep parent directories trusted on all platforms: intermediate directory symlinks/reparse points are followed. Other platforms rejectfile:references; useenv:orkeyring:instead. Keyring access requires a working OS credential service. - Normal sync resolves credentials only for sources and targets referenced by
pairs. Unused secret references remain untouched; explicit
validate-configresolves all declared resources for connectivity checks. Source password files may end with one LF or CRLF, which is removed without stripping password spaces. Other embedded line breaks are rejected, including in env/literal passwords. S3 JSON credential files remain byte-preserving and can contain multiple lines. - A sync only constructs and initializes sources/targets referenced by pairs.
--dry-runfetches source messages, but does not initialize/write targets or update persistent state. Existing state is opened read-only; absent state is represented by a private in-memory database. State database paths are literal filesystem paths; characters such as?,#, and%cannot redirect the database or inject SQLite connection options. - New mbox archives use mode
0600; newly created parent directories use0700(subject to umask). Existing files and directories retain their modes. To intentionally share an archive, explicitly pre-create it and its parent directories with the desired group permissions. Members of that group can read the plaintext archived mail; review existing archive permissions when upgrading, since Mailvault does not silently tighten them. - Filesystem targets honor
create_if_missing: false: the mbox file, or all Maildir directories, must already exist. Maildir publication never replaces an existing message. Cooperating mbox writers lock the mailbox while appending and rolling back failed appends; rollback failure disables further writes through that target instance. External mbox writers must use compatible locks. - Maildir syncs newly created directories and their immediate parents during initialization; unrelated existing ancestors need only traversal permissions. It syncs the publication directory after each link before acknowledging delivery. Failed publication sync attempts are rolled back and reported as failures. Directory sync must be supported by the platform/filesystem; otherwise Maildir fails closed. Tests cover sync ordering and injected failures, not physical power loss.
Maildir folder and flag preservation
Maildir targets keep the legacy flat layout when preserve_folders and
preserve_flags are omitted or false. New configurations can enable both; the
example configuration does so explicitly. Preserved folder labels are encoded
into safe directory components under .folders, with / retaining hierarchy.
The initial IMAP system flags map to Maildir filename flags (Seen to S,
Answered to R, Flagged to F, Deleted to T, and Draft to D). This
captures flags when a message is archived. Run sync --refresh-flags to refresh
flags for previously delivered IMAP messages without downloading their bodies.
This updates Maildir filenames when preserve_flags is enabled and updates the
integrity manifest for all targets. It never deletes backups when source mail is
deleted. Older receipts without a manifest need a repair run before flag refresh.
Custom IMAP keywords are retained in the manifest for restore; Maildir filenames
map the five standard system flags. Flagged messages are published in cur/. Windows cannot represent the standard :2, filename
suffix, so set preserve_flags: false on Windows. Switching preservation modes
creates a separate receipt scope and can write new copies for the new layout;
existing backup files are retained.
Maildir access pins directory handles and rejects symlinks in the configured root,
its ancestors, tmp/, new/, cur/, and preserved-folder components. Configure a
physical path (for example /private/tmp/... instead of macOS's /tmp/... alias).
Replacing a directory during delivery fails the write; publication, rollback, and
sync stay on the opened directories. Backup reads check and read one regular-file
descriptor with the configured message byte limit, including when the file grows
during the read.
These controls address directory-entry replacement by another local writer;
manifest checksums remain necessary to detect modifications to message contents.
S3 operation limits
S3 initialization and each message upload have a five-minute total timeout,
including SDK retries and response-body reads. Set operation_timeout in the
target's config (for example, operation_timeout: "10m") for larger uploads.
The value must be positive; an earlier caller deadline still takes precedence.
S3 user metadata is independently limited to 2,048 UTF-8 key/value bytes.
Ordinary metadata remains unchanged. When it would exceed that budget, the
largest folder/UID/Message-ID/date values are replaced by <field>-sha256
metadata containing their hex digests until the budget is met. These digest
fields cannot reconstruct the original oversized values; raw RFC822 message
bytes and stable object keys are unaffected.
Backup listing limits
Backup verification, repair scans, and restore preflight enumerate targets
incrementally. Each target's config accepts max_listing_entries (default
1,000,000) and max_listing_locator_bytes (default 67,108,864 bytes, or 64 MiB).
Omitted values and zero select these bounded defaults; negative, fractional, or
out-of-range values are rejected. Set explicit larger positive integers for
larger archives after sizing available memory and temporary disk space. Exceeding
either budget fails the operation with an error; entries are never silently
truncated. Maildir counts all traversed directory entries and their relative path
bytes, including directories and ignored files; tmp contents are skipped.
Traversal and renamed-message searches use bounded streams under pinned directory
handles. Replacing a directory during enumeration fails the operation.
Mbox and S3 count message records/object keys and their locator bytes.
S3 requests pages of 128 objects and finishes consuming each page before requesting
the next. A fixed 2 MiB XML response cap also bounds endpoints that ignore the page
size; oversized pages or keys fail closed. Ordinary transient S3 failures retain
SDK retries, while listing budget failures are not retried. The configured
operation_timeout bounds total listing I/O across all page requests, including
SDK retries and decoding; consumer processing time uses the caller's context.
Enumeration order is backend-specific. Verification and repair retain hash/locator indexes bounded by
the listing budgets, while message bodies are processed one at a time. Restore
retains trusted manifest metadata and hash deduplication indexes and spools its
normalized plan (metadata only) to a private 0600 file in the system temporary
directory. It completes preflight before creating the destination mailbox, then
re-reads and re-verifies each message before APPEND. Temporary plans are removed
on normal return and errors; an abrupt process termination can leave a plan for
operator review. Trusted state database queries remain outside the target listing
budgets.
S3 credentials
Omit credentials_ref to use the standard AWS credential chain (environment,
shared profiles, workload roles, and so on). To explicitly select credentials,
set credentials_ref to an env: or file: reference resolving to a JSON object
with access_key_id and secret_access_key, plus optional session_token.
Explicit empty or malformed values fail without falling back to ambient AWS
credentials. Never commit the JSON credential object to configuration files.
S3 string options reject malformed types instead of silently selecting defaults. Ordinary object keys retain their existing format; oversized folder/UID components use a bounded identity digest. Prefixes, including their trailing slash, must leave room for the bounded object name, keeping every key within S3's 1,024-byte limit.
failure reporting
Delivery and source/target finalization failures increment TotalErrors, and
the CLI exits non-zero after printing the report. JSON Results[].Errors contains
error strings, while FinalizationErrors contains resource-specific close errors.
The engine does not print close warnings to stdout, keeping --json parseable.
An interrupted sync in JSON mode prints the available statistics before exiting
nonzero.
For Go callers, Run returns setup failures directly; delivery and finalization
failures are recorded in the returned statistics.
Resources are closed on setup failures too, including partially initialized
targets; cleanup errors are preserved alongside the original failure.
validate-config --json reports configuration validity, whether connectivity was
tested, source/target status, and error strings as one JSON document, including
failed validations. Connectivity testing still initializes targets and can create
missing destination directories/files; it does not require a state database.
license
GNU Affero General Public License v3.0.
Proton Mail with Docker Compose
For an isolated local Proton test with persistent Bridge credentials, Mailvault state, Maildir backups, and verified STARTTLS, see the Proton Compose guide.
Container publishing
The Publish GitHub Actions workflow publishes Mailvault for
linux/amd64 and linux/arm64 to ghcr.io/zekihan/mailvault and
docker.io/<DOCKER_USERNAME>/mailvault after the checks workflow passes.
Bridge uses a separate GHCR image published from the zekihan/dockerfiles repository.
Set these GitHub repository Actions secrets before the first release:
DOCKER_USERNAME: Docker Hub account name owning themailvaultrepository.DOCKER_PASSWORD: Docker Hub access token with write permission for that repository.
Create the Docker Hub repository first. GHCR authentication uses the automatic
GITHUB_TOKEN with package write permission. Set the GHCR package visibility to
public after its first publication if anonymous pulls are desired.
Pushing a stable semantic version tag such as v1.2.3 publishes the immutable
1.2.3 image to both registries and moves latest forward. Nightly and manual
runs on main update the multi-architecture edge image instead and never
replace a stable version. The image's version command includes the build version.
See Publishing for the full release process.
Kubernetes
The Helm chart provides a suspended backup CronJob, retained state and backup volumes, and an optional continuously running Proton Bridge with verified TLS and manual initialization instructions.
Version-tagged releases also publish the Helm chart to
oci://ghcr.io/zekihan/charts/mailvault after container publication succeeds.
List server folder names
List selectable folders using the source's configured credentials (including automatic OAuth token refresh):
go run ./cmd/mailvault --config ./config.yaml list-folders --source hotmail
The output is a folders: YAML block with decoded Unicode names and escaped literal characters, ready to copy into that source's configuration. Non-selectable IMAP parent folders are excluded. The command does not download messages or open backup targets. Use --json for a JSON array of names.
For an existing Kubernetes setup deployment:
kubectl -n mailvault exec deployment/mailvault-mailvault-setup -- \
mailvault --config /config/config.yaml list-folders --source hotmail
The container image must include this command; previously released images do not gain it automatically.
Publishing and manual recovery: Publishing.