Search code examples
phpemailsmtpimap

Is it possible to alter an email using PHP's IMAP functions?


I have no problem working with emails using PHP's IMAP functions, but I'd like to be able to alter messages physically and I'm just not sure it's possible. Has anyone had any success doing this?

i.e. I'd like to be able to change the subject line, or I'd like to permanently remove signatures, or ads from the body, etc.

So far the only way I can see is to:

  1. load a message
  2. gather up all of it's headers, etc.
  3. recreate the email using an email object of some sort and populate it with the old data
  4. Change the parts I want to change
  5. Delete the original message
  6. Save the new message**

** this is the only unknown here... do you know if it's possible to simply save a new message to a folder, or does it need to be received via SMTP?

If I can simply save, do I need to worry about the message's order number (the unique id within the folder context, simple integer), or will the folder simply re-sort based on the messages indicated send date?

Any insights would be greatly appreciated!


Solution

  • As pointed out by @Max in the OP comments, the IMAP function I was looking for was 'APPEND' and the corresponding PHP method is http://php.net/manual/en/function.imap-append.php

    The syntax is: bool imap_append ( resource $imap_stream , string $mailbox , string $message [, string $options = NULL [, string $internal_date = NULL ]] )

    There are examples in how to append a message to an IMAP folder in the reference page comments, but the basic example is as follows for adding a message to the 'INBOX.drafts' folder...

    imap_append($stream, "{imap.example.org}INBOX.Drafts"
                       , "From: me@example.com\r\n"
                       . "To: you@example.com\r\n"
                       . "Subject: test\r\n"
                       . "\r\n"
                       . "this is a test message, please ignore\r\n"
                       );
    

    ... with $stream being the connection handle. In my case I also want to include mime containers, which would be included in the concatenated $message, and would be appropriately encoded based on the content types.

    Hope that helps!