Return to Snippet

Revision: 43120
at March 17, 2011 05:44 by konstruktors


Initial Code
<?php 

/*
 	mig - a command line PHP tool for transfering emails from one host to another.

	Created by Kaspars Dambis 
	http://konstruktors.com
	[email protected]
*/

function m_connect() {
	global $msrc, $mdst;
	
	// FROM
	$msrc = imap_open(
		'{mail.example.lv:143/imap/novalidate-cert}', // host
		'[email protected]', // username
		'pass123') // password
		or die("Can't connect: " . imap_last_error());
		
	// TO
	$mdst = imap_open(
		'{imap.gmail.com:993/imap/ssl/novalidate-cert}', // host
		'[email protected]', // username
		'pass123') // password
		or die("can't connect: " . imap_last_error());
}

// Go!
m_connect();

$start = 1;
$end = 1;

// Find the last message transfered
if ($dst_status = imap_check($mdst)) {
	$start = $dst_status->Nmsgs;
}

// Check how many messages are the source.
if ($src_status = imap_check($msrc)) {
	$end = $src_status->Nmsgs;
}

echo "Getting destination mailbox address...\n";
$to_box = imap_mailboxmsginfo($mdst)->Mailbox;

echo "Started! - start: $start / end: $end";

for ($i = $start; $i <= $end; $i++) {
	// Check if we are still connected
	if (($i - $start) % 5 == 0) {
		if (!imap_ping($msrc) || !imap_ping($mdst)) {
			echo "\n\n Connection lost! Trying to reconnect ...\n\n";
			m_connect();
		} else {
			echo "\n\n Connection OK! \n\n";
		}
	}
	
	// Check if message doesn't exist at the destination	
	if ($message = imap_fetchbody($msrc, $i, null)) {
		if ($m = imap_headerinfo($msrc, $i)) {
			echo "\n" . $i . " / $end" . "\n from: " . $m->fromaddress . "\n to: " . $m->toaddress . "\n subject: " . $m->subject . "\n size: " . format_size($m->Size) . "\n date: " . $m->date . "\n\n";
			imap_append($mdst, $to_box, $message);
		}
	}
}

echo "Ended!\n";

imap_close($msrc);
imap_close($mdst);

function format_size($size) {
      $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      if ($size == 0) { return('n/a'); } else {
      return (round($size/pow(1024, ($i = floor(log($size, 1024)))), $i > 1 ? 2 : 0) . $sizes[$i]); }
}

?>

Initial URL


Initial Description


Initial Title
Transfer / migrate messages between two IMAP/POP e-mail accounts

Initial Tags
email, php

Initial Language
PHP