Sample code for 30+ languages & platforms
Delphi DLL

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 Delphi DLL Downloads

Delphi DLL
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Imap, StringBuilder;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
imapSrc: HCkImap;
imapDest: HCkImap;
sbMime: HCkStringBuilder;
seqNum: Integer;

begin
success := False;

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

imapSrc := CkImap_Create();

// Connect to our source IMAP server.
success := CkImap_Connect(imapSrc,'imap.example.com');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imapSrc));
    Exit;
  end;

// Login to the source IMAP server
success := CkImap_Login(imapSrc,'admin@chilkatsoft.com','myPassword');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imapSrc));
    Exit;
  end;

imapDest := CkImap_Create();

// Connect to our destination IMAP server.
success := CkImap_Connect(imapDest,'mail.example-code.com');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imapDest));
    Exit;
  end;

// Login to the destination IMAP server
success := CkImap_Login(imapDest,'myLogin','myPassword');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imapDest));
    Exit;
  end;

// Select an IMAP mailbox on the source IMAP server
success := CkImap_SelectMailbox(imapSrc,'Inbox');
if (success = False) then
  begin
    Memo1.Lines.Add(CkImap__lastErrorText(imapSrc));
    Exit;
  end;

// After selecting a mailbox, the NumMessages property will
// be updated to reflect the total number of emails in the mailbox:
Memo1.Lines.Add(IntToStr(CkImap_getNumMessages(imapSrc)));

// 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 := CkStringBuilder_Create();

for seqNum := 1 to 10 do
  begin
    CkStringBuilder_Clear(sbMime);
    success := CkImap_FetchSingleAsMimeSb(imapSrc,seqNum,False,sbMime);
    if (success = False) then
      begin
        Memo1.Lines.Add(CkImap__lastErrorText(imapSrc));
        Exit;
      end;

    success := CkImap_AppendMimeWithFlagsSb(imapDest,'Inbox',sbMime,False,False,False,False);
    if (success = False) then
      begin
        Memo1.Lines.Add(CkImap__lastErrorText(imapDest));
        Exit;
      end;
  end;

// Disconnect from the IMAP servers.
success := CkImap_Disconnect(imapSrc);
success := CkImap_Disconnect(imapDest);

CkImap_Dispose(imapSrc);
CkImap_Dispose(imapDest);
CkStringBuilder_Dispose(sbMime);

end;