PHPverse 2025

Voting

: two plus four?
(Example: nine)

The Note You're Voting On

Steve
3 years ago
It has been noted that imap_search breaks with imap4 syntax. To do an imap 4 search use curl and send a custom command, then grab the results. Its best to do a UID search to get the unique IDs to work with later. Here's an example with a working curl function.

<?php
$host
= 'your-server.tld';
$user = 'username';
$pass = 'password';
$folder = 'INBOX';

function
send_imap_command($server, $user, $pass, $command, $folder="INBOX")
{
//Send an imap command directly to the imap server

$result=["response"=>"", "error"=>""];
$url = "imaps://$server/". rawurlencode($folder);
$options=[CURLOPT_URL=>$url, CURLOPT_PORT=> 993, CURLOPT_USERNAME=> $user,
CURLOPT_PASSWORD=> $pass, CURLOPT_RETURNTRANSFER=> true, CURLOPT_HEADER=> true,
CURLOPT_CUSTOMREQUEST=> $command];
$ch = curl_init();
curl_setopt_array($ch, $options);

$result["response"] = curl_exec($ch);
if(
curl_errno($ch)) $response["error"]="Error (". curl_errno($ch) ."): ". curl_error($ch);

return
$result;
}

//Pull out all the emails returned as undeliverable by the remote mail server in the inbox using curl
$response=send_imap_command($host, $user, $pass,
'UID SEARCH SINCE "01-Jan-2022" (OR FROM "mailer-daemon" FROM "postmaster") (OR SUBJECT "fail" (OR SUBJECT "undeliver" SUBJECT "returned"))',
$folder);

if(
$response["error"]!="")
{
echo
$response["error"]."\n";
} elseif (
strlen($response["response"])>5){
//Server returns a string in the form * SEARCH uid1 uid2 uid3 ... Clean up and create array of UIDs.
$response["response"]=str_replace("* SEARCH ","",$response["response"]);
$messages=explode(" ",$response["response"]);
}

print_r($messages);
?>

<< Back to user notes page

To Top