Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Nextcloud-ConnectMail
Bulk-link IMAP/SMTP mail accounts for Nextcloud users via occ mail:account:create.
Intended for admins who need to link mail accounts for multiple users at once — for example during onboarding, migration, or provisioning from an external list.
When to use this script
The Nextcloud Mail app provides no REST endpoint for an admin to link an
account on behalf of another user. There is an occ mail:account:create <userId> ...
command, but it is positional and cumbersome for bulk work. This script wraps that
call and reads a CSV file.
Alternatives:
- Provisioning templates (Mail admin UI): one template per domain, no per-user credentials. Only works if all users share the same mail cluster.
- Custom REST controller: requires patching the Mail app itself.
Requirements
- Shell access to the Nextcloud server (directly or via SSH /
docker exec) occexecutable as the web user (usuallywww-data)- The Nextcloud Mail app installed and enabled
python3on the host running the script (for RFC-4180 CSV parsing)
Usage
OCC_CMD="docker exec -u www-data nc-dev php occ" \
./mail-bulk-link.sh accounts.csv
Classic install:
OCC_CMD="sudo -u www-data php /var/www/nextcloud/occ" \
./mail-bulk-link.sh accounts.csv
Remote via SSH:
OCC_CMD="ssh hetzner-ax42 docker exec -u www-data nc-dev php occ" \
./mail-bulk-link.sh accounts.csv
CSV format
Header row required, column order flexible. Required columns:
userId,name,email,imapHost,imapPort,imapSsl,imapUser,imapPass,smtpHost,smtpPort,smtpSsl,smtpUser,smtpPass
Optional column: authMethod (password or xoauth2, defaults to password).
imapSsl/smtpSsl:ssl,tls, ornone- Lines starting with
#are skipped - Quote fields containing commas per RFC 4180 (
"foo,bar")
See accounts.example.csv for a working example.
Limitations
- No connection test. The
occcommand stores blindly — invalid credentials are accepted silently. The user only finds out on the first sync. The REST route (POST /api/accounts) does a live IMAP/SMTP check, but only works for the currently logged-in user. - No initial mailbox sync. The REST route triggers one;
occdoes not. First sync happens on the next background job run or first user login. - Plaintext passwords in the CSV. They sit on disk during execution. After
the run:
shred -u accounts.csv. Never commit credential CSVs.
Security
- Add
accounts.csv(and variants) to your deployment repo's.gitignore - Only run this from environments where you already hold admin rights
- For production use: pull credentials from a secrets store and generate the
CSV on the fly in
tmpfs
License
AGPL-3.0-or-later (consistent with Nextcloud Mail).