Perform Gmail Search using IMAP in JAVA

Let say, if you come up with a scenario where you want to search a particular email or specific set of emails on a Gmail account using JAVA code, then below steps will solve your problem as you can easily automate GMAIL search using java-gmail-imap-1.4.4-gm-ext-0.5.jar


  • Add it to the build path of the project

Sample Code

NOTE 1 : Below code will use IMAP to read emails from GMAIL server

NOTE 2 : GmailRawSearchTerm class will be used to perform search on Gmail Server

NOTE 3 : Below code will search all the emails related to specific search keyword and will print the subject of emails

import java.util.Properties;

import org.junit.Test;


public class GmailSearch {

	// Enter search keyword here
	String search_keyword = "Testing Gmail Search";

	Properties prop;
	Session session;
	Store store;
	IMAPFolder inbox;
	GmailRawSearchTerm rawTerm;

	public void test01() throws Exception {

		// pass search keyword to gmailSearch function

	public void gmailSearch(String search_keyword) throws Exception {
		try {
			prop = System.getProperties();
			prop.setProperty("", "imaps");
			session = Session.getDefaultInstance(prop, null);
			store = session.getStore("imaps");

			// Enter user name and password to connect to Gmail Account
			store.connect("", "username", "password");
			System.out.println("Connection established !!!!");

			inbox = (IMAPFolder) store.getFolder("INBOX");;
			System.out.println("Total email counts in inbox : " + inbox.getMessageCount());

			rawTerm = new GmailRawSearchTerm(search_keyword);
			Message messagesFound[] =;
			System.out.println("Messages found for Keyword : " + messagesFound.length);

			// Print subject of all messages found for search keyword
			System.out.println("***********Print subjects ***********************");
			for (Message message : messagesFound) {
			System.out.println("Searching Completed !!!");

		} finally {
			if (inbox.isOpen()) {
			System.out.println("Connection Closed !!!");


Kindly update the details mentioned below before executing above project :

a) Update the search term in above code

b) Update the Gmail Account credentials

NOTE : You can refer this document for search operators as you can improve your search using the operators mentioned in the doc

Output of above Code would look like :


If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *