如何在PHP中使用IMAP获取电子邮件正文内容?

8

我无法获取电子邮件正文内容。

这是我的代码

<?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获取电子邮件时,电子邮件正文内容会显示出来,但是一旦我使用我的邮件服务器,我就无法获取电子邮件的正文内容。
你能帮我解决这个问题吗?

你使用的是哪个邮件服务器? - Ben
测试过了,你的脚本在 Gmail 上能够正常工作。错误很可能来自于你的邮件服务器。你还有其他细节可以提供吗? - Ben
可能是 https://dev59.com/mlTTa4cB1Zd3GeqPv9SF 的重复。 - dkarp
尝试使用 https://github.com/MonstaApps/PHP-IMAP-Fetcher。可以通过管道或获取电子邮件,将日志记录到MySQL并保存附件。 - Daniel Williams
2个回答

46

我找到了解决方案,

问题出在这一行代码上。

$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)

谢谢,我一直在寻找完全相同的东西...这也是检查文档的好方法哈哈...我只是从互联网上复制/粘贴了一个示例并期望它能工作... - Beto Aveiga
查找 fetch_structure,如果消息已编码,则需要解码。 - Andrew

0

Zeta Mail 组件允许更加 方便地从 IMAP 获取邮件POP,并且可以将传入的电子邮件解析为漂亮而干净的对象结构,以便您轻松处理。


1
他正在使用POP,而不是IMAP。请检查imap_open调用的第一个参数。 - dkarp
1
抱歉,我弄错了。不过,也可以使用POP:http://incubator.apache.org/zetacomponents/documentation/trunk/Mail/tutorial.html#retrieving-mail-using-pop3 - tobyS
1
我更新了我的答案以反映IMAP和POP都是可能的。 - tobyS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接