Подтвердить что ты не робот

Сообщения об ошибках PHP IMAP

У меня есть электронные письма, отправленные через кодировку base64 и 8-битную кодировку. Мне было интересно, как я могу проверить кодировку сообщения с помощью imap_fetchstructure (делал это примерно два часа, поэтому потерялся), а затем правильно декодировал его.

Gmail и почтовый ящик (приложение на iOS) отправляют его как 8 бит, а приложение для Windows 8 Mail отправляет его как base64. В любом случае, мне нужно декодировать, может ли его 8 бит или base64 определить, какой тип кодировки он использовал.

Использование PHP 5.1.6 (да, я должен обновить, был занят).

У меня действительно нет кода для показа. Это все, что у меня есть:

<?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);
        $message = imap_fetchbody($inbox,$email_number,2);
        $struct = imap_fetchstructure($inbox, $email_number);

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

        /* output the email body */
        $output.= '<div class="body">'.$message.'</div>';
    }

    echo $output;
} 

imap_close($inbox);
?>
4b9b3361

Ответ 1

imap_bodystruct() или imap_fetchstructure() должны вернуть эту информацию вам. Следующий код должен делать именно то, что вы ищете:

<?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);
?>

Ответ 2

Вы можете посмотреть этот пример.

Imap/Imap

Здесь фрагмент кода

switch ($encoding) {
    # 7BIT
    case 0:
        return $text;
    # 8BIT
    case 1:
        return quoted_printable_decode(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;
}

Ответ 3

Возвращенные объекты для imap_fetchstructure()

  • кодирование (кодирование передачи тела)

Передача кодировок (может отличаться от используемой библиотеки)

0 7BIT 1 8BIT 2 БИНАРЫ 3 BASE64 4 QUOTED-PRINTABLE 5 OTHER

$s = imap_fetchstructure($mbox,$mid);
if ($s->encoding==3)
    $data = base64_decode($data);

Ответ 4

            // Best for reading attached file from e-mail as well as body of the mail
            $hostname = '{imap.gmail.com:993/imap/ssl}Inbox';
            $username = '[email protected]';
            $password = '****************';

            $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());  
            $emails   = imap_search($inbox, 'SUBJECT "'.$subject.'"');
            rsort($emails);
            foreach ($emails as $key => $value) {

                $overview = imap_fetch_overview($inbox,$value,0);
                $message_date = new DateTime($overview[0]->date);
                $date = $message_date->format('Ymd');
                $message = imap_fetchbody($inbox,$value,2);
                $structure = imap_fetchstructure($inbox, $value);
                $attachments = [];
                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, $value, $i+1);                           
                            if($structure->parts[$i]->encoding == 3) //3 = BASE64 encoding
                            { 
                                $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                            }
                            elseif($structure->parts[$i]->encoding == 4) //4 = QUOTED-PRINTABLE encoding
                            { 
                                $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                            }
                        }
                    }
                }
            }
            imap_close($inbox);//Never forget to close the connection