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 CkJava Downloads
import com.chilkatsoft.*;
public class ChilkatExample {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
boolean success = false;
int replacements;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkJsonObject token = new CkJsonObject();
success = token.LoadFile("gmail-mail-token.json");
if (success != true) {
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) == true)) {
System.out.println("Authorize or refresh the mailbox first.");
return;
}
String mailbox = "user@example.com";
CkImap imap = new CkImap();
imap.put_Ssl(true);
imap.put_Port(993);
imap.put_RequireSslCertVerify(true);
imap.put_AuthMethod("XOAUTH2");
success = imap.Connect("imap.gmail.com");
if (success != true) {
System.out.println("Could not establish the Gmail IMAP TLS connection.");
return;
}
success = imap.Login(mailbox,token.stringOf("access_token"));
if (success != true) {
imap.Disconnect();
System.out.println("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.");
return;
}
String capabilities = imap.capability();
if ((imap.get_LastMethodSuccess() != true) || (imap.HasCapability("X-GM-EXT-1",capabilities) != true)) {
imap.Logout();
imap.Disconnect();
System.out.println("Gmail IMAP extensions are unavailable.");
return;
}
CkMailboxes folders = new CkMailboxes();
success = imap.MbxList(false,"","*",folders);
if (success != true) {
imap.Logout();
imap.Disconnect();
System.out.println("Could not list Gmail folders.");
return;
}
String allMail = "";
int folderMatches = 0;
int f = 0;
while ((f < folders.get_Count())) {
if ((folders.HasFlag(f,"\\All") == true) && (folders.IsSelectable(f) == true)) {
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;
}
success = imap.ExamineMailbox(allMail);
if (success != true) {
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";
CkStringBuilder quoted = new CkStringBuilder();
quoted.Append(query);
if ((quoted.Contains("\r",true) == true) || (quoted.Contains("\n",true) == true)) {
imap.Logout();
imap.Disconnect();
System.out.println("A search query must not contain CR or LF.");
return;
}
replacements = quoted.Replace("\\","\\\\");
replacements = quoted.Replace("\"","\\\"");
CkStringBuilder joined1 = new CkStringBuilder();
joined1.Append("X-GM-RAW \"");
joined1.Append(quoted.getAsString());
joined1.Append("\"");
String criteria = joined1.getAsString();
CkMessageSet found = new CkMessageSet();
success = imap.QueryMbx(criteria,true,found);
if (success != true) {
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.get_Count());
System.out.println("UID set: " + found.toCompactString());
imap.Logout();
imap.Disconnect();
}
}