Search code examples
phpoutlookimapphp-imap

PHP IMAP : How to get the correct body?


I am connecting to my inbox via PHP IMAP plugin. Below are my steps

Connection

//The location of the mailbox.
$hostname = '{outlook.office365.com:993/imap/ssl/novalidate-cert}';

//The username / email address that we want to login to.
$username = 'username';

//The password for this email address.
$password = 'password';

I am further opening the inbox connection and looking at anything that is UNSEEN in the inbox

//Attempt to connect using the imap_open function.

$inbox = imap_open($hostname,$username,$password);

$mailboxes = imap_list($inbox, $hostname, '*');
imap_reopen($inbox, $hostname.'INBOX');

$emails = imap_search($inbox, 'UNSEEN');

Further, I am iterating over all the emails and its working well with headers. The issue I am having is with body.

To get the body of the email I am using

//get message body
$message = quoted_printable_decode(imap_fetchbody($inbox, $email_number, 2.1));
if ($message == '') {
  $message = quoted_printable_decode(imap_fetchbody($inbox, $email_number, 1));
}

So running a test on 40 emails, 28 emails fetch the body correct and store into the database.

12 emails fetch a body which looks like

PGh0bWwgeG1sbnM6dj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp2bWwiIHhtbG5zOm89InVy
bjpzY2hlbWFzLW1pY3Jvc29mdC1jb206b2ZmaWNlOm9mZmljZSIgeG1sbnM6dz0idXJuOnNjaGVt
YXMtbWljcm9zb2Z0LWNvbTpvZmZpY2U6d29yZCIgeG1sbnM6bT0iaHR0cDovL3NjaGVtYXMubWlj
cm9zb2Z0LmNvbS9vZmZpY2UvMjAwNC8xMi9vbW1sIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv
VFIvUkVDLWh0bWw0MCI+DQo8aGVhZD4NCjxtZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQtVHlwZSIg
Y29udGVudD0idGV4dC9odG1sOyBLWZhbWlseToiQ2FsaWJyaSIsc2Fucy1zZXJp
ZjsNCglmb250LXdlaWdodDpib2xkO30NCmE6bGluaywgc3Bhbi5Nc29IeXBlcmxpbmsNCgl7bXNv
LXN0eWxlLXByaW9

How should I be reading the body? So that I can have my test pass all the emails correctly?

Thank you


Solution

  • Also I found a way to get rid of those characters.

    I looked at the encoding and I am parsing based on encoding numbers as follow

    $encoding = $structure->encoding;
    
    if($encoding == 3) {
       $finalmsg = imap_base64($message);
    } else if($encoding == 1) {
       $finalmsg = imap_8bit($message);
    } else {
       $finalmsg = imap_qprint($message);
    }
    

    I am still having issues when encoding type = 0. The signature is causing major problem