How to read email inbox data with Nylas Java SDK

How to read email inbox data with Nylas Java SDK

11 min read
Tags:

It can be challenging to programmatically analyze and extra data from Email as the data can be complex and unstructured. Thanks to the Nylas Connectivity APIs we can use different kinds of objects and filters that treat emails like first-class citizens, making this task easier.

To make things even easier for Java developers, we offer the Nylas Java SDK. Today we’re going to review how to read email inbox data using Java and the Nylas Java SDK.

If you’re interested in our other SDK offerings, we have you covered:

Is your system ready?

If you’re new to Java or new to Nylas, we would recommend you to read the post How to Send Emails with the Nylas Java SDK where everything is clearly explained.

Reading the Inbox

Let’s name this project read_inbox and our main class ReadInbox.

This is going to be our pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>Nylas</groupId>
   <artifactId>ReadInbox</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <maven.compiler.source>17</maven.compiler.source>
       <maven.compiler.target>17</maven.compiler.target>
   </properties>

   <dependencies>
       <dependency>
           <groupId>com.nylas.sdk</groupId>
           <artifactId>nylas-java-sdk</artifactId>
           <version>1.16.0</version>
       </dependency>
       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-jdk14</artifactId>
           <version>1.7.25</version>
       </dependency>
       <dependency>
           <groupId>io.github.cdimascio</groupId>
           <artifactId>dotenv-java</artifactId>
           <version>2.2.4</version>
       </dependency>
   </dependencies>

   <build>
       <pluginManagement>
           <plugins>
               <plugin>
                   <!-- Build an executable JAR -->
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-jar-plugin</artifactId>
                   <version>3.1.0</version>
                   <configuration>
                       <archive>
                           <manifest>
                               <addClasspath>true</addClasspath>
                               <mainClass>ReadInbox</mainClass>
                           </manifest>
                       </archive>
                   </configuration>
               </plugin>
               <plugin>
                   <artifactId>maven-assembly-plugin</artifactId>
                   <configuration>
                       <archive>
                           <manifest>
                               <mainClass>ReadInbox</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                           <descriptorRef>jar-with-dependencies</descriptorRef>
                       </descriptorRefs>
                   </configuration>
               </plugin>
               <plugin>
                   <groupId>org.codehaus.mojo</groupId>
                   <artifactId>exec-maven-plugin</artifactId>
                   <version>1.2.1</version>
                   <executions>
                       <execution>
                           <phase>package</phase>
                           <goals>
                               <goal>java</goal>
                           </goals>
                       </execution>
                   </executions>
                   <configuration>
                       <mainClass>ReadInbox</mainClass>
                       <cleanupDaemonThreads>false</cleanupDaemonThreads>
                   </configuration>
               </plugin>
           </plugins>
       </pluginManagement>
   </build>

</project>

And here’s our source code:

//Import Java Utilities
import java.io.IOException;
import java.util.List;

//Import Nylas Packages
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Message;
import com.nylas.Messages;
import com.nylas.RemoteCollection;

//Import DotEnv to handle .env files
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;

public class ReadInbox {
   public static void main(String[] args) throws RequestFailedException, 
                                                 IOException{
       Dotenv dotenv = Dotenv.load();
       // Create the client object
       NylasClient client = new NylasClient();
       // Connect it to Nylas using the Access Token from the .env file
       NylasAccount account = client.account(dotenv.get("ACCESS_TOKEN"));

       //Access the messages endpoint
       Messages messages = account.messages();
       //Read all messages
       RemoteCollection<Message> messageList = messages.list();

       //Loop through the emails
       for(Message email : messageList){
       //Print the subject and who’s sending the email
           System.out.print("Subject: " + email.getSubject() + " | " +
                            "From: " + email.getFrom().get(0).getEmail() + 
                            " |\n\n");
       }
   }
}

In order to run our project, we need to compile it first. We can open a Terminal window, go to our project’s root folder and type the following maven command:

$ mvn package
Compile Java app

Now, we can run this command to execute our application:

$ mvn exec:java -Dexec.mainClass=”ReadInbox” -Dexec.cleanupDaemonThreads=false
Read email inbox

This will display the first 100 emails in your mailbox.

If we would like to compile this as JAR file, we can use the following maven command:

$ mvn clean compile assembly:single

And run the JAR file like this:

$ java -jar target/ReadInbox-1.0-SNAPSHOT-jar-with-dependencies.jar

Just keep in mind that if the ACCESS_TOKEN expires, you will need to generate a new one and update the JAR file.

We might notice we’re getting more messages than expected in the response: all emails in the box are separated into “folders” using “labels”. As we’re not specifying any particular source, we’re getting Inbox but also Sent, Spam, and Trash messages.

We can easily fix this, by adding new MessageQuery().in(“inbox”) on line 21:

RemoteCollection<Message> messageList = messages.list(new MessageQuery().in("inbox"));
Read from inbox folder

This will get only the emails that are in our inbox only.

If we want to only read the first 3 emails, we can just add .limit(3).

RemoteCollection<Message> messageList = messages.list(new MessageQuery().in("inbox").limit(3));

And add this to your list of imports:

import com.nylas.MessageQuery;
Read 3 emails

We’re just adding an extra property to our messages.list() function.

We know how to read emails from the account, specifying the source folder with .where, and setting a limit on the number of messages to read with .limit(). There’s a lot more you can configure when reading messages. Have a look at our documentation to see what else you can do.

Reading email threads

A thread is a message shared between 2 or more people. It consists of the original message with its corresponding replies.

For this example, we’re going to limit the results to three threads. We’re going to call this project Reading_Threads and our main class will be called ReadThreads.

Here’s our pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>Nylas</groupId>
   <artifactId>ReadThreads</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <maven.compiler.source>17</maven.compiler.source>
       <maven.compiler.target>17</maven.compiler.target>
   </properties>

   <dependencies>
       <dependency>
           <groupId>com.nylas.sdk</groupId>
           <artifactId>nylas-java-sdk</artifactId>
           <version>1.16.0</version>
       </dependency>
       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-jdk14</artifactId>
           <version>1.7.25</version>
       </dependency>
       <dependency>
           <groupId>io.github.cdimascio</groupId>
           <artifactId>dotenv-java</artifactId>
           <version>2.2.4</version>
       </dependency>
   </dependencies>

   <build>
       <pluginManagement>
           <plugins>
               <plugin>
                   <!-- Build an executable JAR -->
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-jar-plugin</artifactId>
                   <version>3.1.0</version>
                   <configuration>
                       <archive>
                           <manifest>
                               <addClasspath>true</addClasspath>
                               <mainClass>ReadThreads</mainClass>
                           </manifest>
                       </archive>
                   </configuration>
               </plugin>
               <plugin>
                   <artifactId>maven-assembly-plugin</artifactId>
                   <configuration>
                       <archive>
                           <manifest>
                               <mainClass>ReadThreads</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                           <descriptorRef>jar-with-dependencies</descriptorRef>
                       </descriptorRefs>
                   </configuration>
               </plugin>
               <plugin>
                   <groupId>org.codehaus.mojo</groupId>
                   <artifactId>exec-maven-plugin</artifactId>
                   <version>1.2.1</version>
                   <executions>
                       <execution>
                           <phase>package</phase>
                           <goals>
                               <goal>java</goal>
                           </goals>
                       </execution>
                   </executions>
                   <configuration>
                       <mainClass>ReadThreads</mainClass>
                       <cleanupDaemonThreads>false</cleanupDaemonThreads>
                   </configuration>
               </plugin>
           </plugins>
       </pluginManagement>
   </build>

</project>

And here’s our source code:

//Import Java Utilities
import java.io.IOException;
import java.util.List;

//Import Nylas Packages
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;

//Import DotEnv to handle .env files
import com.nylas.Thread;
import com.nylas.Threads;
import com.nylas.ThreadQuery;
import com.nylas.NameEmail;
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;

public class ReadInbox {
   public static void main(String[] args) throws RequestFailedException, 
                                                 IOException{
       Dotenv dotenv = Dotenv.load();
       // Create the client object
       NylasClient client = new NylasClient();
       // Connect it to Nylas using the Access Token from the .env file
       NylasAccount account = client.account(dotenv.get("ACCESS_TOKEN"));

       Threads threads = account.threads();
       List<Thread> thread = threads.list(new ThreadQuery().
                             in("inbox").limit(3)).fetchAll();

       for(Thread message : thread){
           List<NameEmail> participants = message.getParticipants();
           for(NameEmail participant : participants){
               System.out.println("Subject: " + message.getSubject() +
                                  " | Participant: " + participant.getName() +
                                  " | Email: " + participant.getEmail());
           }
           if(participants.size() != 0) {
               System.out.println();
           }
       }
   }
}

Let’s compile and run our application:

$ mvn package && mvn exec:java -Dexec.mainClass="ReadThreads"

We can link actions using the && command:

Read threads

Searching emails

Let’s say we want to search the latest message sent by a particular email account. We can do this on either messages or threads, but for this example, we’re going to use messages. We’re going to call our project Search_Messages and the main class SearchMessages.

This is our pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>Nylas</groupId>
   <artifactId>Search_Messages</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <maven.compiler.source>17</maven.compiler.source>
       <maven.compiler.target>17</maven.compiler.target>
   </properties>

   <dependencies>
       <dependency>
           <groupId>com.nylas.sdk</groupId>
           <artifactId>nylas-java-sdk</artifactId>
           <version>1.16.0</version>
       </dependency>
       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-jdk14</artifactId>
           <version>1.7.25</version>
       </dependency>
       <dependency>
           <groupId>io.github.cdimascio</groupId>
           <artifactId>dotenv-java</artifactId>
           <version>2.2.4</version>
       </dependency>
       <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-lang3</artifactId>
           <version>3.12.0</version>
       </dependency>
   </dependencies>

   <build>
       <pluginManagement>
           <plugins>
               <plugin>
                   <!-- Build an executable JAR -->
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-jar-plugin</artifactId>
                   <version>3.1.0</version>
                   <configuration>
                       <archive>
                           <manifest>
                               <addClasspath>true</addClasspath>
                               <mainClass>SearchMessages</mainClass>
                           </manifest>
                       </archive>
                   </configuration>
               </plugin>
               <plugin>
                   <artifactId>maven-assembly-plugin</artifactId>
                   <configuration>
                       <archive>
                           <manifest>
                               <mainClass>SearchMessages</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                           <descriptorRef>jar-with-dependencies</descriptorRef>
                       </descriptorRefs>
                   </configuration>
               </plugin>
               <plugin>
                   <groupId>org.codehaus.mojo</groupId>
                   <artifactId>exec-maven-plugin</artifactId>
                   <version>1.2.1</version>
                   <executions>
                       <execution>
                           <phase>package</phase>
                           <goals>
                               <goal>java</goal>
                           </goals>
                       </execution>
                   </executions>
                   <configuration>
                       <mainClass>SearchMessages</mainClass>
                       <cleanupDaemonThreads>false</cleanupDaemonThreads>
                   </configuration>
               </plugin>
           </plugins>
       </pluginManagement>
   </build>

</project>

And here’s our source code:

//Import Java Utilities
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils.*;
//Import Nylas Packages
import com.nylas.*;

//Import DotEnv to handle .env files
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;

public class SearchMessages {
   public static void main(String[] args) throws RequestFailedException, 
                                                 IOException{
       Dotenv dotenv = Dotenv.load();
       // Create the client object
       NylasClient client = new NylasClient();
       // Connect it to Nylas using the Access Token from the .env file
       NylasAccount account = client.account(dotenv.get("ACCESS_TOKEN"));

       // Access the messages endpoint
       Messages messages = account.messages();
       // Filter messages by sender
       RemoteCollection<Message> messageList = 
                        messages.search("from:[email protected]", 3, 0);
       // Loop through messages
       for(Message email : messageList){
           // Print out the subject
           System.out.print("Subject: " + email.getSubject() + " | ");
           // Get attachments if there are any
           List<File> attachments = email.getFiles();
           // If we some attachment, let's get the names
           if (attachments.size() != 0){
               String attachs = "";
               System.out.print("Attachments: ");
               // Loop through the attachments
               for(File attachment : attachments){
                   // Get the attachment name
                   attachs += attachment.getFilename() + ", ";
               }
               // Print out the attachment getting rid of the last ","
               System.out.println(StringUtils.strip(attachs, ", "));
           }else{
               // No attachments found
               System.out.println("Attachments: None");
           }
       }
   }
}

Let’s compile and run our application:

$ mvn package && mvn exec:java -Dexec.mainClass="SearchMessages"
Search emails

And that’s it. As you can see, by using the Nylas Java SDK, reading email inbox data becomes an easy task. If you want to learn more, visit our Documentation Page.

Related resources

How to block time slots in Outlook and Google calendar with Nylas Calendar API

Key Takeaways Managing calendar availability is essential for professionals, teams, and businesses to stay organized…

How to Solve Webhook Integration Challenges with PubSub Notification Channel

Key Takeaways This article addresses the challenges of webhook integration and introduces the PubSub Notification…

How to Send Emails Using an API

Key Takeaways This post will provide a complete walkthrough for integrating an email API focused…