Search emails with IMAP protocol

Automatically translated from English

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.

 

HDI IMAPMailsSearching

email search

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)
$boxInfo:=$transporter.selectBox("inbox")

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:

$mailIds:=$transporter.searchMails("unread ")

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 “imap.test@4d.com” since August 1, 2020:

$mailIds:=$transporter.searchMails("unread SINCE \"1-Aug-2020\" FROM \"imap.test@4d.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.

download emails

To download all of the found emails, you can use the new getMails method which takes a collection of mails IDs in parameter :

$mails:=$transporter.getMails($mailsIds)

There you go! You have obtained all of your unread emails received from “imap.test@4d.com” since August 1, 2020, in just a few lines of code.

 

Fabrice Mainguené

• Product Owner •

Fabrice Mainguené joined 4D Program team in November, 2016. As a Product Owner, he is in charge of writing the user stories then translating it to functional specifications. His role is also to make sure that the feature implementation delivered is meeting the customer need.

After obtaining a Bachelor degree in Computer Science at CNAM, Fabrice joined a small software publishing company as a Windev developer. Then he worked for different companies in industry and trade areas as a Windev and web developer as well as technical advisor on new features.