imap_search
(PHP 4, PHP 5)
imap_search — This function returns an array of messages matching the given search criteria
Описание
This function performs a search on the mailbox currently opened in the given imap stream.
For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also » RFC2060, section 6.4.4).
Список параметров
- imap_stream
-
An IMAP stream returned by imap_open().
- criteria
-
A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted.
- ALL - return all messages matching the rest of the criteria
- ANSWERED - match messages with the \\ANSWERED flag set
- BCC "string" - match messages with "string" in the Bcc: field
- BEFORE "date" - match messages with Date: before "date"
- BODY "string" - match messages with "string" in the body of the message
- CC "string" - match messages with "string" in the Cc: field
- DELETED - match deleted messages
- FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
- FROM "string" - match messages with "string" in the From: field
- KEYWORD "string" - match messages with "string" as a keyword
- NEW - match new messages
- OLD - match old messages
- ON "date" - match messages with Date: matching "date"
- RECENT - match messages with the \\RECENT flag set
- SEEN - match messages that have been read (the \\SEEN flag is set)
- SINCE "date" - match messages with Date: after "date"
- SUBJECT "string" - match messages with "string" in the Subject:
- TEXT "string" - match messages with text "string"
- TO "string" - match messages with "string" in the To:
- UNANSWERED - match messages that have not been answered
- UNDELETED - match messages that are not deleted
- UNFLAGGED - match messages that are not flagged
- UNKEYWORD "string" - match messages that do not have the keyword "string"
- UNSEEN - match messages which have not been read yet
- options
-
Valid values for options are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.
- charset
-
Возвращаемые значения
Returns an array of message numbers or UIDs.
Return FALSE if it does not understand the search criteria or no messages have been found.
Список изменений
Версия | Описание |
---|---|
4.3.3 | The charset parameter was added |
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с почтой
- IMAP, POP3 и NNTP
- imap_8bit
- imap_alerts
- imap_append
- imap_base64
- imap_binary
- imap_body
- imap_bodystruct
- imap_check
- imap_clearflag_full
- imap_close
- imap_create
- imap_createmailbox
- imap_delete
- imap_deletemailbox
- imap_errors
- imap_expunge
- imap_fetch_overview
- imap_fetchbody
- imap_fetchheader
- imap_fetchmime
- imap_fetchstructure
- imap_fetchtext
- imap_gc
- imap_get_quota
- imap_get_quotaroot
- imap_getacl
- imap_getmailboxes
- imap_getsubscribed
- imap_header
- imap_headerinfo
- imap_headers
- imap_last_error
- imap_list
- imap_listmailbox
- imap_listscan
- imap_listsubscribed
- imap_lsub
- imap_mail_compose
- imap_mail_copy
- imap_mail_move
- imap_mail
- imap_mailboxmsginfo
- imap_mime_header_decode
- imap_msgno
- imap_num_msg
- imap_num_recent
- imap_open
- imap_ping
- imap_qprint
- imap_rename
- imap_renamemailbox
- imap_reopen
- imap_rfc822_parse_adrlist
- imap_rfc822_parse_headers
- imap_rfc822_write_address
- imap_savebody
- imap_scan
- imap_scanmailbox
- imap_search
- imap_set_quota
- imap_setacl
- imap_setflag_full
- imap_sort
- imap_status
- imap_subscribe
- imap_thread
- imap_timeout
- imap_uid
- imap_undelete
- imap_unsubscribe
- imap_utf7_decode
- imap_utf7_encode
- imap_utf8
Коментарии
imap_search() always returns false when op_silent flag is set in the connection parameters.
The date format for e.g. SINCE is, according to rfc3501:
date = date-text / DQUOTE date-text DQUOTE
date-day = 1*2DIGIT
; Day of month
date-day-fixed = (SP DIGIT) / 2DIGIT
; Fixed-format version of date-day
date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
"Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
date-text = date-day "-" date-month "-" date-year
So a valid date is e.g. "22-Jul-2012" with or without the double quotes.
To set your own CHARSET, which is useful if you are dealing with Chinese Japanese and Korean queries.
<?php imap_search($inbox,'BODY "'.$keyword.'"', SE_FREE, "UTF-8"); ?>
Hi,
be aware, that imap_search() does NOT (as you may exspect) return an empty array, if nothing was found!
As the manual says, it returns FALSE.
Do not test the result like "count($array)" as I did.
This gives you 1 for an empty result. Took me an hour to found out why :-( RTFM
imap_search function is not fully compatible with IMAP4. the c-client used as of now supports only IMAP2 and some search criterion will not be available for use such as "OR"
So a php code similar to:
$inbox = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);
$search_string = 'SUBJECT "FedEx" OR SUBJECT "USPS"';
$emails = imap_search($inbox, $search_string);
will throw an error saying "Unknown search criterion"
observations and reference:
PHP source trace:(ref: https://github.com/php/php-src/blob/master/ext/imap/php_imap.c)
/ext/imap/php_imap.c -> line no : 4126
imap_search => line no : 4148
c-client library source trace:
src/c-client/mail.c -> line no : 3973
internal.txt -> line no : 1919 => mail_criteria()
criteria IMAP2-format search criteria string
WARNING: This function does not accept IMAP4 search criteria.
IMAP2 RFC1064 => [ref: https://tools.ietf.org/html/rfc1064] [page: 13]
IMAP4 RFC2060 => [ref: http://www.faqs.org/rfcs/rfc2060.html] [section: 6.4.4]
Note:
The core search functionality in a core module(IMAP) is still not available in PHP. Hope this will be brought to the developer community's attention...
This is the correct way to use the imap_search with ON "date"
$date = date("j F Y");
$emails = imap_search($inbox,'ON "'.$date.'"' );
Please be aware about UID of the message.
It is NOT an ID that never change!
If you move your message to another folder in your IMAP account, this UID WILL CHANGE.
So if your message has UID = 100 (in INBOX folder) and you move it to some subfolder and then back to INBOX, it's new UID in INBOX will be 101.
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);
?>