2015-06-22 81 views
3

我有一个使用PHP IMAP从G-mail检索电子邮件的功能。该功能每次都会从Gmail帐户中删除邮件,但在日本语言中解码主题和日期仍然存在问题。完全用于解码它的消息。所以我想问你,如何解码主题以便用PHP读取。如何解码从gmail检索的主题和日期(日本文本)

这里是我的功能:

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

和结果(不正确):

enter image description here

谁能告诉我哪个函数在PHP可以解决这个问题。

问候,

+0

仅供参考,在日本的人不要使用Unicode和倾向于使用ISO-2022-JP(用于电子邮件)。我不太了解PHP给你的功能,但如果你试图将它解码为unicode,那很失败。 – meneldal

+0

谢谢,我们来看看PHP中的ISO-2022-JP。 – Samphors

回答

2
public function encodeToUtf8($string) { 
     mb_internal_encoding("utf-8"); 
     $str_japan = mb_convert_encoding($string, "UTF-8", "ISO-2022-JP"); 
     //"=?iso-2022-jp?B?GyRCQjZCPjhsOEBCLDtuGyhCIC0gdGVzdGluZw==?="; 
     return mb_decode_mimeheader($str_japan); 
} 

用法:

encodeToUtf8($overview[0]->date); 
encodeToUtf8($overview[0]->subject);