Page 1 of 1

search/replace or append in pre-existing MIME structure

Posted: Tue May 13, 2008 2:04 pm
by gmorehoudh
I'm using Swift to forward messages exactly as they are (not as attachments) by basically copying the existing body and the content-transfer-encoding and so forth. In limited testing, this has worked well.

Now, however, I have a need to either search and replace a string in the existing message structure (which is usually MIME, often multipart, in various encodings) or append another MIME piece at the bottom of the message with a custom URL in it. Is there any way to easily do this with Swift? To be clear, I'm not building the message in Swift, it's built by some other mailer (usually Apple Mail) and forwarded mostly intact through Swift.

I tried attaching a new Swift_Message_part, but this made the original message not appear in my mail reader because Swift then uses its own MIME boundary, not the one in the existing message, and so the original message becomes some weird glob and it just shows the appended part.

Here's some code. If you want to know how I got the body out or the content-type and content-transfer-encoding.. well, it's a lot longer, so just accept that they're usually correct. :P

Code: Select all

 
        // ternary operators here = FAIL?  if/else instead.  it works.
        if(!$content_type && !$content_transfer_encoding)
            $message =& new Swift_Message($subject, $body);
        elseif(!$content_type && $content_transfer_encoding)
            $message =& new Swift_Message($subject, $body, null, $content_transfer_encoding);
        elseif($content_type && !$content_transfer_encoding)
            $message =& new Swift_Message($subject, $body, $content_type);
        else
            $message =& new Swift_Message($subject, $body, $content_type, $content_transfer_encoding);        
            
    $message->setFlowed(false);
        
        // copy the original content-type attributes over
    if($content_type && $content_type_attributes) {         // can't set attributes if the header doesn't exist
        foreach($content_type_attributes as $attr => $val) {
        $message->headers->setAttribute("Content-Type", trim($attr), trim($val));
        }
    }
        
        // set reply-to path using constant
        $message->setReplyTo(REPLYTO);
 
I should say that this is all that's done to $body:

Code: Select all

 
    // fetch the raw body
        $body = imap_body($mbox, $msgno);
    
    // decode it if necessary
    if($content_transfer_encoding == "quoted-printable") {
        $body = imap_qprint($body);
    } elseif($content_transfer_encoding == "base64") {
        $body = imap_base64($body);
    }
 

Re: search/replace or append in pre-existing MIME structure

Posted: Tue May 13, 2008 2:10 pm
by gmorehoudh
PS I'd like to avoid fetching each MIME part via imap_fetchbody() and so forth and rebuilding the message if at all possible.