DEV Community

Fernando Paladini
Fernando Paladini

Posted on

Copy Rocket.Chat SMTP and Upload Settings Between MongoDB Instances with Python

Standing up a staging or replacement Rocket.Chat server often stalls on repetitive admin work: copying outbound SMTP relay fields and S3-compatible file upload settings across environments by hand in the web UI, hoping no bucket URL, region, or port gets mistyped. Full database dumps (mongodump and mongorestore) handle disaster recovery, but they also overwrite rooms, users, and site URLs when you only want mail or storage configuration.

TL;DR: Rocket.Chat.Export.Settings is an MIT-licensed Python CLI utility that reads selected configuration documents (-s for SMTP, -u for File Upload) from an origin rocketchat.rocketchat_settings MongoDB collection, replaces the matching _id documents in a destination Rocket.Chat database, and refreshes their ts and _updatedAt timestamps. Because the script calls PyMongo's legacy Collection.update method, run it inside a virtual environment pinned to pymongo==3.13.0 (pymongo<4), back up the destination rocketchat_settings collection first, and tunnel MongoDB traffic over localhost or a private network rather than exposing port 27017.

In this tutorial, you will inspect the repository at its verified commit, run a read-only preflight check before touching live data, execute a selective SMTP and file-upload copy, and verify the destination documents without printing plaintext secrets.

Prerequisites and Environment Boundaries

Confirm these requirements before running the exporter:

  • Source state: paladini/Rocket.Chat.Export.Settings publishes no tagged GitHub releases or PyPI package. All files live on master at commit fc29d7a under the MIT License.
  • Python and PyMongo version: Python 3 with pymongo>=3.12,<4 (pymongo==3.13.0). Note two upstream details in requeriments.txt: the filename is spelled requeriments.txt, and pymongo is unpinned. Installing PyMongo 4.x breaks settings_exporter.py during writes because Collection.update() was removed in PyMongo 4.0.
  • Private MongoDB reachability: Direct connectivity to both rocketchat databases. For remote servers, forward local ports over SSH (127.0.0.1:27017 and 127.0.0.1:27018) instead of binding MongoDB to public interfaces.
  • Destination backup: Dump rocketchat_settings on the target first (mongodump --uri="mongodb://127.0.0.1:27018/rocketchat" --collection=rocketchat_settings --out=./backup-settings) so any unintended overwrite is reversible.

Minimal Working Path

Clone the repository, check out commit fc29d7a, and install pymongo==3.13.0 inside an isolated virtual environment:

git clone https://github.com/paladini/Rocket.Chat.Export.Settings.git
cd Rocket.Chat.Export.Settings
git checkout fc29d7af1913ed438fd751f0137c1a3ee8ee8635

python3 -m venv .venv
source .venv/bin/activate
python -m pip install "pymongo==3.13.0"
Enter fullscreen mode Exit fullscreen mode

On Windows PowerShell, activate the environment with .venv\Scripts\Activate.ps1 before running pip.

Check the CLI flags with --help:

python settings_exporter.py --help
Enter fullscreen mode Exit fullscreen mode

The command outputs the positional MongoDB endpoints and selector flags without opening a network connection:

usage: settings_exporter.py [-h] [-s] [-u] origin destiny

Export settings from one Rocket.Chat instance to another.

positional arguments:
  origin             The IP Address of the MongoDB database that you would
                     like to export configs. Eg: 172.12.0.3:27017.
  destiny            The IP Address of the MongoDB database that you would
                     like to import configs. Eg: 172.12.0.5:27017

options:
  -h, --help         show this help message and exit
  -s, --smtp         Enable 'SMTP' configs to be exported.
  -u, --file-upload  Enable 'File Upload' configs to be exported.
Enter fullscreen mode Exit fullscreen mode

Assume your origin MongoDB listens on 127.0.0.1:27017 and your staging MongoDB is forwarded to 127.0.0.1:27018. Run a read-only preflight check first to confirm every target _id exists in both databases:

from pymongo import MongoClient
import settings_exporter as se

src = MongoClient("mongodb://127.0.0.1:27017/", serverSelectionTimeoutMS=3000).rocketchat["rocketchat_settings"]
dst = MongoClient("mongodb://127.0.0.1:27018/", serverSelectionTimeoutMS=3000).rocketchat["rocketchat_settings"]

for group, keys in se.configs_to_export.items():
    uniq = sorted(set(keys))
    miss_src = [k for k in uniq if src.find_one({"_id": k}) is None]
    miss_dst = [k for k in uniq if dst.find_one({"_id": k}) is None]
    print(f"{group}: count={len(uniq)} missing_src={miss_src} missing_dst={miss_dst}")
Enter fullscreen mode Exit fullscreen mode

Once missing_src and missing_dst are empty ([]) for your chosen groups, run the exporter with -s (SMTP), -u (file upload), or -su (both):

python settings_exporter.py -su 127.0.0.1:27017 127.0.0.1:27018
Enter fullscreen mode Exit fullscreen mode

Expected Result and Reproducible Verification

A successful run prints a separator line and Done!:

=================================================================

Done!
Enter fullscreen mode Exit fullscreen mode

With pymongo==3.13.0, Python also prints DeprecationWarning: update is deprecated to stderr when import_configs() refreshes the timestamps. That warning is normal under PyMongo 3.x.

Verify that the destination rocketchat_settings documents match the origin values and received fresh _updatedAt timestamps while keeping secrets masked:

from pymongo import MongoClient
import settings_exporter as se

SECRET_IDS = {"SMTP_Password", "FileUpload_S3_AWSAccessKeyId", "FileUpload_S3_AWSSecretAccessKey"}
src = MongoClient("mongodb://127.0.0.1:27017/").rocketchat["rocketchat_settings"]
dst = MongoClient("mongodb://127.0.0.1:27018/").rocketchat["rocketchat_settings"]

for key in sorted({k for keys in se.configs_to_export.values() for k in keys}):
    s_doc, d_doc = src.find_one({"_id": key}), dst.find_one({"_id": key})
    same = bool(s_doc and d_doc and s_doc.get("value") == d_doc.get("value"))
    shown = "<redacted>" if key in SECRET_IDS else repr(d_doc.get("value") if d_doc else None)
    print(f"{key}: match={same} value={shown} _updatedAt={d_doc.get('_updatedAt') if d_doc else None}")
Enter fullscreen mode Exit fullscreen mode

Every exported key should report match=True with a current UTC _updatedAt timestamp and <redacted> for credential fields.

Why It Works

Rocket.Chat stores instance administration settings in the rocketchat database's rocketchat_settings collection. Each setting is a BSON document keyed by a string _id (such as SMTP_Host or FileUpload_Storage_Type) containing its value, UI metadata, ts, and _updatedAt fields.

settings_exporter.py performs three focused operations:

  1. Flag-based pruning (check_configs_to_export): configs_to_export maps "smtp" to 5 keys (SMTP_Host, SMTP_Port, SMTP_Username, SMTP_Password, From_Email) and "file_upload" to 14 unique keys (FileUpload, FileUpload_Enabled, FileUpload_MaxFileSize, FileUpload_MediaTypeWhiteList, FileUpload_ProtectFiles, FileUpload_Storage_Type, plus eight FileUpload_S3_* keys). Disabled groups are popped before connecting.
  2. Whole-document reads (export_configs): Each target _id is fetched with settings.find_one({"_id": value}), preserving Rocket.Chat's full document structure rather than overwriting documents with bare values.
  3. Replacement and timestamp refresh (import_configs): On the destination collection, settings.replace_one({"_id": value}, new_configs[value]) writes the document, followed by two $currentDate updates on ts and _updatedAt so running Rocket.Chat processes observe the change without serving stale cached values.

Failure Modes, Limitations, and Security Boundaries

Treat these operational boundaries carefully before running the script against real servers:

  • PyMongo 4.x crash mid-import: In PyMongo 4.0+, Collection.update does not exist, so settings.update resolves as a sub-collection object and raises TypeError: 'Collection' object is not callable right after replace_one overwrites the first setting. Always pin pymongo==3.13.0 for unmodified execution, or replace the two settings.update(...) calls with settings.update_one(...) in a local copy.
  • Schema drift (None documents and upsert=False): If an _id in configs_to_export is missing on the origin server (for example, when newer Rocket.Chat releases rename a setting key), find_one returns None and replace_one aborts with TypeError: document must be an instance of dict. If an _id is missing on the destination server, replace_one defaults to upsert=False and silently updates zero documents.
  • Silent no-op without flags and duplicate list items: Running python settings_exporter.py origin destiny without -s or -u pops both groups and prints Done! after zero reads or writes. Also note that FileUpload_ProtectFiles, FileUpload_Storage_Type, and FileUpload_S3_Bucket appear twice in configs_to_export["file_upload"], causing three extra idempotent writes when -u is enabled.
  • Plaintext secrets and URI exposure: Copying -s and -u transfers SMTP_Password and S3 secret keys verbatim, which can cause a staging server to send real mail or write to production storage unless you immediately adjust destination settings. Finally, MongoClient('mongodb://{}/'.format(...)) uses plain mongodb:// against database rocketchat; keep connections inside SSH local tunnels or private networks, and avoid passing credentials on shared multi-user command lines.

FAQ

Does this tool talk to the Rocket.Chat HTTP API?
No. It reads and writes MongoDB's rocketchat.rocketchat_settings collection directly via pymongo.

Why did pip install -r requirements.txt fail?
The repository file is named requeriments.txt, and its pymongo entry is unpinned. Install "pymongo==3.13.0" explicitly instead.

Will staging start using production S3 or SMTP immediately?
Yes, if both instances share those setting keys. Point FileUpload_S3_Bucket or SMTP_Host on staging to non-production resources right after importing.

Takeaway

Rocket.Chat.Export.Settings streamlines selective Rocket.Chat configuration copies when you pair it with pymongo==3.13.0, an _id existence preflight, and a destination mongodump backup before running replacements.

When migrating configuration across self-hosted chat or MongoDB-backed services, do you rely on targeted collection scripts, Admin REST APIs, or environment variable overrides?

Disclosure: This tutorial was researched, smoke-tested, and drafted with AI assistance using primary repository sources and local PyMongo verification.

Top comments (0)