Gmail IMAP: Search with Gmail Search Syntax
See more GMail SMTP/IMAP/POP Examples
Search with Gmail operators through X-GM-RAW, using QueryMbx to obtain UIDs. The example discovers All Mail and opens it read-only. It quotes the query for the IMAP command rather than URL-encoding it.
IMAP search is limited to the selected mailbox. All Mail normally covers inbox and archived messages, but excludes Spam and Trash; a Gmail search operator cannot expand an IMAP search beyond its selected mailbox. An empty result is successful. Returned IMAP UIDs are mailbox-specific and are not Gmail message IDs. Persist them only with their mailbox and UIDVALIDITY.
Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Imap;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Mailboxes;
import com.chilkatsoft.chilkat2.MessageSet;
import com.chilkatsoft.chilkat2.StringBuilder;
public class ChilkatExample {
public static void main(String[] args) {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
JsonObject token = new JsonObject();
try {
token.loadFile("gmail-mail-token.json");
} catch (ChilkatException e) {
System.out.println("Could not load the protocol token from the private working directory.");
return;
}
if ((token.jsonTypeOf("access_token") != 1) || (token.stringOfEquals("access_token", "", true))) {
System.out.println("Authorize or refresh the mailbox first.");
return;
}
String mailbox = "user@example.com";
Imap imap = new Imap();
imap.setSsl(true);
imap.setPort(993);
imap.setRequireSslCertVerify(true);
imap.setAuthMethod("XOAUTH2");
try {
imap.connect("imap.gmail.com");
} catch (ChilkatException e) {
System.out.println("Could not establish the Gmail IMAP TLS connection.");
return;
}
try {
imap.login(mailbox, token.stringOf("access_token"));
} catch (ChilkatException e) {
imap.disconnect();
System.out.println("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.");
return;
}
String capabilities = imap.capability();
if ((!imap.getLastMethodSuccess()) || (!imap.hasCapability("X-GM-EXT-1", capabilities))) {
imap.logout();
imap.disconnect();
System.out.println("Gmail IMAP extensions are unavailable.");
return;
}
Mailboxes folders = new Mailboxes();
try {
imap.mbxList(false, "", "*", folders);
} catch (ChilkatException e) {
imap.logout();
imap.disconnect();
System.out.println("Could not list Gmail folders.");
return;
}
String allMail = "";
int folderMatches = 0;
int f = 0;
while (f < folders.getCount()) {
if ((folders.hasFlag(f, "\\All")) && (folders.isSelectable(f))) {
allMail = folders.getName(f);
folderMatches = folderMatches + 1;
}
f = f + 1;
}
if (folderMatches != 1) {
imap.logout();
imap.disconnect();
System.out.println("Expected one selectable folder with the \\All special-use attribute. Check label visibility.");
return;
}
try {
imap.examineMailbox(allMail);
} catch (ChilkatException e) {
imap.logout();
imap.disconnect();
System.out.println("Could not open All Mail read-only.");
return;
}
// This search uses Gmail syntax inside a quoted IMAP search argument.
String query = "has:attachment from:sender@example.net";
StringBuilder quoted = new StringBuilder();
quoted.append(query);
if ((quoted.contains("\r", true)) || (quoted.contains("\n", true))) {
imap.logout();
imap.disconnect();
System.out.println("A search query must not contain CR or LF.");
return;
}
int replacements = quoted.replace("\\", "\\\\");
replacements = quoted.replace("\"", "\\\"");
StringBuilder joined1 = new StringBuilder();
joined1.append("X-GM-RAW \"");
joined1.append(quoted.getAsString());
joined1.append("\"");
String criteria = joined1.getAsString();
MessageSet found = new MessageSet();
try {
imap.queryMbx(criteria, true, found);
} catch (ChilkatException e) {
imap.logout();
imap.disconnect();
System.out.println("Gmail search failed.");
return;
}
// Preserve UIDs as text. They belong to this mailbox and its UIDVALIDITY.
System.out.println("Matching messages: " + found.getCount());
System.out.println("UID set: " + found.toCompactString());
imap.logout();
imap.disconnect();
}
}