Posted By

konstruktors on 03/17/11


Tagged

email php gmail move pop imap transfer


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

uberdragon
Mello


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


 / Published in: PHP
 

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

Report this snippet  

You need to login to post a comment.