【问题标题】:How to extract only HTML from imap_body result如何从 imap_body 结果中仅提取 HTML
【发布时间】:2014-10-18 21:46:59
【问题描述】:

我只想从 imap_body 结果中提取 HTML 内容。 imap_body 给出邮件的逐字副本。

【问题讨论】:

标签: php html imap


【解决方案1】:

我找到了解决办法:

function getBody($uid, $imap)
{
    $body = $this->get_part($imap, $uid, "TEXT/HTML");
    // if HTML body is empty, try getting text body
    if ($body == "") {
        $body = $this->get_part($imap, $uid, "TEXT/PLAIN");
    }
    return $body;
}

function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false)
{
    if (!$structure) {
        $structure = imap_fetchstructure($imap, $uid, FT_UID);
    }
    if ($structure) {
        if ($mimetype == $this->get_mime_type($structure)) {
            if (!$partNumber) {
                $partNumber = 1;
            }
            $text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
            switch ($structure->encoding) {
                case 3:
                    return imap_base64($text);
                case 4:
                    return imap_qprint($text);
                default:
                    return $text;
            }
        }

        // multipart
        if ($structure->type == 1) {
            foreach ($structure->parts as $index => $subStruct) {
                $prefix = "";
                if ($partNumber) {
                    $prefix = $partNumber . ".";
                }
                $data = $this->get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
}

function get_mime_type($structure)
{
    $primaryMimetype = ["TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"];

    if ($structure->subtype) {
        return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
    }
    return "TEXT/PLAIN";
}

【讨论】:

  • 很好的解决方案!
  • 完美输出HTML
【解决方案2】:

http://php.net/manual/en/function.imap-fetchbody.php

参数3,“节”如下:

部件号。它是由句点分隔的整数字符串,根据 IMAP4 规范索引到正文部分列表中

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - file.ext

因此,要获取邮件的 HTML 部分,您必须使用 1.2 选项作为第三个参数。像这样:

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

【讨论】:

  • 这仅适用于 /if/ 消息遵循此结构。许多电子邮件没有,如果包含附件,它们也不会遵循这种结构。最好的方法是解析 bodystructure 找到你想要的 HTML 部分。
  • 感谢您的回答。不幸的是,我尝试了这种方法,但没有奏效。
  • @Max 你能帮我介绍一下身体结构的方法吗?
  • imap_fetchbody($inbox, $number, 2); 为我工作
【解决方案3】:

我没有足够的声誉来添加评论,但我只是想在@GunniH 的回答中澄清您对该函数的调用应该如下所示:

$message = imap_fetchbody($inbox, $number, '1.2');

而不是这个

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

最后一个参数应该是string,而不是int

【讨论】:

  • 1.2 不是 int 而是 float。但是两个输入都应该有效。
  • imap_fetchbody($inbox, $number, 2); 为我工作
猜你喜欢
  • 2020-03-26
  • 2011-08-16
  • 2019-04-24
  • 2019-10-21
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
相关资源
最近更新 更多