Simple way to forward emails using PHP IMAP

910 Views Asked by At

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.

1

There are 1 best solutions below

4
On

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);