0

I am working on mailbox using imap php. I am using imap_fetchbody($mbox, 4,2) to read the contents of mail. It works fine for normal text messages but when the email has inline images (not attachment) or html template its not working properly. It simply returns some encrypted code. I referred many codes. The one i used is:

$mbox = imap_open($hostname,$username,$password) 
        or die('Cannot connect to Gmail: ' .       imap_last_error());
$message=imap_fetchbody($mbox, 4,2);
$decoded_data = base64_decode($message);
file_put_contents('image002.jpg',$decoded_data); 
<img src="image002.jpg">   

It fetches the inline image but if the mail has more than one inline image it returns only the last image.I don't have any idea on how to get the html template message can anyone help me?

Remko
  • 968
  • 6
  • 19
Sam
  • 1
  • 1
  • There are many examples how to deal with multipart messages in the comments of [imap_fetchstructure()](http://php.net/manual/en/function.imap-fetchstructure.php). – syck Oct 30 '15 at 10:00

2 Answers2

0

This post will help you out as it did for me! You could do strip_tags($message) to get only the text. Hope that helps

Community
  • 1
  • 1
STIKO
  • 1,995
  • 1
  • 10
  • 9
0

<?php
$hostname = '{********:993/imap/ssl}INBOX';
$username = '*********';
$password = '******';

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to server: ' . imap_last_error());

$emails = imap_search($inbox,'ALL');

if($emails) {
    $output = '';
    rsort($emails);

    foreach($emails as $email_number) {
        $overview = imap_fetch_overview($inbox,$email_number,0);
        $structure = imap_fetchstructure($inbox, $email_number);

        if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
            $part = $structure->parts[1];
            $message = imap_fetchbody($inbox,$email_number,2);

            if($part->encoding == 3) {
                $message = imap_base64($message);
            } else if($part->encoding == 1) {
                $message = imap_8bit($message);
            } else {
                $message = imap_qprint($message);
            }
        }

        $output.= '<div class="toggle'.($overview[0]->seen ? 'read' : 'unread').'">';
        $output.= '<span class="from">From: '.utf8_decode(imap_utf8($overview[0]->from)).'</span>';
        $output.= '<span class="date">on '.utf8_decode(imap_utf8($overview[0]->date)).'</span>';
        $output.= '<br /><span class="subject">Subject('.$part->encoding.'): '.utf8_decode(imap_utf8($overview[0]->subject)).'</span> ';
        $output.= '</div>';

        $output.= '<div class="body">'.$message.'</div><hr />';
    }

    echo $output;
}

imap_close($inbox);
?>