php - четене на имейл от Gmail

Имам малък PHP проблем с четене на имейли от Gmail. Проблемът е с кирилицата. Когато изпратя писмо до моята Gmail поща от abv.bg - резултата при прочитането на имейла е следния:

Subject: Проба със
Body: Тестване със специални знаци
smiley.gif

From: Борислав Развански
Date: Fri, 18 Nov 2016 19:28:09 +0200 (EET)
Имайл: [email protected]


НО когато изпратя имейл до моята Gmail поща от друга gmail поща - резултата е следния:

Subject: Проверка от гмейл
Body: PGRpdiBkaXI9Imx0ciI+0JTQsNC90L4g0L/RgNC+0LLQtdGA0LrQsNGC0LAg0LTQsCDQvNC40L3Q tS48YnI+PC9kaXY+DQo
From: Елена Иванова
Date: Fri, 18 Nov 2016 19:50:03 +0200
Имайл: [email protected]


Тук реда - Body: PGRpdiBkaXI9Imx0ciI+0JTQsNC90L4g0L/RgNC+0LLQtdGA0LrQsNGC0LAg0LTQsCDQvNC40L3Q tS48YnI+PC9kaXY+DQo
Трябва да се визуализира като - Body: Дано проверката да мине.

Въпроса ми е: Защо при получаване на имейл от Gmail поща Body-то на имейла го енкодва (или нещо подобно), а когато получа имейл от abv-поща кода ми прочита нормално писмото и го визуализира добре?

Ето го и кода:
Код:
<html>
    <head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
        <title>Read Mail</title>
    </head>
    <body>

PHP:
/* Create gmail connection */
        $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
        $username = '[email protected]';
        $password = 'pass';
        $inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());

        /* Fetch emails */
        $emails = imap_search($inbox, "UNSEEN");

        /* If emails are returned, cycle through each... */
        if ($emails) {
            $output = '';

            /* Make the newest emails on top */
            rsort($emails);

            /* For each email... */
            foreach ($emails as $email_number) {

                $headerInfo = imap_headerinfo($inbox, $email_number);

                $fromaddr = $headerInfo->from[0]->mailbox . "@" . $headerInfo->from[0]->host;

                $structure = imap_fetchstructure($inbox, $email_number);


                /* get information specific to this email */
                $overview = imap_fetch_overview($inbox, $email_number, 0);

                /* get mesage body */
                $message = quoted_printable_decode(imap_fetchbody($inbox, $email_number, 2));

                /*
                  // If attachment found use this one
                  // $message = imap_qprint(imap_fetchbody($inbox,$email_number,"1.2"));
                 */

                $output .= 'Subject: ' . imap_utf8($overview[0]->subject) . '<br />';
                $output .= 'Body: ' . imap_utf8($message) . '<br />';
                $output .= 'From: ' . imap_utf8($overview[0]->from) . '<br />';
                $output .= 'Date: ' . imap_utf8($overview[0]->date) . '<br />';
                $output .= 'Имайл: ' .$fromaddr. '<br /><br />';
                //$output .= 'CC: ' . $headerInfo->ccaddress . '<br />'; - 

//  Attachments
                $attachments = array();
                if (isset($structure->parts) && count($structure->parts)) {
                    for ($i = 0; $i < count($structure->parts); $i++) {
                        $attachments[$i] = array(
                            'is_attachment' => false,
                            'filename' => '',
                            'name' => '',
                            'attachment' => ''
                        );

                        if ($structure->parts[$i]->ifdparameters) {
                            foreach ($structure->parts[$i]->dparameters as $object) {
                                if (strtolower($object->attribute) == 'filename') {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['filename'] = $object->value;
                                }
                            }
                        }

                        if ($structure->parts[$i]->ifparameters) {
                            foreach ($structure->parts[$i]->parameters as $object) {
                                if (strtolower($object->attribute) == 'name') {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['name'] = $object->value;
                                }
                            }
                        }

                        if ($attachments[$i]['is_attachment']) {
                            $attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i + 1);

                            /* 3 = BASE64 encoding */
                            if ($structure->parts[$i]->encoding == 3) {
                                $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                            }
                            /* 4 = QUOTED-PRINTABLE encoding */ elseif ($structure->parts[$i]->encoding == 4) {
                                $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                            }
                        }
                    }
                }

                foreach ($attachments as $attachment) {
                    if ($attachment['is_attachment'] == 1) {
                        $filename = $attachment['name'];
                        if (empty($filename))
                            $filename = $attachment['filename'];
                        $file_path = 'upload/'; //  Upload folder
                        $fp = fopen($file_path . $filename, "w+");
                        fwrite($fp, $attachment['attachment']);
                        fclose($fp);
                    }
                }
//  Attachments

                /* change the status */
                $status = imap_setflag_full($inbox, $overview[0]->msgno, "\Seen \Flagged");
            }

            echo $output;
        }

        /* close the connection */
        imap_close($inbox);

Код:
</body>
</html>
 
По default Gmail не използва UTF-8. И imap_utf8() няма как да ти свърши работа в случая. Трябва да проверяваш енкодинга на съобщението предварително.
EEQ9gBN5-mailg1-s-.png
 
По default Gmail не използва UTF-8. И imap_utf8() няма как да ти свърши работа в случая. Трябва да проверяваш енкодинга на съобщението предварително.
EEQ9gBN5-mailg1-s-.png

Абсолютно сте прав! Ето и версия на работещия код:

PHP:
/* Create gmail connection */
        $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
        $username = '[email protected]';
        $password = 'pass';
        $inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());

        /* Fetch emails */
        $emails = imap_search($inbox, "UNSEEN");

        /* If emails are returned, cycle through each... */
        if ($emails) {
            $output = '';

            /* Make the newest emails on top */
            rsort($emails);

            /* For each email... */
            foreach ($emails as $email_number) {

                $headerInfo = imap_headerinfo($inbox, $email_number);

                //показва имейл адреса
                $fromaddr = $headerInfo->from[0]->mailbox . "@" . $headerInfo->from[0]->host;

                $structure = imap_fetchstructure($inbox, $email_number);

                /* get mesage body */
                $overview = imap_fetch_overview($inbox, $email_number, 0);

                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 = quoted_printable_decode(imap_fetchbody($inbox, $email_number, 2));
                    }
                }

                /* get information specific to this email */

                /*
                  // If attachment found use this one
                  // $message = imap_qprint(imap_fetchbody($inbox,$email_number,"1.2"));
                 */

                $output .= 'Subject: ' . imap_utf8($overview[0]->subject) . '<br />';
                $output .= 'Body: ' . $message . '<br />';
                $output .= 'From: ' . imap_utf8($overview[0]->from) . '<br />';
                $output .= 'Date: ' . imap_utf8($overview[0]->date) . '<br />';
                $output .= 'Имeйл: ' .$fromaddr. '<br /><hr />';
                //$output .= 'CC: ' . $headerInfo->ccaddress . '<br />'; -

//  Attachments
                $attachments = array();
                if (isset($structure->parts) && count($structure->parts)) {
                    for ($i = 0; $i < count($structure->parts); $i++) {
                        $attachments[$i] = array(
                            'is_attachment' => false,
                            'filename' => '',
                            'name' => '',
                            'attachment' => ''
                        );

                        if ($structure->parts[$i]->ifdparameters) {
                            foreach ($structure->parts[$i]->dparameters as $object) {
                                if (strtolower($object->attribute) == 'filename') {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['filename'] = $object->value;
                                }
                            }
                        }

                        if ($structure->parts[$i]->ifparameters) {
                            foreach ($structure->parts[$i]->parameters as $object) {
                                if (strtolower($object->attribute) == 'name') {
                                    $attachments[$i]['is_attachment'] = true;
                                    $attachments[$i]['name'] = $object->value;
                                }
                            }
                        }

                        if ($attachments[$i]['is_attachment']) {
                            $attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i + 1);

                            /* 3 = BASE64 encoding */
                            if ($structure->parts[$i]->encoding == 3) {
                                $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                            }
                            /* 4 = QUOTED-PRINTABLE encoding */ elseif ($structure->parts[$i]->encoding == 4) {
                                $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                            }
                        }
                    }
                }

                foreach ($attachments as $attachment) {
                    if ($attachment['is_attachment'] == 1) {
                        $filename = $attachment['name'];
                        if (empty($filename))
                            $filename = $attachment['filename'];
                        $file_path = 'upload/'; //  Upload folder
                        $fp = fopen($file_path . $filename, "w+");
                        fwrite($fp, $attachment['attachment']);
                        fclose($fp);
                    }
                }
//  Attachments

                /* change the status */
                $status = imap_setflag_full($inbox, $overview[0]->msgno, "\Seen \Flagged");
            }

            echo $output;
        }

        /* close the connection */
        imap_close($inbox);
 

Горе