Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

How to Copy IMAP Mail to another IMAP Server

Demonstrates how to copy the entire contents of an IMAP mailbox to another IMAP server.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Imap;
use Chilkat2\StringBuilder;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

$imapSrc = new Imap();

// Connect to our source IMAP server.
try {
    $imapSrc->Connect('imap.example.com');

    // Login to the source IMAP server
    $imapSrc->Login('admin@chilkatsoft.com', 'myPassword');

    $imapDest = new Imap();

    // Connect to our destination IMAP server.
    $imapDest->Connect('mail.example-code.com');

    // Login to the destination IMAP server
    $imapDest->Login('myLogin', 'myPassword');

    // Select an IMAP mailbox on the source IMAP server
    $imapSrc->SelectMailbox('Inbox');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// After selecting a mailbox, the NumMessages property will
// be updated to reflect the total number of emails in the mailbox:
echo $imapSrc->NumMessages, "\n";

// The emails in the mailbox will always have sequence numbers
// ranging from 1 to NumMessages.

// This example will copy the first 10 messages using sequence numbers
$sbMime = new StringBuilder();
for ($seqNum = 1; $seqNum <= 10; $seqNum++) {
    $sbMime->Clear();
    try {
        $imapSrc->FetchSingleAsMimeSb($seqNum, false, $sbMime);

        $imapDest->AppendMimeWithFlagsSb('Inbox', $sbMime, false, false, false, false);
    } catch (\Chilkat2\Exception $e) {
        echo $e->getMessage(), "\n";
        exit;
    }
}

// Disconnect from the IMAP servers.
$imapSrc->Disconnect();
$imapDest->Disconnect();