php - 如何从 imap_body 结果中仅提取 HTML

标签 php html imap

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

最佳答案

我找到了一个解决方案:

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";
}

关于php - 如何从 imap_body 结果中仅提取 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491061/

相关文章:

html - 嵌入到 HTML 中的视频无法播放

javascript - 隐藏了错误的盒子

php - 使用 PHP IMAP 类时损坏的 .docx 文件

php - 如何使用 PHP 和 AJAX 显示 MySQL 数据库

php - 让 PHP 执行 shell 脚本的正确且安全的方法

php - MySQLi CREATE 表查询不工作

php - 加密是否可以防止 sql 注入(inject)?

html5 block 链接样式问题

node.js - 使用 Node.js 进行 Imap,将电子邮件标记为已读

php - 7bit 和 8bit 编码的消息在输出之前必须解码吗?