php - 从 imap_open 修剪在电子邮件正文中添加的额外换行符

标签 php

我正在使用以下函数来检索电子邮件正文,同时使用 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";
}

最佳答案

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

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

关于php - 从 imap_open 修剪在电子邮件正文中添加的额外换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61089338/

相关文章:

javascript - for 循环在自动完成内不起作用

php - 用 preg_replace 包裹 <b> 标签中的第一个单词——不能引用全字符串匹配

php - 如何在 PHP MySQL 中查找任何节点的子节点?

php - Mysql 时间戳和 php date()

php - 比较从数据库返回的值与 json 返回的值

php - 博客文章评论无需刷新页面(ajax)

javascript - 是否可以根据按钮名称将表单的值从按钮提交到两个页面?

php - 同一页面上有两个ajax,但第二个没有得到第一个已更改的内容

php - 如何在 MySQLi 中为我的数据库创建表

php - WHERE 子句中的 MySQL RAND() 匹配一小组行