4 define('INSTALL_PATH', realpath(dirname(__FILE__) . '/..') . '/' );
5 ini_set('memory_limit', -1);
7 require_once INSTALL_PATH.'program/include/clisetup.php';
11 print "Usage: msgexport -h imap-host -u user-name -m mailbox name\n";
12 print "--host IMAP host\n";
13 print "--user IMAP user name\n";
14 print "--mbox Folder name, set to '*' for all\n";
15 print "--file Output file\n";
20 $out = $GLOBALS['args']['file'] ? STDOUT : STDERR;
24 function progress_update($pos, $max)
26 $percent = round(100 * $pos / $max);
27 vputs(sprintf("%3d%% [%-51s] %d/%d\033[K\r", $percent, @str_repeat('=', $percent / 2) . '>', $pos, $max));
30 function export_mailbox($mbox, $filename)
34 $IMAP->set_mailbox($mbox);
36 vputs("Getting message list of {$mbox}...");
37 vputs($IMAP->messagecount()." messages\n");
41 if (!($out = fopen($filename, 'w')))
43 vputs("Cannot write to output file\n");
46 vputs("Writing to $filename\n");
51 for ($count = $IMAP->messagecount(), $i=1; $i <= $count; $i++)
53 $headers = $IMAP->get_headers($i, null, false);
54 $from = current($IMAP->decode_address_list($headers->from, 1, false));
56 fwrite($out, sprintf("From %s %s UID %d\n", $from['mailto'], $headers->date, $headers->uid));
57 fwrite($out, $IMAP->conn->fetchPartHeader($mbox, $i));
58 fwrite($out, $IMAP->conn->handlePartBody($mbox, $i));
59 fwrite($out, "\n\n\n");
61 progress_update($i, $count);
63 vputs("\ncomplete.\n");
71 $args = get_opt(array('h' => 'host', 'u' => 'user', 'p' => 'pass', 'm' => 'mbox', 'f' => 'file')) + array('host' => 'localhost', 'mbox' => 'INBOX');
73 if ($_SERVER['argv'][1] == 'help')
78 else if (!$args['host'])
80 vputs("Missing required parameters.\n");
85 // prompt for username if not set
86 if (empty($args['user']))
89 $args['user'] = trim(fgets(STDIN));
92 // prompt for password
93 $args['pass'] = prompt_silent("Password: ");
97 $a_host = parse_url($args['host']);
100 $host = $a_host['host'];
101 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
102 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : 143);
106 $host = $args['host'];
110 // instantiate IMAP class
111 $IMAP = new rcube_imap(null);
113 // try to connect to IMAP server
114 if ($IMAP->connect($host, $args['user'], $args['pass'], $imap_port, $imap_ssl))
116 vputs("IMAP login successful.\n");
119 $mailboxes = $args['mbox'] == '*' ? $IMAP->list_mailboxes(null) : array($args['mbox']);
121 foreach ($mailboxes as $mbox)
124 $filename = preg_replace('/\.[a-z0-9]{3,4}$/i', '', $args['file']) . asciiwords($mbox) . '.mbox';
125 else if ($args['mbox'] == '*')
126 $filename = asciiwords($mbox) . '.mbox';
128 if ($args['mbox'] == '*' && in_array(strtolower($mbox), array('junk','spam','trash')))
131 export_mailbox($mbox, $filename);
136 vputs("IMAP login failed.\n");