Posted by on in iDevelop, PHP | 2 comments

In the past week, I was messing around with the imap functions of PHP, to connect to a POP3 server, get eMail messages, etc.

But the problem is that imap_body() function doesn’t give out just the email message if the eMail is a multipart message. I was having problems with this as I didn’t find any solution in the comments on the online manual’s page & what I was trying to do is to get the HTML from an HTML eMail, but I got the plain text part as well as the headers if I used imap_body() for a multipart HTML eMail. 🙁

So I tried to get around it by looking at the eMail structure using the imap_fetchstructure(). And I ended up with the following code doing the job for me.

  1. $msgStructure = imap_fetchstructure($oIMAP, $msgNumber);
  2. if(!empty($msgStructure->parts)) {
  3.     for($i=0, $j=count($msgStructure->parts); $i<$j; $i++) {
  4.         $part = $msgStructure->parts[$i];
  5.         if($part->subtype == "HTML") {
  6.             $msgContent = imap_fetchbody($oIMAP, $msgNumber, $i+1);
  7.         }
  8.     }
  9. } else {
  10.     $msgContent = imap_body($oIMAP, $msgNumber);
  11. }

 
This piece of code will check if the message is multipart or not. If its multipart, then it’ll get the HTML message for you else you’ll get the TEXT message. 😉 Now $oIMAP is the IMAP connection object that you will create & $msgNumber is ofcourse the number of the eMail whose message you want to get.

This piece of code is not a full solution or any function etc. Its just a code snippet which is meaningless by itself but which you can use if you work with POP3 in your PHP scripts. 😀