eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

Webmail apps such as Gmail rely on protocols like the Internet Message Application Protocol (IMAP) to retrieve and manipulate email from an email server.

In this tutorial, we’ll explore how to use IMAP to interact with the Gmail server using Java. Also, we’ll perform operations such as reading emails, counting unread emails, moving emails between folders, marking emails as read, and deleting emails. Also, we’ll see how to set up Google app-specific passwords for authentication.

2. What Is IMAP?

IMAP is a technology that helps email clients retrieve emails stored on a remote server for further manipulation. Unlike Post Office Protocol (POP3), which downloads emails to the client and removes them from the email server, IMAP keeps the email on the server and allows multiple clients to access the same email server.

Furthermore, IMAP maintains an open connection while accessing emails from a remote server. It allows for better synchronization across multiple devices/machines.

IMAP runs on port 143 by default for an unencrypted connection and on port 993 for an SSL/TLS encrypted connection. When the connection is encrypted, it’s called IMAPS.

Most webmail services, including Gmail, provide support for both IMAP and POP3.

3. Project Setup

To begin, let’s add the jarkarta.mail-api dependency to the pom.xml:

<dependency>
    <groupId>jakarta.mail</groupId>
    <artifactId>jakarta.mail-api</artifactId>
    <version>2.1.3</version>
</dependency>

This dependency provides classes to establish a connection to an email server and perform different forms of manipulation like opening emails, deleting emails, and moving emails between different folders.

To connect to the Gmail server, we need to create an app password. Let’s navigate to the Google Account settings page and select the security option at the sidebar. Then, let’s enable 2-Factor Authentication (2FA) if not already active.

Next, let’s search for “app password” in the search bar and create a new app-specific password for our application.

4. Connecting to Gmail

Now that we have an app password for authentication, let’s create a method to establish a connection to the Gmail server:

static Store establishConnection() throws MessagingException {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");

    Session session = Session.getDefaultInstance(props, null);

    Store store = session.getStore("imaps");
    store.connect("imap.googlemail.com", "GMAIL", "APP PASSWORD");
    return store;
}

In the code above, we create a connection method that returns the Store object. We create a Properties object to set up configuration parameters for the mail session. Also, we specify the authentication credentials for the Store object to successfully establish a connection to our email.

5. Basic Operations

After a successful connection to the Gmail server through IMAP, we can perform basic operations like reading an email, listing all emails, moving emails between folders, deleting emails, marking emails as read, and more.

5.1. Counting Total and Unread Emails

Let’s list the total count of all emails and unread emails in the inbox and Spam folders:

static void emailCount(Store store) throws MessagingException {
    Folder inbox = store.getFolder("inbox");
    Folder spam = store.getFolder("[Gmail]/Spam");
    inbox.open(Folder.READ_ONLY);
    LOGGER.info("No of Messages : " + inbox.getMessageCount());
    LOGGER.info("No of Unread Messages : " + inbox.getUnreadMessageCount());
    LOGGER.info("No of Messages in spam : " + spam.getMessageCount());
    LOGGER.info("No of Unread Messages in spam : " + spam.getUnreadMessageCount());
    inbox.close(true);
}

The method above accepts the Store object as an argument to establish a connection to the email server. Also, we define a Folder object indicating the inbox and Spam folder. Then, we invoke getMessageCount() and getUnreadMessageCount() on the folder objects to get both the total and unread email counts.

The “[Gmail]” prefix indicates a special folder in the Gmail hierarchy, and it must be used for Gmail-specific folders. Apart from the Spam folder, other Gmail-specific folders include [Gmail]/All Mail, [Gmail]/Bin, and [Gmail]/Draft.

We can specify any folder to get its email count. However, this throws an error if the folder doesn’t exist.

5.2. Reading an Email

Furthermore, let’s read the first email in the inbox folder:

static void readEmails(Store store) throws MessagingException, IOException {
    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_ONLY);
    Message[] messages = inbox.getMessages();
    if (messages.length > 0) {
        Message message = messages[0];
        LOGGER.info("Subject: " + message.getSubject());
        LOGGER.info("From: " + Arrays.toString(message.getFrom()));
        LOGGER.info("Text: " + message.getContent());
    }
    inbox.close(true);
}

In the code above, we retrieve all emails in the inbox folder and store them in an array of type Message. Then, we log the subject, the sender address, and the content of the email to the console.

Finally, we close the inbox folder after a successful operation.

5.3. Searching Email

Moreover, we can perform a search operation by creating a SearchTerm instance and passing it to the search() method:

static void searchEmails(Store store, String from) throws MessagingException {
    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_ONLY);
    SearchTerm senderTerm = new FromStringTerm(from);
    Message[] messages = inbox.search(senderTerm);
    Message[] getFirstFiveEmails = Arrays.copyOfRange(messages, 0, 5);
    for (Message message : getFirstFiveEmails) {
        LOGGER.info("Subject: " + message.getSubject());
        LOGGER.info("From: " + Arrays.toString(message.getFrom()));
    }
    inbox.close(true);
}

Here, we create a method that accepts the Store object and the search criteria as parameters. Then, we open the inbox and invoke the search() method on it. Before invoking the search() method on the Folder object, we pass the search query to the SearchTerm object.

Notably, the search will be limited only to the specified folder.

5.4. Moving Email Across Folders

Also, we can move emails across different folders. In the case where the specified folder isn’t available, a new one is created:

static void moveToFolder(Store store, Message message, String folderName) throws MessagingException {
    Folder destinationFolder = store.getFolder(folderName);
    if (!destinationFolder.exists()) {
        destinationFolder.create(Folder.HOLDS_MESSAGES);
    }
    Message[] messagesToMove = new Message[] { message };
    message.getFolder().copyMessages(messagesToMove, destinationFolder);
    message.setFlag(Flags.Flag.DELETED, true);
}

Here, we specify the destination folder and invoke the copyMessages() method on the current email folder. The copyMessages() method accepts the messagesToMove and the destinationFolder as arguments. After copying the email to the new folder, we delete it from its original folder.

5.5. Marking an Unread Email as Read

Additionally, we can mark an unread email as read in a specified folder:

static void markLatestUnreadAsRead(Store store) throws MessagingException {
    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);

    Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
    if (messages.length > 0) {
        Message latestUnreadMessage = messages[messages.length - 1];
        latestUnreadMessage.setFlag(Flags.Flag.SEEN, true);
    }
    inbox.close(true);
}

After opening the inbox folder, we enable the read and write permission because marking an email as read will change its state. Then, we search the inbox and list all unread emails. Finally, we mark the latest unread email as read.

5.6. Deleting an Email

While we can move an email to the Trash folder, we can also delete an email while a connection is still open:

static void deleteEmail(Store store) throws MessagingException {
    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Message[] messages = inbox.getMessages();

    if (messages.length >= 7) {
        Message seventhLatestMessage = messages[messages.length - 7];

        seventhLatestMessage.setFlag(Flags.Flag.DELETED, true);
        LOGGER.info("Delete the seventh message: " + seventhLatestMessage.getSubject());
    } else {
        LOGGER.info("There are less than seven messages in the inbox.");
    }
    inbox.close(true);
}

In the code above, after getting all the emails in the inbox, we select the seventh email in the array and invoke the setFlag() method on it. This action marks the email for deletion.

6. Conclusion

In this article, we covered the basics of working with IMAP in Java, focusing on Gmail integration. Additionally, we explored essential email operations such as reading emails, moving emails between folders, deleting emails, and marking unread emails as read.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)