How to determine email part numbers received through PHP IMAP functions?

To get a specific section of the message body using imap_fetchbody(), you must pass a parameter sectionrelated to the IMAP part number, and as indicated in the PHP documentation :

This is a string of integers, divided by period, which is indexed into a list of body parts in accordance with the IMAP4 specification

The only key I have is to use imap_fetchstructure()to read the structure of a particular message. However, I do not know how to derive part numbers from it.

EDIT

For those interested in the IMAPv4 specification, here is an extraction paragraph that lists part numbers. Unfortunately, it does not clearly indicate how to obtain or calculate them.

+6
source share
1 answer

You are right, you need to use the result of the function imap_fetchstructure().

You can get a complete list of mail parts and sub-parts using the following function:

 function getPartList($struct, $base="") {
    $res=Array();
    if (!property_exists($struct,"parts")) {
            return [$base?:"0"];
    } else {
            $num=1;
            if (count($struct->parts)==1) return getPartList($struct->parts[0], $base);

            foreach ($struct->parts as $p=>$part) {
                    foreach (getPartList($part, $p+1) as $subpart) {
                            $res[]=($base?"$base.":"").$subpart;
                    }
            }
    }
    return $res;
 }

 $struct=imap_fetchstructure($mbox, $i);
 $res=getPartList($struct);
 print_r($res);

 Result:
 Array(
     [0] => 1
     [1] => 2
     [2] => 3.1
     [3] => 3.2
     [4] => 4.1
     [5] => 4.2
 );

EDIT: keep in mind that your server may not process the RFC822 subcommand

For example, on a Dovecot v2.2 server, it returns an empty string

 telnet imapserver.com 143
 a1 LOGIN user@example.com password
 a2 SELECT "Inbox"
 a3 FETCH 522 (BODY[3.1.2])

 // result:

 * 522 FETCH (BODY[3.1.2] {0}
 )
 a3 OK Fetch completed.
 a4 logout

EDIT2: It seems that subparts with one part are not taken into account ... See modified code

+1
source

All Articles