SharpMailserver SHARPMAILSERVER
Chapter 11 Clients, Groupware & CLI Admin: #pApiAuth

sharpmail-cli Reference: Commands, Schema Cache, jq Queries & GitOps IaC

With sharpmail-cli, you manage domains, mailboxes, distribution lists, aliases, scoped API keys, outbound SMTP routes (incl. TLS overrides), IP warming, Reputation Shield, and DNS zones directly from your terminal or CI/CD pipelines (Ansible, GitLab CI, GitHub Actions) - with 0 ms cluster hot-reload and zero restarts.

Operational Tip & Architecture Note

Pre-installed in PATH out of the box: the Windows .msi installer (C:\Program Files\SharpMailserver\sharpmail-cli.cmd), Debian/Ubuntu .deb package (/usr/bin/sharpmail-cli), install.sh (/usr/local/bin/sharpmail-cli), and OCI image all register sharpmail-cli automatically. Always pass credentials via SHARPMAIL_API_KEY (or SHARPMAIL_TOKEN) so secrets never appear in process arguments.

1. Invocation, Environment Variables, Auth & Exit Codes

Works identically on the mail host itself or remotely from any admin workstation or CI runner over HTTPS.

Reference / Configuration
# Linux / macOS / GitLab CI / GitHub Actions:
export SHARPMAIL_URL="https://mail.firma.de"
export SHARPMAIL_API_KEY="smk_01968f2a_..."   # Alias: SHARPMAIL_TOKEN

# PowerShell (Windows Server / Admin-Workstation):
$env:SHARPMAIL_URL = "https://mail.firma.de"
$env:SHARPMAIL_API_KEY = "smk_01968f2a_..."

# Docker-Host ohne lokalen Wrapper (direkt im Container):
docker exec -i sharpmailserver sharpmail-cli describe

# Interaktive Erst-Anmeldung vor dem ersten API-Key (fragt Passwort verdeckt ab, nur ohne 2FA):
sharpmail-cli --url https://localhost --insecure -u admin@firma.de create ApiKey \
  --set label="Ansible Prod" --set role=ServerAdmin --set allowedCidrs=10.0.0.0/8 --set expiresInDays=90

# Hilfe zu jedem Unterbefehl direkt im Terminal + definierte Exit-Codes für Skripte:
sharpmail-cli --help
sharpmail-cli help create
# Exit-Codes: 0 = Erfolg · 1 = HTTP-/Auth-/Server-Fehler · 2 = Ungültige CLI-Parameter / JSON

2. Schema Discovery (describe), Filtered Queries (query) & jq Pipelines

With --json, get prints a single compact JSON object while query streams newline-delimited JSON (NDJSON) ready for jq or PowerShell.

Reference / Configuration
# Alle 12 verfügbaren Objekttypen oder die Felder eines einzelnen Typs anzeigen:
sharpmail-cli describe
sharpmail-cli describe Route
sharpmail-cli describe TransactionalSend

# Einzelnes Objekt oder globale Singleton-Konfiguration lesen:
sharpmail-cli get Domain firma.de
sharpmail-cli get SmtpQueue --json | jq '{paused: .outboundQueuePaused, tls: .outboundTlsCertValidation}'

# Gefilterte Tabellen-Abfrage mit Spaltenprojektion:
sharpmail-cli query Account --filter domain=firma.de,isActive=true --fields email,role,quotaMb,twoFactorEnabled

# NDJSON-Pipeline (Bash + jq): Alle aktiven Admin-Konten ohne 2FA auflisten:
sharpmail-cli query Account --filter isActive=true --json \
  | jq -r 'select(.role != "User" and .twoFactorEnabled == false) | "\(.email)\t\(.role)"'

# PowerShell-Pipeline auf Windows Server: Postfächer > 80 % Quota finden:
sharpmail-cli query Account --json | ForEach-Object { $_ | ConvertFrom-Json } |
  Where-Object { $_.quotaMb -gt 0 -and ($_.usedBytes / 1MB) -gt ($_.quotaMb * 0.8) } |
  Select-Object email, quotaMb, @{N="UsedMB";E={[math]::Round($_.usedBytes/1MB,1)}}

3. Creating, Patching & Deleting Objects (create, update, delete · @file.json & stdin)

Scalars, booleans, numbers, and comma-separated arrays are coerced automatically via --set key=value; pass nested JSON payloads via --data @file.json or stdin (-).

Reference / Configuration
# 1. Domain mit Dual-DKIM (RSA-2048 + Ed25519) und 10 Jahren GoBD-Aufbewahrung anlegen:
sharpmail-cli create Domain \
  --set name=firma.de \
  --set dkimSigningMode=Dual \
  --set retentionLockMode=Compliance \
  --set retentionDays=3650

# 2. Benutzerpostfach, Verteilerliste & Datenschutz-Alias anlegen:
sharpmail-cli create Account/User --set email=buchhaltung@firma.de --set displayName="Buchhaltung" --set password='...' --set quotaMb=15360
sharpmail-cli create Account/List --set email=rechnung@firma.de --set members=buchhaltung@firma.de,archiv@firma.de
sharpmail-cli create Alias --set address=info@firma.de --set target=buchhaltung@firma.de --set description="Zentrale"

# 3. Scoped API-Key für Webshop/ERP (nur /api/v1/send, feste Absenderadresse & Subnetz-Filter):
sharpmail-cli create ApiKey \
  --set label="Shopware Produktion" \
  --set role=User \
  --set senderAddress=bestellung@firma.de \
  --set defaultCategory=transactional \
  --set allowedCidrs=10.20.0.0/16,198.51.100.12/32 \
  --set expiresInDays=180

# 4. Ausgehende Route / TLS-Ausnahme für Partner-MX mit RemoteCertificateNameMismatch (Auto DNS-MX):
sharpmail-cli create Route --set domain=neff.me --set tlsMode=StartTlsIgnoreCert --set description="Shared-MX TLS Override"

# 5. IP-Warming & Reputation Shield aktivieren oder JSON per Pipe (stdin) übergeben:
sharpmail-cli update TransactionalSend --set preset=warming_28d
sharpmail-cli update ReputationShield --set preset=recommended
echo '{"junkScoreThreshold":4.2,"clamAvEnabled":true}' | sharpmail-cli update SpamGuard --data -

4. Live DNS Checks, BIND Zone Export & Declarative GitOps (snapshot & apply --dry-run)

Each line in an .ndjson plan describes an idempotent operation (upsert or delete); # and // comments are natively supported for Git code reviews.

Reference / Configuration
# Öffentliche DNS-Einträge live gegen die konfigurierten DKIM/DMARC/TLSA-Werte prüfen & als BIND-Zone speichern:
sharpmail-cli dns firma.de --live
sharpmail-cli dns firma.de --bind --output firma.de.zone

# Aktuellen Serverzustand als versionierbaren NDJSON-Plan exportieren (ohne Geheimnisse für Git):
sharpmail-cli snapshot Domain Account Alias Route TransactionalSend ReputationShield --output infra/mail-prod.ndjson

# Beispiel für deklarative Zeilen in infra/mail-prod.ndjson (inkl. Kommentaren & gezieltem Löschen):
# {"op":"upsert","type":"Domain","key":"firma.de","fields":{"name":"firma.de","dkimSigningMode":"Dual","retentionDays":3650}}
# {"op":"upsert","type":"Route","key":"neff.me","fields":{"domain":"neff.me","tlsMode":"StartTlsIgnoreCert","enabled":true}}
# {"op":"delete","type":"Alias","key":"alt-kampagne@firma.de"}

# CI/CD Pull-Request Check (verändert NICHTS in der Datenbank, Exit-Code != 0 bei Fehlern):
sharpmail-cli apply --file infra/mail-prod.ndjson --dry-run

# Nach Freigabe idempotent auf Produktion anwenden:
sharpmail-cli apply --file infra/mail-prod.ndjson

Settings, Default Values & Best Practices

Setting / Location Description Default Value Production Best Practice
Globale Flags & Umgebungsvariablen Controls server URL (--url / SHARPMAIL_URL), API key (--api-key, --token / SHARPMAIL_API_KEY, SHARPMAIL_TOKEN), Basic auth (-u/-p), JSON mode (--json), lab TLS (--insecure / -k), colors (--no-color / NO_COLOR), and HTTP trace (--debug / SHARPMAIL_DEBUG=1). URL: http://localhost Always export SHARPMAIL_URL + SHARPMAIL_API_KEY and pass --json in automation scripts; reserve --insecure (-k) strictly for local staging labs.
describe [Type] (Schema & Offline-Cache) Lists all 12 server object types or inspects every field, type, and enum variant of a specific object, caching the schema locally by X-SharpMail-Schema-Version. Lokaler XDG/AppData-Cache Run sharpmail-cli describe <Type> before scripting new policies (e.g. sharpmail-cli describe TransactionalSend); minimum role: ComplianceAuditor.
get <Type> [IdOrName] [--json] Fetches a single collection object by name, email, slug, or GUID, or reads a global singleton policy ('singleton' is inferred automatically). Kartenansicht / 1-Zeilen-JSON For singletons, omit the ID: sharpmail-cli get SpamGuard or sharpmail-cli get ReputationShield --json.
query <Type> (Alias: list) Searches collections with comma-AND filters (--filter k=v,k2=v2), column projection (--fields a,b,c), and --limit N. Emits strict NDJSON (1 JSON object per line) with --json. Tabelle / NDJSON-Stream Ideal for security audits: sharpmail-cli query Account --json | jq -r 'select(.twoFactorEnabled==false) | .email' lists accounts missing 2FA.
create <Type[/Variant]> & update <Type> (Alias: patch) Creates new collection items or patches individual fields on existing objects/singletons without clobbering untouched properties (0 ms cluster hot-reload). --set k=v · @file.json · stdin Pass scalar/array fields via --set key=value (comma-separated arrays) and complex nested policies via --data @policy.json or stdin (--data -).
delete <Type> <IdOrName> (Alias: rm) Soft-deactivates Domains/Accounts safely, deletes secondary Aliases or custom Routes, and revokes Scoped API Keys immediately. Schutz vor Selbstlöschung Built-in lockout guard prevents deleting the currently authenticated API key or admin principal.
dns <Domain> [--live] [--bind] [-o Datei] Verifies MX, SPF, Dual-DKIM (RSA-2048 + Ed25519), DMARC, MTA-STS, DANE TLSA, and BIMI live against public DNS or exports an RFC 1035 BIND zone file. Advisor-Tabelle / BIND-Zone Right after creating a domain, run sharpmail-cli dns company.com --bind -o company.com.zone to import all records cleanly without copy-paste typos.
snapshot & apply --dry-run (GitOps IaC) snapshot exports complete server or tenant state as ordered NDJSON operations; apply executes plans (supporting # and // comments) idempotently. Atomarer Zeilen-Bericht Always gate CI/CD deployments on sharpmail-cli apply -f plan.ndjson --dry-run (exits 1 with exact line diagnostics if any entry is invalid).
Sammlungen: Tenant, Domain, Account, Alias Manages Tenants (ServerAdmin), Domains with automatic Dual-DKIM key generation, user mailboxes (Account/User), distribution lists (Account/List), and Aliases (incl. isMasked). Rolle: TenantAdmin+ Running create Domain --set dkimSigningMode=Dual automatically generates both RSA-2048 and Ed25519 keypairs immediately.
Sammlungen: ApiKey & Route (OutboundRoute) ApiKey mints immutable role- and CIDR-scoped smk_ tokens (rotate via create + delete). Route manages per-domain smart-hosts and TLS certificate overrides. ApiKey: TenantAdmin+ · Route: ServerAdmin When a partner MX fails with RemoteCertificateNameMismatch, run: sharpmail-cli create Route --set domain=partner.com --set tlsMode=StartTlsIgnoreCert (blank targetHost = Auto DNS-MX).
Singletons: TransactionalSend & ReputationShield Controls IP/domain warming, categories, and provider quotas (TransactionalSend) alongside suppression lists, ARF FBL, RFC 8058 unsubscribe, and circuit breakers (ReputationShield). Presets per 1 Befehl Quick-configure via presets: sharpmail-cli update TransactionalSend --set preset=warming_28d and sharpmail-cli update ReputationShield --set preset=recommended.
Singletons: SpamGuard, SmtpQueue, TransportRules & Server Configures spam thresholds & ClamAV (SpamGuard), queue workers, smart-host & TLS policy (SmtpQueue), disclaimers & Fail2Ban (TransportRules), and serverHostName (Server). Rolle: ServerAdmin Zero-downtime hostname update: sharpmail-cli update Server --set serverHostName=mail.company.com updates EHLO, banners, and Autodiscover live.