PHP Script to Migrate Labels From One GMail or Google Apps Account to Another

Google provides no easy way to migrate or import/export labels from GMail. During a recent domain name change this was an absolute requirement, so I whipped up a PHP script.

I wrote this while watching Top Gear and there is no error checking here. Use at your own risk. This would be a decent kernel for a class or a more robust application, but since it was just needed to work once with limited testing it's very barebones.

One note: you must have PHP compiled --with-imap-ssl. This sounds scary; for me it was just a matter of finding the imap.so file that I could drop into MAMP's extension directory and restart Apache.


<?php

// source
$hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}';
$username = 'name@sourcedomain.com';
$password = 'supersecretpassword';

$imap = @imap_open($hostname,$username,$password) 
    or die('Cannot connect to Gmail: ' . imap_last_error());

$list = imap_getmailboxes($imap, $hostname, "*");

$folders = array();
foreach($list as $k => $v)
{
    $name = str_replace($hostname, '', $v->name);
    
    if($name != 'INBOX' && (strpos($name, '[Gmail]') === FALSE) )
    {
        $folders[] = $name;
    }
}

// target
$hostname = '{imap.gmail.com:993/imap/ssl/novalidate-cert}';
$username = 'name@targetdomain.com';
$password = 'supersecretpassword';

$imap = @imap_open($hostname,$username,$password) 
    or die('Cannot connect to Gmail: ' . imap_last_error());

foreach($folders as $label)
{ 
    @imap_createmailbox($imap, imap_utf7_encode($hostname . $label));
}

?>