Search code examples
phpcodeigniterimapphp-imap

IMAP PHP with embedded images not showing Codeigniter on localhost


I use codeigniter and imap php currently developing project xampp. For some reason them embedded images not showing.

In my getBody() function I have this call back

$body = preg_replace_callback(
        '/src="cid:(.*)">/Uims',
        function($m) use($email, $uid){
            //split on @
            $parts = explode('@', $m[1]);
            //replace local path with absolute path
            $img = str_replace($parts[0], '', $parts[0]);
            return "src='$img'>";
       },
    $body);

enter image description here

enter image description here

I get error

enter image description here

Question: How can I make sure it gets the images correct for the text/html body etc.

<?php

class Email extends MY_Controller {

    private $enc;
    private $host;
    private $user;
    private $pass;
    private $mailbox;
    private $mbox;

    public function __construct() {
        parent::__construct();

        $this->enc = '/imap/ssl/novalidate-cert';
        $this->host = '****';
        $this->user = '****'; // email
        $this->pass = '****'; // Pass

        $this->mailbox = '{' . $this->host . $this->enc . '}';
        $this->mbox = imap_open($this->mailbox, $this->user, $this->pass);
    }

    public function view() {

        $this->data['message'] = $this->getBody($this->uri->segment(4));

        $this->load->view('template/common/header', $this->data);
        $this->load->view('template/common/nav', $this->data);
        $this->load->view('template/mail/view', $this->data);
        $this->load->view('template/common/footer', $this->data);

        imap_close($this->mbox);
    }

    public function getBody($uid) {
        $body = $this->get_part($uid, "TEXT/HTML");
        // if HTML body is empty, try getting text body
        if ($body == "") {
            $body = $this->get_part($uid, "TEXT/PLAIN");
        }

        $email = $this->user;

        //replace cid with full path to image
        $body = preg_replace_callback(
            '/src="cid:(.*)">/Uims',
            function($m) use($email, $uid){
                //split on @
                $parts = explode('@', $m[1]);
                //replace local path with absolute path
                $img = str_replace($parts[0], '', $parts[0]);
                return "src='$img'>";
           },
        $body);

        return trim(utf8_encode(quoted_printable_decode($body)));
    }    

    private function get_part($uid, $mimetype, $structure = false, $partNumber = false) {
        if (!$structure) {
               $structure = imap_fetchstructure($this->mbox, $uid);
        }
        if ($structure) {
            if ($mimetype == $this->get_mime_type($structure)) {
                if (!$partNumber) {
                    $partNumber = 1;
                }
                $text = imap_fetchbody($this->mbox, $uid, $partNumber, FT_PEEK);
                switch ($structure->encoding) {
                    # 7BIT
                    case 0:
                        return imap_qprint($text);
                    # 8BIT
                    case 1:
                        return imap_8bit($text);
                    # BINARY
                    case 2:
                        return imap_binary($text);
                    # BASE64
                    case 3:
                        return imap_base64($text);
                    # QUOTED-PRINTABLE
                    case 4:
                        return quoted_printable_decode($text);
                    # OTHER
                    case 5:
                        return $text;
                    # UNKNOWN
                    default:
                        return $text;
                }
           }
            // multipart
            if ($structure->type == 1) {
                foreach ($structure->parts as $index => $subStruct) {
                    $prefix = "";
                    if ($partNumber) {
                        $prefix = $partNumber . ".";
                    }
                    $data = $this->get_part($uid, $mimetype, $subStruct, $prefix . ($index + 1));
                    if ($data) {
                        return $data;
                    }
                }
            }
        }
        return false;
    }

    private function get_mime_type($structure) {
        $primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
        if ($structure->subtype) {
           return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
        }
        return "TEXT/PLAIN";
    }

}

Solution

  • Introduction

    You are trying to convert an Email into a HTML Page.

    An Email has multiple parts:

    1. Headers
    2. Text based email
    3. HTML based email
    4. Attachments

    In the header you will find the Message-ID as well as other relevant metadata.

    In order to convert an Email into a website you have to expose the HTML and the Attachments to the browser.

    Each of the Parts has its own headers. When you have a url='cid:Whatever' you have to look for which part of the email hast that Content-Id header.

    Serve the Email as a Web Page

    You need to find wich Email part contains the HTML Body. Parse it and replace the CID URL's for your http://yourhost/{emailId} you already implemented that part so I will not add how to do it here.

    Replace CID URL on HTML - Implementation

    This is a prototype that may work for you.

    $mailHTML="<html>All your long code here</html>";
    $mailId="email.eml";
    $generatePartURL=function ($messgeId, $cid) {
        return "http://myhost/".$messgeId."/".$cid; //Adapt this url according to your needs
    };
    $replace=function ($matches) use ($generatePartURL, $mailId) {
        list($uri, $cid) = $matches;
        return $generatePartURL($mailId, $cid);
    };
    $mailHTML=preg_replace_callback("/cid:([^'\" \]]*)/", $replace, $mailHTML);
    

    Find the part by CID

    http://yourhost/{emailId}/{cid}

    Pseudo code:

    • Load email
    • Find part by CID
    • Decode from Base64 or other Encoding used (Check Content-Transfer-Encoding header)
    • Serve the file as an HTTP Response

    Which part has my CID image?

    Iterate all email parts looking for the Content-ID header that match your CID value.

    --_part_boundery_
    Content-Type: image/jpeg; name="filename.jpg"
    Content-Description: filename.jpg
    Content-Disposition: inline; filename="filename.jpg"; size=39619; creation-date="Thu, 28 Dec 2017 10:53:51 GMT"; modification-date="Thu, 28 Dec 2017 10:53:51 GMT"
    Content-ID: <YOUR CID WILL BE HERE>
    Content-Transfer-Encoding: base64
    

    Decode the transfer encoding and serve the contents as a regular http file.

    Webmail implemented in PHP

    RoundCube is a webmail implemented in PHP you can have a look how they do this: https://github.com/roundcube/roundcubemail/blob/master/program/lib/Roundcube/rcube_washtml.php

    Note: My code it is not based in this solution.