Search code examples
phpimapemail-headers

PHP imap_search filter X-priority header


Currently I'm writing a script to move emails from a folder to a different folder. All mails containing the X-Priority: 3 header should be moved.

Part of source of the mail:

Date: DATE
To: NAME <EMAIL>
From: "NAME" <EMAIL>
Subject: SUBJECT
Message-ID: <SOMEID@EMAIL>
X-Priority: 3

Code I'm using:

$imapStream = imap_open('{HOST}Sent', 'EMAIL', 'PASSWORD');
$emailIds = imap_search($imapStream, 'ALL');
rsort($emailIds);

foreach ($emailIds as $emailId) {
    $overview = imap_fetch_overview($imapStream, $emailId, 0);
    $message = imap_fetchtext($imapStream, $emailId, 2);

    var_dump($overview); // <-- Doesn't contain X-Priority
    die;
}

Now, I need to filter all emails that has the X-Priority header set. I first thought I could maybe check the imap_fetch_overview, imap_fetchtext or imap_fetchbody but none contain the X-Priority. However, the X-Priority isn't a valid imap_search criteria.

How can I filter the mailbox and get only the emails with the X-Priority header?


Solution

  • Okay, I should've looked better before posting but I'll post my findings anyways:

    I found out I could get the headers with imap_fetchheader, which also contains the X-Priority header (duh...)

    So the code to retrieve it would be:

    $headers = explode("\n", imap_fetchheader($imapStream, $emailId, 0));
    

    In case of filtering, I could use TEXT as criteria to filter emails with a certain X-Priority, like this:

    $emailIds = imap_search($imapStream, 'TEXT "X-Priority: 3"');
    

    This seems to get all emails containing the X-Priority header only.