I'm writing a script that will get all the new emails in different accounts on the same server, check for keywords and then move each email to different account and folder in that account depending on the keywords found. I've been looking for a simple way to move the emails from one account to another, and to a folder in that account. There doesn't seem to be a simple imap_forward() function. imap_mail_move() only works within the same account. I've been searching the internet for hours looking for a way to do this without having to loop through attachments and fetching each part of the email before sending it to the destination address like I would a new email. I need to make sure no info gets lost during this process and the email arrives at the destination exactly the same as it was initially received. It can look like a forwarded message, that's fine, as long as the attachments, from address and body are intact.
Asked
Active
Viewed 786 times
1 Answers
0
If you also have IMAP access to the destination mailbox, you can have two IMAP connections open simultaneously. Use one connection to read the message from the source account and the other to imap_append()
it to the destination account.
You'll have to manually re-build the message headers, but that should be pretty simple, looks like you can just do this:
$newMessage = imap_headers($sourceStream) . "\r\n" . imap_body($sourceStream)
imap_append($destinationStream, $destinationMailbox, $newMessage);

Alex Howansky
- 50,515
- 8
- 78
- 98
-
You should be able to just fetch the whole RFC822 body and just reupload it (without getting any subparts) – Max Nov 05 '19 at 19:22
-
@Max I was thinking the same but I don't see a function that returns the whole message. It's not clear if that's what `imap_body()` does. – Alex Howansky Nov 05 '19 at 19:25
-
imap_headers() returns headers for all messages in a mailbox. I need to move each message one by one, with their corresponding headers. How would this work for each email? – Suzanne Edelman Nov 06 '19 at 10:13
-
[`imap_fetchheader()`](https://www.php.net/manual/en/function.imap-fetchheader.php)? – Alex Howansky Nov 06 '19 at 14:07