Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim additional line breaks being added in email body from imap_open

Tags:

php

I am using the following functions to retrieve the body of emails while using PHP's imap_open function.

it's called simply by $email_body = getBody($email_number, $inbox);

It works really well, but 1 issue I have sometimes is emails with line breaks end up having extra line breaks added.

Can I tried the additional line breaks being added?

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";
}
like image 889
charlie Avatar asked Apr 07 '20 21:04

charlie


1 Answers

You can remove all extra new lines by using preg_replace.

preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $your_email_body);
like image 106
Sifat Haque Avatar answered Oct 30 '22 12:10

Sifat Haque