- Php imap move folder
- Command Options
- Examples
- Move from Gmail to Google Apps
- Move from Source to Sub-Folder on Target
- Remove from Source
- Show Source Paths and Messages to Copy
- imap_mail_move
- Список параметров
- Возвращаемые значения
- Список изменений
- Примечания
- Смотрите также
- User Contributed Notes 13 notes
- Folder
- Check if the folder has sub folder
- Move a folder
- Delete a folder
- Idle connection
- Get folder detail
- Folder overview
Php imap move folder
When migrating email services one does not want to lose the old messages. This tool copies messages from one IMAP system to the other. We’ve used this to migrate from Exchange to Gmail/Google Apps, Gmail to Exchange, Exchange to Exchange, in or out of dovecot too.
Here is a sample script to get started
#!/bin/bash -x curl edoceo.com/pub/imap-move.php > imap-move.php php ./imap-move.php \ --source imap-ssl://userA@domain:secretA@imap.example.com:993/ \ --target imap-ssl://userB@domain:secretB@imap.example.com:993/sub-folder
Command Options
This IMAP copy script supports a few options.
—source A URI style pointer to the source IMAP mailbox —target A URI style pointer to the target IMAP mailbox —fake Will simply list the messages and folders that would be copyied —wipe Remove the messages from Source after they have been copied to Target
Examples
Here are a bunch of examples showing how to use imap-move.php
Move from Gmail to Google Apps
This copies from an Gmail style account to a Google Apps hosted domain duplicating folder structure
php ./imap-move.php \ -s imap-ssl://userA@gmail.com:secretA@imap.gmail.com:993/ \ -t imap-ssl://userB@domain.tld:secretB@imap.gmail.com:993/
Move from Source to Sub-Folder on Target
We can copy mail from for example old.com to our new email system, storing these old messages in a folder calld Archive This will also work with Google Mail systems as a target.
php ./imap-move.php \ -s imap-ssl://userA@old.com:secretA@imap.gmail.com:993/ \ -t imap-ssl://userB@new.com:secretB@imap.gmail.com:993/Archive
Remove from Source
php ./imap-move.php \ --wipe \ -s imap-ssl://userA@old.com:secretA@imap.gmail.com:993/ \ -t imap-ssl://userB@new.com:secretB@imap.gmail.com:993/Archive
Show Source Paths and Messages to Copy
php ./imap-move.php \ --fake \ -s imap-ssl://userA@old.com:secretA@imap.gmail.com:993/ \
imap_mail_move
Перемещает письма, заданные в message_nums в указанный почтовый ящик mailbox . Обратите внимание, что почтовые сообщения фактически копируются в mailbox , а исходные сообщения помечаются для удаления. Это означает, что сообщениям в mailbox назначаются новые UID.
Список параметров
message_nums — это диапазон, а не просто номера сообщений (как определено в » RFC2060).
Имя почтового ящика. Более подробно читайте в разделе, посвящённом функции imap_open()
Если imap.enable_insecure_rsh не отключён, то передача в этот параметр не проверенных данных не безопасна.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Список изменений
Примечания
Замечание:
Функция imap_mail_move() помечает оригинальное сообщение флагом удаления, так что не забудьте после неё вызвать функцию imap_expunge() .
Смотрите также
User Contributed Notes 13 notes
to get right the folders names for imap_mail_move/imap_mail_copy, do not guess, instead use imap_list
After using imap_mail_move, imap_mail_copy or imap_delete it is necesary to call imap_expunge() function.
I had the most trouble with figureing out what the message list was supposed to be. There was one comment by jan@showstar.com but i was still terribly confused. So I searched and searched and searched. I read rfc2060 over 10 times. Then BAM! My brother found it here:
Here is the importand stuff.
Another important field is the SEQUENCE, which identifies a set of messages by consecutive numbers from 1 to n where n is the number of messages in the mailbox. A sequence may consist of a single number, a pair of numbers delimited by colon (equivalent to all numbers between those two numbers), or a list of single numbers or number pairs. For example, the sequence 2,4:7,9,12:15 is equivalent to
2,4,5,6,7,9,12,13,14,15 and identifies all those messages.
There is what I know about it. BAM!
To copy/move a mail in Gmail to a particular Folder like Starred/Spam/Drafts/Trash
use the following statement and don’t forget to call CL_EXPUNGE or imap_expunge($mbox) after it.
imap_mail_copy ( $mbox , ’16’ , ‘[Gmail]/Starred’ ); // 16 is the message number, which can also be a range.(ex: ‘1:15’)
imap_close ( $mbox , CL_EXPUNGE );
?>
Incase u want to send it to a personally created Label/folder(ex: Test) use..
imap_mail_copy ( $mbox , ’16’ , ‘Test’ );
imap_expunge ( $mbox );
imap_close ( $mbox );
?>
To move mails via IMAP on an Exchange Server into «Gel?schte Objekte» use:
It took me some tcpdumping to get this out, since both
imap_utf7_encode and
imap_utf8
did not translate it right.
to complete the previous example, if the mbox/folders names are
INBOX
INBOX/draft
INBOX/test
and you want to copy/move from INBOX to INBOX/test this is the syntax:
$mbox = imap_open(«INBOX»,$mailuser,$mailpass)
or die(«can’t connect: «.imap_last_error());
.
imap_mail_move($mbox,$messageset,»INBOX/test»);
Be aware that this function returning TRUE doesn’t necessarily mean anything actually happened.
It counts as «success» if all messages matching the range you supply were moved; however that includes if there were _no_ matching messages to move.
So suppose you supply a sequence-number or UID that’s invalid, e.g. because it’s no longer present in the source folder:
$res = imap_mail_move ( $stream , ‘99999’ , ‘DestFolder’ , CP_UID );
var_dump ( $res ); // bool(true)
?>
It’s up to you to validate the desired message(s) before moving, and/or afterwards.
This function works, just not like everything else IMAP in PHP3. rather than feeding the server
I offer the following example because it took me HOURS to figure this out
$this -> mailInBox = imap_open ( $this -> mailConnectString . «INBOX» , $this -> accountLogin , $this -> accountPassword );
$this -> messageCount = imap_num_msg ( $this -> mailInBox );
echo «Processing » . $this -> messageCount . » messages:» ;
for ( $i = 1 ; $i messageCount ; ++ $i ) $header = imap_header ( $this -> mailInBox , $i );
$prettydate = date ( «jS F Y» , $header -> udate );
$fromHost = $header -> from [ 0 ]-> host ;
if (isset( $header -> from [ 0 ]-> personal )) $personal = $header -> from [ 0 ]-> personal ;
> else $personal = $header -> from [ 0 ]-> mailbox ;
>
$body = imap_fetchbody ( $this -> mailInBox , $i , «1.1» );
if ( $body == «» ) $body = imap_fetchbody ( $this -> mailInBox , $i , «1» );
>
$move = «INBOX.processed» . date ( «Ymd» );
echo «trying to move:» . $i . «
» ;
@ imap_mail_move ( $this -> mailInBox , $i , $move );
This keeps biting me time after time. A lot of IMAP servers with quotas don’t implement ‘move’ right — they do a ‘copy&delete’ instead and don’t recognize that this conflicts with their quota implementetions. So, if you try to move a large message, you’ll exceed your quota even though moving it does not increase the total size of your mailbox. This is not PHP-specific, but I bet it’ll bite someone else besides me, so here you go.
The syntax for the message list is defined in RFC2060
It is a string, containing a list of message numbers and ranges, separated by commas (no spaces anywhere.) For example, «1,2,5,11:15,19» would be accepted by imap_mail_copy or imap_mail_move.
A range of messages is defined as two message numbers separated by a colon (Ex. «1:10».) Also, a «*» may be used to refer to the last message in a mailbox. (Ex. «1:*» refers to all messages)
Be careful not to use the same mailbox for source and destination, especially if you expunge the mailbox immediately afterwards; the message will be copied (back over itself), flagged as deleted (by the imap_mail_move function), and then expunged.
The following code will move the messages in the $msg_no[] array from the folder in $mbox_name to the folder in $newmbox_name: ($mbox is an already-opened imap stream)
if ( $mbox_name != $newmbox_name ) <
reset ( $msg_no );
$messageset = implode ( «,» , $msg_no );
imap_mail_move ( $mbox , $messageset , $newmbox_name );
imap_expunge ( $mbox );
>
?>
This function copies the mail and then marks the source as deleted. In order to see the changes, you must imap_expunge the source box.
I’ve used a dot in
imap_mail_move($mbox,$movmsgid,’INBOX.send’);
instead of
INBOX/test
and it work’s fine.
- Функции IMAP
- imap_8bit
- imap_alerts
- imap_append
- imap_base64
- imap_binary
- imap_body
- imap_bodystruct
- imap_check
- imap_clearflag_full
- imap_close
- imap_create
- imap_createmailbox
- imap_delete
- imap_deletemailbox
- imap_errors
- imap_expunge
- imap_fetch_overview
- imap_fetchbody
- imap_fetchheader
- imap_fetchmime
- imap_fetchstructure
- imap_fetchtext
- imap_gc
- imap_get_quota
- imap_get_quotaroot
- imap_getacl
- imap_getmailboxes
- imap_getsubscribed
- imap_header
- imap_headerinfo
- imap_headers
- imap_is_open
- imap_last_error
- imap_list
- imap_listmailbox
- imap_listscan
- imap_listsubscribed
- imap_lsub
- imap_mail_compose
- imap_mail_copy
- imap_mail_move
- imap_mail
- imap_mailboxmsginfo
- imap_mime_header_decode
- imap_msgno
- imap_mutf7_to_utf8
- imap_num_msg
- imap_num_recent
- imap_open
- imap_ping
- imap_qprint
- imap_rename
- imap_renamemailbox
- imap_reopen
- imap_rfc822_parse_adrlist
- imap_rfc822_parse_headers
- imap_rfc822_write_address
- imap_savebody
- imap_scan
- imap_scanmailbox
- imap_search
- imap_set_quota
- imap_setacl
- imap_setflag_full
- imap_sort
- imap_status
- imap_subscribe
- imap_thread
- imap_timeout
- imap_uid
- imap_undelete
- imap_unsubscribe
- imap_utf7_decode
- imap_utf7_encode
- imap_utf8_to_mutf7
- imap_utf8
Folder
You can receive a new message search query by using one of the following methods. They all do the same — different names are available as aliases. Pick the one you like.
/** @var \Webklex\PHPIMAP\Folder $folder */ /** @var \Webklex\PHPIMAP\Query\WhereQuery $query */ $query = $folder->query(); $query = $folder->search(); $query = $folder->messages();
Check if the folder has sub folder
You can check if the current folder has any sub folders or «children».
/** @var \Webklex\PHPIMAP\Folder $folder */ /** @var boolean $status */ $status = $folder->hasChildren();
Move a folder
You can move a folder from its current location to any other currently not occupied location. This action might not be reversible!
/** @var \Webklex\PHPIMAP\Folder $folder */ /** @var boolean $status */ $status = $folder->move($new_folder = "INBOX/othername"); $status = $folder->rename($new_folder = "INBOX/othername");
Delete a folder
You can delete a folder from its current location. This action might not be reversible!
/** @var \Webklex\PHPIMAP\Folder $folder */ /** @var boolean $status */ $status = $folder->delete();
Idle connection
You can idle the connection and «listen» for new incoming messages. Set $auto_reconnect to true if you want to automatically reconnect if your connection broke.
/** @var \Webklex\PHPIMAP\Folder $folder */ $folder->idle(function($message)< echo "New message with the subject '".$message->subject."' received\n"; >, $timeout = 1200, $auto_reconnect = false);
Get folder detail
You can receive basic information about the current folder. These include the number of messages, the next uid and a list off all available flags.
/** @var \Webklex\PHPIMAP\Folder $folder */ /** @var array $info */ $info = $folder->examine();
array:5 [ "flags" => array:1 [ 0 => array:6 [ 0 => "\Answered" 1 => "\Flagged" 2 => "\Deleted" 3 => "\Seen" 4 => "\Draft" ] ] "exists" => "65" "recent" => "0" "uidvalidity" => 1488899637 "uidnext" => 202 ]
Folder overview
Get a quick overview of all messages in the current folder matching a given sequence. The default sequence «1:*» will fetch all messages beginning by the first.
/** @var \Webklex\PHPIMAP\Folder $folder */ /** @var array $overview */ $overview = $folder->overview($sequence = "1:*");
array:65 [ . 201 => array:27 [ "from" => array:1 [ …1] "to" => array:1 [ …1] "cc" => array:2 [ …2] "reply_to" => array:1 [ …1] "sender" => array:1 [ …1] "subject" => "message subject" "message_id" => "3ff121ba-f40e-6df9-cdc2-379aee6b9e36@somehost.com" "date" => Carbon\Carbon "return_path" => "" "received" => array:16 [ …16] "x_virus_scanned" => "Debian amavisd-new at mx1.somehost.com" "x_spam_flag" => "NO" "x_spam_score" => "-2.9" "x_spam_level" => "" "x_spam_status" => "No, score=-2.9 required=6.31 tests=[ALL_TRUSTED=-1, BAYES_00=-1.9] autolearn=ham autolearn_force=no" "autocrypt" => array:43 [ …43] "user_agent" => "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.10.0" "mime_version" => "1.0" "content_type" => "text/plain" "content_transfer_encoding" => "8bit" "content_language" => "en-GB" "toaddress" => "Someone Somewhere " "fromaddress" => "Someone Somewhere " "ccaddress" => "'Someone Somewhere' , test@somehost.com" "reply_toaddress" => "Someone Somewhere " "senderaddress" => "Someone Somewhere " "charset" => "utf-8" ] ]