Using JavaMail to Search GMail With IMAP

Enable IMAP in GMail

  • Log into your GMail account and go to Settings
  • Switch to tab “Forwarding and POP/IMAP”
  • Select Enable IMAP
  • Set Folder size limits to Limit IMAP folders to contain no more than this many messages 1,000

Less secure app access

javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
	at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
	at javax.mail.Service.connect(Service.java:366)
	at javax.mail.Service.connect(Service.java:246)

Connect to email account

        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect("imap.gmail.com", <username>, <password>);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);

Multiple Term Search

Search criteria are expressed with search terms, such as SubjectTerm, BodyTerm,FlagTerm etc, with help of logical search terms, more complicated search criteria can be implemented.

        SearchTerm[] srchTerms = new SearchTerm[4];
        srchTerms[0] = new SubjectTerm(subject);
        srchTerms[1] = new BodyTerm(body);
        srchTerms[2] = new FlagTerm(new Flags(Flags.Flag.SEEN), seen);
        srchTerms[3] = new FlagTerm(new Flags(Flags.Flag.RECENT), recent);

        SearchTerm searchTerm = new AndTerm(srchTerms);
        Message[] messages = folder.search(searchTerm);

Sample code

import org.testng.annotations.Test;
import java.util.*;
import javax.mail.*;
import javax.mail.search.*;

public class EmailTest {

    @Test
    public void SearchEmailTest()
    {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");

        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            store.connect("imap.gmail.com", <username>, <password>);
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);

            GetMessage(inbox);
            SearchEmail(inbox, "Critical security alert","check activity");
            SearchEmail(inbox, "Critical security alert","check activity", false,false);
            SearchEmail(inbox, "Critical security alert","check activity",true,false);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void SearchEmail(Folder folder, String subject, String body, boolean seen, boolean recent)
    {
        System.out.println("=====SearchEmail with seen and recent======");
        try{
            SearchTerm[] srchTerms = new SearchTerm[4];
            srchTerms[0] = new SubjectTerm(subject);
            srchTerms[1] = new BodyTerm(body);
            srchTerms[2] = new FlagTerm(new Flags(Flags.Flag.SEEN), seen);
            srchTerms[3] = new FlagTerm(new Flags(Flags.Flag.RECENT), recent);

            SearchTerm searchTerm = new AndTerm(srchTerms);
            Message[] messages = folder.search(searchTerm);
            System.out.println("Message count: " + messages.length);
            Message msg = messages[0];
            PrintMsg(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public void SearchEmail(Folder folder, String subject, String body)
    {
        System.out.println("=====SearchEmail======");
        try{
            SearchTerm searchTerm = new AndTerm(new SubjectTerm(subject), new BodyTerm(body));
            Message[] messages = folder.search(searchTerm);
            System.out.println("Message count: " + messages.length);
            Message msg = messages[0];
            PrintMsg(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public void GetMessage(Folder folder)
    {
        System.out.println("=====GetMessage======");
        try
        {
            System.out.println("Message count: " + folder.getMessageCount());
            Message msg = folder.getMessage(folder.getMessageCount());
            PrintMsg(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void PrintMsg(Message msg)
    {
        try
        {
            Address[] in = msg.getFrom();
            for (Address address : in) {
                System.out.println("FROM:" + address.toString());
            }
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            System.out.println("body count: "+count);
            for (int i = 0; i < count; i++)
            {
                System.out.println("===========Body no. " + i);
                BodyPart bp = mp.getBodyPart(i);
                System.out.println("SENT DATE:" + msg.getSentDate());
                System.out.println("SUBJECT:" + msg.getSubject());
                System.out.println("CONTENT:" + bp.getContent());

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Execution output

# Removed the email message details from the output
=====GetMessage======
Message count: 1000
=====SearchEmail======
Message count: 2
=====SearchEmail with seen and recent======
Message count: 1
=====SearchEmail with seen and recent======
Message count: 1