There are few things you shall keep your eyes on if you want to thread your messages.
- each message has and must have a message_id, and this can be found in the message header.
$header->message_id
- each reply has message references, and the deeper in the thread you go the more references you'll find.
$header->references
- If the message has no references then it is a root message, else it is a reply.
You shall take care of the exceptions too.
The servers clean up the messages and the first messages which are removed are usually the root messages, SO you shall examine to fins if it's root is present in the thread or not, and if not deploy that reply as root.
Some other servers which are a little bugy, send the replies out of order and sometimes sooner than the root, and that is another problem that you shall take care of.
Sincerely yours
//Babak