首页 > 解决方案 > 从 imap_open 修剪在电子邮件正文中添加的其他换行符

问题描述

在使用 PHP 的函数时,我正在使用以下函数来检索电子邮件的正文imap_open

它被简单地称为$email_body = getBody($email_number, $inbox);

它工作得非常好,但有时我遇到的一个问题是带有换行符的电子邮件最终会添加额外的换行符。

我可以尝试添加额外的换行符吗?

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

function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
    if (!$structure) {
        //$structure = imap_fetchstructure($imap, $uid, FT_UID);
        $structure = imap_fetchstructure($imap, $uid);
    }
    //var_dump($structure);
    if ($structure) {
        if ($mimetype == get_mime_type($structure)) {
            if (!$partNumber) {
                $partNumber = 1;
            }
            //$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
            $text = imap_fetchbody($imap, $uid, $partNumber);
            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 = get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
}

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

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

标签: php

解决方案


您可以使用删除所有额外的新行preg_replace

preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $your_email_body);

推荐阅读