Email

Migrate Google Workspace email with imapsync (OAuth2 service account)

Reviewed on 11 min read email migration imapsync Google Workspace

When a customer wants to move the email of a domain hosted on Google Workspace to our servers, they can use imapsync. Google no longer allows third-party apps to connect over IMAP with the account's normal password. You have to use OAuth 2.0 or, for a one-off migration of a few accounts where the policy allows it, an app password.

In this guide we explain the two valid ways to authenticate the Google Workspace source and, specifically, how to set up a service account with domain-wide delegation. The same credential can authenticate the authorised mailboxes without touching each user, although imapsync has to synchronise them one by one.

Why the normal password no longer works

Google has withdrawn access for "less secure apps" (basic auth) in stages:

  • 15 June 2024: the less secure apps setting is removed from the Admin console. The administrator can no longer turn it on (existing connections kept working temporarily).
  • 14 March 2025: Google began turning off third-party app access with the normal password on Workspace accounts.
  • 1 May 2025: the announced transition for these apps came to an end.

So don't set up imapsync with the normal password. OAuth2 delegation is the right option for many accounts; an app password is a per-user exception that requires 2-Step Verification and that the administrator hasn't restricted it.

The two options

Service account (XOAUTH2) App passwords
Best for Migrating a whole domain Migrating one or a few accounts
You need to touch each user No Yes (turn on 2-Step Verification + generate a code)
What you need 1 JSON file (the admin creates it once) A 16-character code per account
Access required Workspace admin + Google Cloud Access to each account

If you're only going to migrate one or two accounts, app passwords (described in Move Gmail accounts to Hostsuar) are the quickest option. For a whole domain, carry on with the service account.

Set up the service account (done by the Workspace administrator)

These steps are carried out just once by a super administrator of the Google Workspace domain. At the end you get a JSON file that can authenticate every account in the domain. It contains a private key that gives full access to those mailboxes: store it as you would a password.

1. Create or select a project in Google Cloud

Go to console.cloud.google.com with the administrator account and create a new project (for example migracion-correo) or select an existing one.

Creating a project in Google Cloud

2. Enable the Gmail API (optional)

In APIs & Services → Library, search for Gmail API and click Enable. The imapsync documentation doesn't require it for this method, because access is granted by the delegation in step 4, but many Google guides include it and it costs nothing.

Enabling the Gmail API

3. Create the service account and its JSON key

Go to APIs & Services → Credentials → Create credentials → Service account and give it a name. The wizard will then offer you two steps marked (optional): "Permissions / Grant this service account access to project" (select a role) and "Principals with access". Leave both empty and continue: this service account doesn't need any IAM role on the project, because access to the mailboxes is granted in step 4 (domain-wide delegation), not here. Click Done to create it.

Then, inside the service account, open the Keys tab → Add key → Create new key and choose the JSON format (don't use P12).

Creating a JSON key for the service account

A file with this structure will be downloaded, which you'll rename to secret.xoauth2.json:

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
  "client_email": "xxx@proyecto.iam.gserviceaccount.com",
  "client_id": "1234567890...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}

Note down the client_id value from the JSON (a long number): we'll need it in the next step. It's the service account's OAuth2 identifier and it's exactly what goes into the Client ID field of the domain-wide delegation (step 4).

4. Authorise domain-wide delegation

This step takes place in the Google Workspace Admin console (admin.google.com), which is a different site from the Google Cloud Console where you created the service account.

The quickest way is to go straight to the delegation URL (signed in as a super administrator):

https://admin.google.com/ac/owl/domainwidedelegation

Or, by navigating: Menu (☰) → Security → Access and data control → API controls → "Manage Domain Wide Delegation". Once there, click Add new and:

  • In Client ID, paste the client_id from the previous step.
  • In OAuth scopes, enter this scope:
https://mail.google.com/

Very important: https://mail.google.com/ is the scope that imapsync's JSON flow requests to access over IMAP. Authorise only that scope. gmail.readonly doesn't allow IMAP sign-in. Google documents gmail.imap_admin as an alternative for clients that explicitly request that scope; adding it in the console doesn't make imapsync request it, nor does it guarantee that hidden labels will appear.

Click Authorise to save.

5. Check that IMAP is enabled

In the Admin console, go to Apps → Google Workspace → Gmail → End User Access and make sure IMAP access is turned on. In the email client policy for the organisational unit concerned, any mail client must be allowed; restricting it to specific OAuth client IDs can block the service account even if the delegation exists.

With this, the Google side is ready. The administrator just needs to get the secret.xoauth2.json file to whoever runs the migration, through a secure channel (not in the text of a ticket or by email).

Test and run imapsync

This method doesn't work in imapsync's web interface, which only supports a user name and password: you have to run it from the command line. If you use imapsync from the source code (not the binary), first install the Perl modules XOAUTH2 needs:

sudo cpanm JSON::WebToken JSON Crypt::OpenSSL::RSA LWP HTML::Entities Encode::Byte

Save the destination mailbox password in a private file (chmod 600 ~/.imapsync-destino) and first test only the sign-in for one account:

imapsync \
  --host1 imap.gmail.com --ssl1 --sslargs1 SSL_verify_mode=1 --user1 usuario@tudominio.com \
  --password1 /ruta/privada/secret.xoauth2.json --authmech1 XOAUTH2 \
  --host2 SERVIDOR_IMAP_DESTINO --ssl2 --sslargs2 SSL_verify_mode=1 --user2 usuario@tudominio.com \
  --passfile2 "$HOME/.imapsync-destino" --justlogin

Remove --justlogin only once both authentications work. Delegation saves you creating a key per user, but imapsync still runs one synchronisation per mailbox. Test one account first, check labels and counts, and then process the rest in a controlled way. Gmail limits IMAP downloads to 2,500 MB per user per day according to the published limit, which Google may change; when you reach the limit, stop that account and wait before resuming it. For SERVIDOR_IMAP_DESTINO, use the hostname with a valid certificate shown in cPanel's Connect Devices.

To migrate every account, prepare a cuentas.txt file with one address per line and one destination password per account in ~/.imapsync-destino-USUARIO, and loop through it:

while read cuenta; do
  imapsync \
    --host1 imap.gmail.com --ssl1 --user1 "$cuenta" \
    --password1 /ruta/privada/secret.xoauth2.json --authmech1 XOAUTH2 \
    --host2 SERVIDOR_IMAP_DESTINO --ssl2 --user2 "$cuenta" \
    --passfile2 "$HOME/.imapsync-destino-${cuenta%@*}" \
    --gmail1 --logfile "migracion-${cuenta}.log"
done < cuentas.txt

--gmail1 applies imapsync's settings for Gmail as the source: it limits the speed so as not to hit Google's limits, removes the [Gmail]/ prefix from special folders, leaves "All Mail" until the end and doesn't copy again a message it has already copied from another label. If an account is cut off by the daily download limit, run it again the next day: imapsync only copies what's missing.

When the migration is finished

Once you've checked the mailboxes at the destination:

  1. In admin.google.com/ac/owl/domainwidedelegation, delete the authorisation for the client_id.
  2. In Google Cloud, open the service account, Keys tab, and delete the key (or the whole service account).
  3. Delete every copy of the secret.xoauth2.json file.

If the key could have been exposed at any point, delete it and create a new one before continuing: deleting the file doesn't invalidate a key that has already been copied.

Then, when you want new email to arrive at Hostsuar, change the MX records and run imapsync one last time to copy whatever has arrived in Google in the meantime.

You may also find useful

Something wrong or out of date? Tell us and we will review it.