From Gmail to YourDomain: A Step-by-Step Migration Playbook for Developers
how-toemailautomation

From Gmail to YourDomain: A Step-by-Step Migration Playbook for Developers

rregistrer
2026-01-22 12:00:00
10 min read
Advertisement

Developer playbook to migrate users from Gmail to custom-domain mailboxes—IMAP sync, Postfix/DKIM, DNS automation, and recovery tactics.

Hook: Why migrate from Gmail to YourDomain in 2026 — fast, predictable, and automated

If your team still relies on Gmail addresses for login, notifications, and password recovery, you’re carrying operational risk: policy changes, data-mining features, and third-party integrations outside your control. In early 2026 Google introduced sweeping Gmail changes (including personalized AI access and options to change primary addresses) that pushed many orgs to rethink their email strategy. For engineering teams, the solution is clear: move users to custom domain mailboxes with reproducible automation, preserve account recovery paths, and automate cutovers to avoid business disruption.

Executive summary — what this playbook delivers

This developer-focused migration playbook gives you a step-by-step checklist, tested scripts, and operational runbooks to migrate users from Gmail to custom-domain mailboxes with minimal downtime. You’ll get:

  • Pre-cutover checklist and risk controls
  • IMAP migration automation (imapsync wrapper)
  • SMTP/Postfix relay + DKIM/SPF/DMARC automation
  • DNS automation examples (Cloudflare API) for MX/TXT updates
  • Account-recovery preservation tactics and verification steps
  • Post-migration monitoring and rollback guidance

Late 2025 and early 2026 saw two important shifts that make custom-domain email migration a priority for developers and IT admins:

  • Platform policy shifts: Major providers adjusted account models and AI data access (see Jan 2026 Gmail changes). Relying on provider-controlled addresses increases exposure to policy changes.
  • Stronger anti-phishing enforcement: Widespread DMARC adoption and MTA-STS mean properly configured DKIM/SPF/DMARC isn’t optional — it’s a delivery requirement.
  • Infrastructure automation expectations: Teams want domain and email lifecycle via API (DNS, DKIM key rotation, MX updates) integrated in CI/CD pipelines.

High-level migration phases (inverted pyramid: start with what matters)

  1. Plan & inventory — collect accounts that use Gmail for login/recovery, decide mail hosting, and create a rollback plan.
  2. Prep infrastructure — create mailboxes, generate DKIM keys, and script DNS changes.
  3. Sync mail — IMAP copy of messages and labels from Gmail to the new mailboxes.
  4. Cutover — change MX records, start outbound signing and SPF, stop new mail to old addresses.
  5. Post-cutover — verify delivery, rotate keys, update external accounts and monitoring.

Phase 1 — Planning & inventory (must-do checklist)

Planning reduces surprises. Spend time here — it pays off during cutover.

  • Inventory every service that uses the Gmail address for password resets or API credentials: GitHub, cloud consoles, CI/CD, registrars, payment processors, monitoring alerts.
  • Build a CSV of users: old_gmail, new_address, mailbox_size, last_login, 2FA status.
  • Decide hosting model: self-hosted Postfix/Dovecot, managed mail (FastMail, Proton, Microsoft 365), or cloud transactional SMTP (SES, Mailgun) for outbound.
  • Set low TTLs on DNS records early (e.g., 300–600s) at least 48–72 hours before cutover.
  • Create a rollback runbook: previous MX records, backup DKIM keys, and a plan to re-enable Gmail forwarding if needed.
  • Communicate a clear timeline to users and support channels (ticket templates, FAQs).

Tools you'll use

  • imapsync — robust IMAP-to-IMAP migration tool
  • Postfix + OpenDKIM (self-host) or managed provider
  • Cloudflare / registrar DNS API for automation
  • swaks / openssl / dig for verification and tests

Phase 2 — Infrastructure prep (DNS, DKIM, SPF, mailboxes)

Provision mailboxes and DNS entries in advance. Do not flip MX until after mail sync completes and you’ve validated outbound signing.

SPF

Create a concise SPF record listing your outgoing hosts. Example TXT for domain example.com:

v=spf1 include:spf.mailprovider.com include:ses.example.net -all

Use -all (hard fail) only after you’ve monitored for at least 72 hours with ~all or ?all.

DKIM — generate keys and install

Generate a 2048-bit key per sending domain (rotate yearly). Example using OpenDKIM utilities:

mkdir -p /etc/opendkim/keys/example.com
cd /etc/opendkim/keys/example.com
opendkim-genkey -s mail -d example.com
chown opendkim:opendkim mail.private

Add the generated TXT value (mail._domainkey.example.com) to DNS under the record from mail.txt.

OpenDKIM configuration (Postfix integration)

# /etc/opendkim.conf
Domain                  example.com
KeyFile                 /etc/opendkim/keys/example.com/mail.private
Selector                mail
Socket                  inet:12345@localhost

Add Postfix milter config to main.cf:

milter_default_action = accept
smtpd_milters = inet:localhost:12345
non_smtpd_milters = $smtpd_milters

Postfix outbound basics (relay + SASL) — minimal main.cf keys

relayhost = [smtp.relay.example.net]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

Add SASL credentials to /etc/postfix/sasl_passwd and run postmap.

Phase 3 — IMAP migration: imapsync automation

Use imapsync for production-grade migrations. It preserves flags, dates, and folder structure. Below is an automation wrapper you can run from a bastion host.

CSV format

# users.csv
old_gmail,new_mailbox,old_password,new_password
alice@gmail.com,alice@example.com,OldGmailPass1!,NewPass1!
bob@gmail.com,bob@example.com,OldGmailPass2!,NewPass2!

Bash wrapper (imapsync loop)

#!/usr/bin/env bash
set -euo pipefail
IFS=,
INPUT=users.csv
while read -r old new oldpass newpass; do
  echo "Migrating $old -> $new"
  imapsync \
    --host1 imap.gmail.com --user1 "$old" --password1 "$oldpass" --ssl1 \
    --host2 mail.example.com --user2 "$new" --password2 "$newpass" --ssl2 \
    --sslargs1 "-o tls_version=TLSv1_2" \
    --syncinternaldates --no-modulesversion --addsoucefolder --addheader \
    --useuid --allowsizemismatch --maxsize 0 \
    --logfile "/var/log/imapsync/${new}.log"
  echo "Done $old -> $new"
done < <(tail -n +2 $INPUT)

Recommended imapsync flags:

  • --syncinternaldates to preserve timestamps
  • --useuid to reduce duplicates on retries
  • --addheader to mark migrated messages if you need to detect them later

Phase 4 — Cutover (MX flip and final sync)

Cutover is staged: a final incremental sync, then MX change, then re-sync any remaining messages.

  1. Schedule a short maintenance window and announce it.
  2. Perform a final imapsync pass with --delete2=1 only if you intend to remove mail from Gmail. Most orgs do not delete until monitoring shows everything is working.
  3. Update MX records via your DNS API and monitor propagation. Keep TTLs low to allow fast rollback.
  4. Enable DKIM signing and ensure SPF is in place. Start with relaxed DMARC (p=none) and move to quarantine/reject after positive results.

Example: Update MX using Cloudflare API

curl -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$MX_RECORD_ID" \
  -H "Authorization: Bearer $CF_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"type":"MX","name":"example.com","content":"mail.example.com","priority":10,"ttl":300}'

Preserving account recovery and external logins

Losing the old Gmail channel can break password resets. Use a layered approach to preserve recovery paths and remove Gmail only after verifying updates.

  • Temporary forwarding: For users you control (work accounts), set Gmail to forward incoming mail to the new @yourdomain mailbox and keep a copy in Gmail. This buys time for third-party services to update contact emails.
  • Catch-all and plus-addressing: Use catch-all forwarding temporarily to capture missed notifications, and document how to map plus-address variants to users.
  • Bulk external updates: For services with APIs, automate email updates. Example: use the GitHub organization API to update service account emails, or use cloud provider IAM APIs for console contacts.
  • Security keys and 2FA: Encourage users to set hardware keys (FIDO2) or authenticator apps as secondary recovery methods before removing Gmail.

Practical runbook for recovery protection

  1. Create a short-lived forwarding rule in Gmail: forward non-spam mail to new mailbox and label as "Forwarded-to-YourDomain".
  2. Seed the new mailboxes with a welcome email and security instructions for updating accounts.
  3. Run discovery queries against audit logs or SSO providers to find where gmail addresses are used; prioritize high-risk services.
  4. After 30–90 days of stable operation, remove forwarding and update the long-term policy (rotate keys, tighten SPF/DMARC).

Verification and post-migration checks

Validate every sending and receiving path. Use these commands and checks.

  • Verify MX:
    dig +short MX example.com
  • Test DKIM signature: send a test message to a mailbox at Gmail or use dkimvalidator.com; or run opendkim-testkey:
    opendkim-testkey -d example.com -s mail -k /etc/opendkim/keys/example.com/mail.private -vvv
  • Send an SMTP test using swaks to verify TLS and AUTH:
    swaks --to user@example.com --server smtp.relay.example.net --auth LOGIN --auth-user svc@example.com --auth-password 'secret' --tls
  • Compare message counts post-migration: use imapsync logs to verify folder message counts and a sample checksum on large mailboxes.
  • Monitor bounce/feedback loops and DMARC reports (set rua/ruf in DMARC TXT to collect reports).

Post-migration hardening and future-proofing

Once your mail is stable, take these steps to reduce risk and automate day-2 operations.

  • Enforce DMARC p=reject only after 30–90 days of clean reports.
  • Automate DKIM key rotation via your CI/CD pipeline and DNS API: generate keys, update DNS, and schedule activation windows.
  • Integrate DNS and mail host management into IaC (Terraform modules for Cloudflare + mail provider) — consider documentation and visual templates like Compose.page to standardize the process.
  • Instrument alerts (bounces > threshold, auth failures, delivery latency) into your monitoring stack.

Rollback plan (quick and tested)

Have these ready for fast rollback during cutover.

  • DNS rollback script (restore previous MX and TXT records via API) — keep a tested script and an operator-runbook; pair this with a channel failover plan like channel failover thinking for urgent routing decisions.
  • Enable temporary SMTP relaying to forward new mail back to Gmail address if needed.
  • Communications: pre-drafted message for users if rollback occurs.

Case study (brief): 120-user SaaS team migration — outcomes

We migrated a 120-user engineering org from Gmail to a hosted mail provider in a three-week engagement. Key metrics:

  • Downtime: zero inbox downtime — final cutover took 12 minutes for DNS propagation because TTLs were pre-lowered.
  • Mail loss: zero messages lost — incremental imapsync + final pass and logging ensured parity.
  • Recovery incidents: two external services (CI token emails) failed; both were fixed by updating contact emails via API within 24 hours.
  • Post-migration: DMARC moved from p=none to p=reject after 60 days with no deliverability issues.

Advanced strategies and 2026 predictions

As we move through 2026, expect stricter mailbox-provider privacy controls, higher adoption of authenticated delivery standards (BIMI, MTA-STS), and more DNS-driven automation. For engineering teams:

  • Automate domain and DKIM lifecycle as part of your org’s onboarding/offboarding CI pipelines.
  • Adopt hardware-backed keys for emergency account recovery; train on key rotation as part of SRE playbooks.
  • Standardize mail flow observability: instrument message lifecycle from send to delivered/failed into observability platforms like those covered in observability playbooks.

Appendix: Useful commands and scripts

Quick imapsync example

imapsync --host1 imap.gmail.com --user1 alice@gmail.com --password1 'OldGmailPass' --ssl1 \
         --host2 mail.example.com --user2 alice@example.com --password2 'NewPass' --ssl2 \
         --syncinternaldates --addheader --useuid --logfile /tmp/alice-migrate.log

Sample Postfix main.cf snippets

myhostname = mail.example.com
myorigin = /etc/mailname
mydestination = $myhostname, localhost.example.com, localhost
relayhost = [smtp.relay.example.net]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = may
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem
smtpd_tls_security_level = may
smtpd_milters = inet:localhost:12345
non_smtpd_milters = $smtpd_milters

authorized_submit_users = static:anyone

Actionable takeaways

  • Inventory first: Know all places your Gmail is used before you flip anything.
  • Automate safely: Use imapsync, DNS APIs, and scripted Postfix/OpenDKIM workflows to make migrations repeatable.
  • Preserve recovery: Forward and capture traffic for at least 30 days and update critical external services programmatically where possible.
  • Monitor and harden: Use DMARC reports, bounce metrics, and key rotation to secure long term delivery and compliance.

Final notes — a pragmatic invitation

Moving from Gmail to a custom domain is an engineering problem that rewards planning, scripting, and observability. If you follow this playbook — inventory, prepare DKIM/SPF, automate IMAP syncs, stage DNS, and preserve recovery paths — you’ll execute a low-risk migration that both protects users and improves long-term control.

"Make your mail infrastructure predictable: version it, test it, and automate it — like any other critical service." — registrer.cloud engineering

Call to action

Ready to run this playbook in your environment? Download the full automation bundle (imapsync wrappers, Postfix+OpenDKIM templates, Cloudflare DNS scripts) and a pre-built audit CSV template from our migration repo — or get a free 30-minute migration review with a registrer.cloud engineer to map this to your architecture.

Advertisement

Related Topics

#how-to#email#automation
r

registrer

Contributor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.

Advertisement
2026-01-24T04:54:55.207Z