Sometimes you need to find all of the unread emails on your mail server and download them to display them to your client. The searchMails method does it for you! It uses the IMAP search protocol which is done entirely on the server-side. This means that it’s fast and allows you to retrieve only the desired emails.
To perform an email search, you must be connected to your mail server and have a mailbox selected. For the examples, we’ll use the Inbox mailbox:
$transporter:=IMAP New transporter($serverInfo)
To search within the Inbox mailbox, send a query to the IMAP server. To search for all of the unread emails, create a request with the “unread ” flag and send it to the server via the searchMails method of your IMAP transporter:
You can conduct more complex searches by combining several flags. For example, if you want to search for all of the unread emails that were received from “firstname.lastname@example.org” since August 1, 2020:
$mailIds:=$transporter.searchMails("unread SINCE \"1-Aug-2020\" FROM \"email@example.com\"")
For a complete list of the available flags, refer to the searchMails method documentation.
In return for this search, you’ll get a collection containing all the email IDs that match your request.
To download all of the found emails, you can use the new getMails method which takes a collection of mails IDs in parameter :
There you go! You have obtained all of your unread emails received from “firstname.lastname@example.org” since August 1, 2020, in just a few lines of code.