Question

after searching and trying solutions here for quite some time I couldn't find a fix for my problem, although it did fix one of the messages..

Anyways to the point, im currently using the imap function in PHP to get Gmail e-mails and so far it worked with 2 messages, but the other messages are still encoded or wrongly decoded and I can't find where I did something wrong, my current code:

<?php

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '******@*******.com';
$password = '*******';


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


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

$max = 5;
$i = 0;

if($emails) {

    $output = '';

    rsort($emails);

    foreach($emails as $email_number) {

        if($i === $max) {
            break;
        }

        $overview = imap_fetch_overview($inbox,$email_number, 0);
        $structure = imap_fetchstructure($inbox, $email_number);

        $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
        if (isset($overview[0]->subject)) {
            $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
        }else{
            $output.= '<span class="subject">No subject</span> ';
        }
        $output.= '<span class="from">'.$overview[0]->from.'</span>';
        $output.= '<span class="date">on '.$overview[0]->date.'</span>';
        $output.= '</div>';

        $message = imap_fetchbody($inbox, $email_number, 2);

        if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
            $part = $structure->parts[1];
            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="body">'.utf8_encode($message).'</div>';
        $i++;
    }

    echo $output;
} 

imap_close($inbox);

?>

Output: http://www.mupload.nl/img/7pn51ldwpxj.png

Thanks alot upfront!

Was it helpful?

Solution 2

You've likely selected the wrong body part for those messages. Those are binary files: one is a GIF file (see the GIF89 header), and the other is a ZIP file (see the PK header).

OTHER TIPS

I'm using the Gmail PHP SDK for opening emails.
PHP Gmail Client Library

You can't just base64 decode the body, because Gmail base64 needs to be "cleaned up". If you just use base64_decode, you will find that the body is still full of weird characters.

$body_data = strtr($parts[0]["modelData"]["body"]["data"], '-_', '+/=');
$message_body = base64_decode($body_data);

I got this solution for base64 decoding from Stackoverflow 'Mark as read mail method'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top