2011-03-03 16 views
6

我無法獲取電子郵件正文內容。如何在PHP中使用IMAP來獲取郵件正文內容?

這是我的代碼

<?php 
/* connect to server */ 
$hostname = '{myserver/pop3/novalidate-cert}INBOX'; 
$username = 'username'; 
$password = 'password'; 

/* try to connect */ 
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error()); 
//echo $inbox; 
/* grab emails */ 
$emails = imap_search($inbox,'ALL'); 


/* if emails are returned, cycle through each... */ 
if($emails) { 

    /* begin output var */ 
    $output = ''; 

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

    /* for every email... */ 
    foreach($emails as $email_number) { 
    //$email_number=$emails[0]; 
//print_r($emails); 
    /* get information specific to this email */ 
    $overview = imap_fetch_overview($inbox,$email_number,0); 
    $message = imap_fetchbody($inbox,$email_number,2); 

    /* output the email header information */ 
    $output.= '<div class="toggler '.($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; 
} 

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

當我使用從Gmail電子郵件獲取,顯示電子郵件的主體內容,但一旦我用我的郵件服務器,我無法獲取郵件的正文內容。

你能幫我解決這個問題嗎?

+0

你使用什麼郵件服務器? – Ben 2011-03-03 07:23:34

+0

經過測試;正如您所說,您的腳本可以正常使用Gmail。錯誤可能來自您的郵件服務器。有沒有其他細節可以提供? – Ben 2011-03-03 07:35:48

+0

可能是http://stackoverflow.com/questions/5170489/php5-imap-i-aint-got-no-body – dkarp 2011-03-03 15:31:48

回答

38

我已經找到了解決方案, 錯誤是此行

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

現在,我使用

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

要接收的text/html格式的正文內容

下面我有給出可用選項的數據集。這可能有一個

()Root Message Part (multipart/related) 
(1) The text parts of the message (multipart/alternative) 
(1.1) Plain text version (text/plain) 
(1.2) HTML version (text/html) 
(2) The background stationary (image/gif) 
+0

謝謝,我一直在尋找完全相同的東西......這就是爲什麼檢查文檔jaja也很好...我只是複製/粘貼來自互聯網的例子,並期望工作... – 2016-06-09 22:17:26

+0

look up fetch_structure,u需要解碼消息,如果它被編碼。 – Andrew 2017-09-15 13:23:46

0

Zeta Mail組件允許更多convenient fetching of mails from IMAPPOP,並且可以將傳入的電子郵件解析爲一個漂亮乾淨的對象結構,以便您輕鬆處理。

+1

他使用POP,而不是IMAP。檢查「imap_open」調用的第一個參數。 – dkarp 2011-03-03 15:36:26

+0

抱歉,弄錯了。但是,也適用於POP:http://incubator.apache.org/zetacomponents/documentation/trunk/Mail/tutorial.html#retrieving-mail-using-pop3 – tobyS 2011-03-03 15:47:25

+0

我更新了我的答案,以反映IMAP和POP都是可能的。 – tobyS 2011-03-03 15:59:26