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


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. /*
  4.   mig - a command line PHP tool for transfering emails from one host to another.
  5.  
  6. Created by Kaspars Dambis
  7. http://konstruktors.com
  8. */
  9.  
  10. function m_connect() {
  11. global $msrc, $mdst;
  12.  
  13. // FROM
  14. $msrc = imap_open(
  15. '{mail.example.lv:143/imap/novalidate-cert}', // host
  16. '[email protected]', // username
  17. 'pass123') // password
  18. or die("Can't connect: " . imap_last_error());
  19.  
  20. // TO
  21. $mdst = imap_open(
  22. '{imap.gmail.com:993/imap/ssl/novalidate-cert}', // host
  23. '[email protected]', // username
  24. 'pass123') // password
  25. or die("can't connect: " . imap_last_error());
  26. }
  27.  
  28. // Go!
  29. m_connect();
  30.  
  31. $start = 1;
  32. $end = 1;
  33.  
  34. // Find the last message transfered
  35. if ($dst_status = imap_check($mdst)) {
  36. $start = $dst_status->Nmsgs;
  37. }
  38.  
  39. // Check how many messages are the source.
  40. if ($src_status = imap_check($msrc)) {
  41. $end = $src_status->Nmsgs;
  42. }
  43.  
  44. echo "Getting destination mailbox address...\n";
  45. $to_box = imap_mailboxmsginfo($mdst)->Mailbox;
  46.  
  47. echo "Started! - start: $start / end: $end";
  48.  
  49. for ($i = $start; $i <= $end; $i++) {
  50. // Check if we are still connected
  51. if (($i - $start) % 5 == 0) {
  52. if (!imap_ping($msrc) || !imap_ping($mdst)) {
  53. echo "\n\n Connection lost! Trying to reconnect ...\n\n";
  54. m_connect();
  55. } else {
  56. echo "\n\n Connection OK! \n\n";
  57. }
  58. }
  59.  
  60. // Check if message doesn't exist at the destination
  61. if ($message = imap_fetchbody($msrc, $i, null)) {
  62. if ($m = imap_headerinfo($msrc, $i)) {
  63. 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";
  64. imap_append($mdst, $to_box, $message);
  65. }
  66. }
  67. }
  68.  
  69. echo "Ended!\n";
  70.  
  71. imap_close($msrc);
  72. imap_close($mdst);
  73.  
  74. function format_size($size) {
  75. $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
  76. if ($size == 0) { return('n/a'); } else {
  77. return (round($size/pow(1024, ($i = floor(log($size, 1024)))), $i > 1 ? 2 : 0) . $sizes[$i]); }
  78. }
  79.  
  80. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.