Displaying IMAP E-mails using PHP - IF No. of mails in thread is even, mails are not correctly displayed

486 views Asked by At

I am trying to create a small ticketing script, but I am stuck on this part where I need to display the e-mail conversation between the user and the support group.

The script works like this:

  1. Form is filled by the User, upon submitting the data, a ticket is created and an e-mail containing some basic information of the ticket is sent to the Support Group.

  2. The Support Group replies to the mail with some instructions

  3. This conversation between the User and Support Group should be displayed on the ticket page, with the current code I encounter the following issue:

If the number of mails in the thread is ODD, mails are displayed correctly (by odd I mean ODD Numbers, 1/3/5/7 etc)

If the number of mails is EVEN, some replies are missing from the thread.

Here is the code:

<?php

    $imap         = imap_open('{mail.mail.eu:993/imap/ssl}INBOX', '[email protected]', 'Mailpass');

    //Testing value
    $value2 = '6';
    $subject     = 'Escalation Ticket No.: '.$value2.' has been created and assigned to you.';
    $threads     = array();

    //remove re: and fwd:
    $subject = trim(preg_replace("/Re\:|re\:|RE\:|Fwd\:|fwd\:|FWD\:/i", '', $subject));

    //search for subject in current mailbox
    $results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

    //because results can be false
    if(is_array($results)) {
        //now get all the emails details that were found
        $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);



        //foreach email
        foreach ($emails as $email) {
            //add to threads
            //we date date as the key because later we will sort it
            $threads[strtotime($email->date)] = $email;
        }   
    }

    //now reopen sent messages
    imap_reopen($imap, '{mail.mail.com:993/imap/ssl}INBOX.Sent');

    //and do the same thing
    //search for subject in current mailbox
    $results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

    //because results can be false
    if(is_array($results)) {
        //now get all the emails details that were found
        $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);


        //foreach email
        foreach ($emails as $email) {
            //add to threads
            //we date date as the key because later we will sort it
            $threads[strtotime($email->date)] = $email;
        }   
    }

    //sort keys so we get threads in chronological order
    ksort($threads);


    foreach ($threads as $key => $object) {

    $kee = $object->msgno;

    $qprint = imap_fetchbody($imap, $kee, 2);


    }

    echo quoted_printable_decode($qprint);


?>
0

There are 0 answers