Two .NET 11 CLI tools:
- MyImapDownloader archives IMAP mailboxes to local
.emlfiles with delta sync. - MyEmailSearch indexes the archive into SQLite FTS5 and searches it.
This project contains code generated by LLMs. Treat it as experimental.
- IMAP folders are opened with
FolderAccess.ReadOnly. No delete, move or flag commands exist. - Archived
.emlfiles are never overwritten or deleted. The only local deletion is cleanup of the downloader's own staging files intmp/. - The search index is derived data and can be rebuilt at any time.
Build from source:
git clone https://github.com/kusl/MyImapDownloader.git
cd MyImapDownloader
dotnet build -c Releaseglobal.json accepts .NET SDK 11.0.100-rc.3 or any newer 11.0 SDK. CI builds and releases with the latest GA SDK.
Or install the latest self-contained Linux release to /opt with wrappers in /usr/local/bin:
bash install.shinstall.sh preserves an existing appsettings.json.
myimapdownloader -s imap.example.com -u you@example.com -p "app-password" -o ~/Documents/mail/you_example_com -a| Option | Alias | Default | Description |
|---|---|---|---|
--server |
-s |
required | IMAP server |
--username |
-u |
required | Username |
--password |
-p |
$MYIMAPDOWNLOADER_PASSWORD |
Password or app password. Required unless the environment variable is set; the variable keeps the secret out of the process list |
--port |
-r |
993 |
Port (implicit TLS) |
--output |
-o |
EmailArchive |
Archive directory |
--all-folders |
-a |
false |
All selectable folders instead of INBOX only |
--start-date |
Only messages delivered after this date (yyyy-MM-dd) |
||
--end-date |
Only messages delivered before this date (yyyy-MM-dd) |
||
--verbose |
-v |
false |
Debug logging |
--help, --version |
-h |
Arguments starting with @ are passed through literally; response files are disabled.
Exit codes: 0 success, 1 failure or invalid arguments, 130 cancelled (Ctrl+C or SIGTERM; up to 30 s is allowed to flush state).
<output>/
├── index.v1.db
└── INBOX/
├── cur/
│ ├── 1702900000.abc123@mail.example.com.myhost.eml
│ └── 1702900000.abc123@mail.example.com.myhost.eml.meta.json
├── new/
└── tmp/
File names are {internal-date-unix}.{normalized-message-id}.{host}.eml. Messages are written to tmp/, flushed to disk and moved to cur/ without ever replacing an existing file. The sidecar is written the same way.
If the target name already exists with identical content (for example after a crash between the move and the index update), the existing file is adopted and a missing sidecar is restored. If the content differs, the new message is stored with a _1, _2, ... suffix on the message id.
Messages without a Message-ID header are identified by the SHA-256 of their content.
index.v1.db (SQLite, WAL):
CREATE TABLE Messages (MessageId TEXT PRIMARY KEY, Folder TEXT NOT NULL, ImportedAt TEXT NOT NULL);
CREATE TABLE SyncState (Folder TEXT PRIMARY KEY, LastUid INTEGER NOT NULL, UidValidity INTEGER NOT NULL);Sidecar .meta.json:
{
"MessageId": "abc123@mail.example.com",
"Subject": "Project Update",
"From": "alice@example.com",
"To": "bob@example.com",
"Date": "2025-12-24T10:30:00Z",
"Folder": "INBOX",
"ArchivedAt": "2025-12-24T15:45:32Z",
"HasAttachments": false
}HasAttachments is currently always false. Header fields are null when the headers cannot be parsed; the message is archived regardless.
- Read
LastUid/UidValidityfor the folder. A changedUIDVALIDITYresets the cursor to 0. - Search
UID > LastUid. - Fetch envelopes in batches of 50 and skip Message-IDs already in
Messages. - Stream each new message to disk.
- After each batch, advance
LastUidto the highest UID below the lowest failed UID in this folder run. Failed messages are retried on the next run.
A message that fails on its own (expunged, rejected by the server, local write error) is recorded as failed and the batch continues. A lost connection (I/O error, timeout, protocol error, disconnected client or closed folder) ends the attempt instead, so the session reconnects rather than failing every remaining message in the batch.
With --start-date or --end-date the run searches the whole date window instead, relies on Message-ID deduplication and leaves LastUid untouched, so a windowed run can never make a later full run skip older mail.
Session attempts are retried with exponential backoff (2 s doubling to a 5 minute cap). Each retry opens a new connection and resumes every folder from its saved LastUid. Authentication errors and cancellation are not retried.
If index.v1.db is corrupt or not a SQLite database, it and its -wal/-shm files are renamed to *.corrupt.<ticks>, a new database is created and Messages is rebuilt from all .meta.json files. SyncState restarts at 0; existing messages are skipped by Message-ID. Other errors, such as a database locked by a second running instance, are reported and never trigger recovery.
appsettings.json next to the binary; environment variables override it (Telemetry__EnableMetrics=false).
{
"Telemetry": {
"ServiceName": "MyImapDownloader",
"ServiceVersion": "1.0.0",
"MaxFileSizeMB": 25,
"EnableTracing": true,
"EnableMetrics": true,
"EnableLogging": true,
"FlushIntervalSeconds": 5,
"MetricsExportIntervalSeconds": 15
},
"Logging": {
"LogLevel": { "Default": "Information", "Microsoft": "Warning", "System": "Warning" }
}
}OpenTelemetry traces, metrics and logs are written as JSONL to the first writable directory of:
$XDG_STATE_HOME/myimapdownloader/telemetry$XDG_DATA_HOME/myimapdownloader/telemetry~/.local/state/myimapdownloader/telemetry~/.local/share/myimapdownloader/telemetry./telemetry
If none is writable, telemetry is disabled.
Files: {traces|metrics|logs}/{kind}_{yyyyMMdd}_{seq:D4}.jsonl, rotated daily and at MaxFileSizeMB. Properties are PascalCase and null values are omitted; tag and attribute values are strings.
Spans: EmailArchiveSession, DownloadEmails, ProcessFolder, ProcessEmail, SaveStream.
| Metric | Type | Unit |
|---|---|---|
emails.downloaded |
Counter | emails |
retry.attempts |
Counter | attempts |
storage.files.written |
Counter | files |
storage.bytes.written |
Counter | bytes |
storage.write.latency |
Histogram | ms |
.NET runtime metrics (the built-in System.Runtime meter) are also exported.
The archive root is expected to contain one directory per account, each holding MyImapDownloader output:
~/Documents/mail/<account>/<folder>/cur/*.eml
myemailsearch index --content
myemailsearch search "from:alice@example.com subject:report kafka"
myemailsearch search "date:2025-01-01..2025-06-30 invoice" --format json --limit 50
myemailsearch status
myemailsearch rebuild --yes --contentGlobal options, valid before or after the subcommand:
| Option | Alias | Description |
|---|---|---|
--archive |
-a |
Archive root |
--database |
-d |
Index database file |
--verbose |
-v |
Debug logging |
| Command | Options |
|---|---|
search <query> |
--limit/-l (100), --format/-f table|json|csv (anything else is rejected), --open/-o |
index |
--full/-f, --content |
status |
|
rebuild |
--yes/-y, --content |
Without --content, only subject, sender and recipients are full-text indexed; a 500-character preview is always stored.
Query syntax:
| Term | Meaning |
|---|---|
from:addr |
Exact sender, case-insensitive; * is a wildcard |
to:addr |
Recipient contains |
subject:text or subject:"two words" |
Subject contains |
date:YYYY-MM-DD or date:YYYY-MM-DD..YYYY-MM-DD |
Sent date range, end inclusive |
after:YYYY-MM-DD, before:YYYY-MM-DD |
Bounds, before inclusive |
account:name, folder:name |
Exact account or folder directory |
| remaining text | FTS5 phrase; trailing * for prefix match |
A term is only recognised at the start of a word, and quoted values may contain other terms (subject:"from:x"). The first occurrence of each term wins; repeats and invalid dates are searched as text.
Defaults:
- Archive:
$MYIMAPDOWNLOADER_ARCHIVE, then$XDG_DATA_HOME/myimapdownloader,~/.local/share/myimapdownloader,~/Documents/mail,~/mail. - Database:
$XDG_DATA_HOME/myemailsearch/search.db, else~/.local/share/myemailsearch/search.db.
Indexing is incremental by file path and modification time. rebuild drops and recreates the index tables. Indexes created by earlier versions are used as they are. Logs go to stderr, so --format json and csv output on stdout is clean. search exits 1 when no index exists.
MyImapDownloader.Core/ XDG paths, SQLite connection helper, JSONL telemetry
MyImapDownloader/
Archive/ On-disk layout: naming, maildir store, SQLite index
Imap/ Mail server port and its MailKit adapter
Sync/ Delta sync per folder, retrying session
MyEmailSearch/
Commands/ CLI commands and output formatting
Data/ SQLite FTS5 index
Indexing/ Archive scan and MIME parsing
Search/ Query parsing, search, snippets
*.Tests/ TUnit tests
Directory.Packages.props Central package versions
dotnet build
dotnet test| Package | Use |
|---|---|
| MailKit / MimeKit.Core | IMAP and MIME parsing |
| Microsoft.Data.Sqlite | SQLite and FTS5 |
| System.CommandLine | CLI parsing |
| Polly.Core | Retry |
| OpenTelemetry | Traces, metrics, logs |
| TUnit | Tests |
JSON serialization uses source-generated JsonSerializerContexts and configuration binding uses the binder source generator. The sync logic depends on IMailServer, so it is tested against an in-memory server; only MailKitMailServer talks to the network.
See docs/net11-migration.md for what changed in the .NET 11 rewrite.