Can someone help me write a extremely robust script for IMAP-transfers

I need to transfer 10 000-20 000 mails between two (Gmail) IMAP mailboxes. If I do this using Mail.app, Thunderbird or some other regular IMAP-client it never completes and it never gives good error messages = you never know what messages was transferred successfully and not.

Could someone here help me write a very robust script that can handle such a transfer? Performance is secondary, stability and reliability as prio 1, 2 and 3.

I imagine that a good approach would be to transfer one message at the time and then verify that it was successfully transferred and the mailbox synced before transferring the next message, in more detail:

  1. Mark message M1 in mailbox X in account A as “In progress”
  2. Transfer M1 from A->X to account B, mailbox Y
  3. Sync Y
  4. Verify that M1 is in Y (search for message-id or so)
  5. Mark M1 as successfully transferred (using some flag, move it to another mailbox in A or so)

Repeat with message M2 up to M15000

If step 1, 2 or 3 fails for a message, continue with the next message, leaving the failed message marked “In progress”.

If this is super slow, maybe transfer 10 messages at the time or so (but not much more because then, when it fail, you have to manually look through all 10 messages to see where it got stuck).

I imagine Mail.app is a good target for this script but I am agnostic with regards to the client.