Only show these results:

Install the Nylas Kotlin/Java SDK

The Nylas Communications Platform allows developers to quickly build features that connect to every inbox, calendar, and contacts book in the world. The Nylas SDKs are the quickest way to integrate the Nylas Email, Calendar, and Contacts APIs into your app.

This guide will help you get started with the Nylas Java SDK.

Prerequisites

Before you can start using the Nylas Java SDK, make sure you have done the following:

  • Sign up for your developer account.
  • Get your developer keys. You need to have your:
    • CLIENT_ID - The CLIENT ID found on the dashboard page for your Nylas App.
    • CLIENT_SECRET - The CLIENT SECRET found on the dashboard page for your Nylas App.
    • ACCESS_TOKEN - The access token provided when you authenticate an account to your Nylas App.

Install the Nylas Java SDK

The Nylas Java SDK requires Java 8 or later.

For the following examples, replace X.X.X with the version you want to use. See the list of Nylas Java SKD releases to learn about the available versions.

Set up with Gradle

If you're using Gradle, add the following to the dependencies section of your build.gradle file:

implementation("com.nylas.sdk:nylas-java-sdk:X.X.X")   

Setup with Maven

For projects using Maven, add the following to your POM file:

<dependency>
<groupId>com.nylas.sdk</groupId>
<artifactId>nylas-java-sdk</artifactId>
<version>X.X.X</version>
</dependency>
``` -->

## Prerequisites

Before you can start using the Nylas Java SDK, make sure you have done the following:

- Sign up for your [developer account](https://dashboard.nylas.com/register?utm_source=docs&utm_medium=devrel-surfaces&utm_campaign=&utm_content=java-sdk).
- Get your [developer keys](/docs/the-basics/quickstart/). You need to have your:
- `CLIENT_ID` - The CLIENT ID found on the dashboard page for your Nylas App.
- `CLIENT_SECRET` - The CLIENT SECRET found on the dashboard page for your Nylas App.
- A Grant ID from a connected account, and either an `ACCESS_TOKEN` for that grant, or an API Key for your Nylas application.

## Install the Nylas Java SDK

::: info
The Nylas Kotlin/Java SDK requires Java 8 or later.
:::

For the following examples, replace `2.X.X` with the version you want to use. The Kotlin/Java SDK versions start with 2.0.0, and prior versions are the Java-only SDK.
See [the list of Java SDK releases to learn about the available versions](https://github.com/nylas/nylas-java/releases).

### Set up with Gradle

If you're using Gradle, add the following to the dependencies section of your `build.gradle` file:

```groovy
implementation ('com.nylas.sdk:nylas:2.0.0-beta.1')

Setup with Maven

For projects using Maven, add the following to your POM file:

<dependency>
<groupId>com.nylas.sdk</groupId>
<artifactId>nylas-sdk</artifactId>
<version>2.X.X</version>
</dependency>

Coming soon

At this time, the Kotlin/Java SDK integrates with the Nylas authentication, webhooks, calendar, and events APIs. Additional APIs are coming soon.

See the Nylas Kotlin/Java Github repo and the SDK's Dokka docs for more details.

Messages are the fundamental object of the Nylas platform and the core building block for most email applications. Messages contain several pieces of information, such as when the message was sent, the sender's address, to whom it was sent, and the message body. They can also contain files (attachments), calendar event invitations, and more.

Threads are first-class objects that represent a collection of messages. Messages are threaded together with a variety of heuristics. For Gmail and Microsoft Exchange accounts, messages are threaded together in a way that is as close as possible to the representation in their environments. For all other providers, including generic IMAP, messages are threaded using a custom JWZ-inspired algorithm.

Read Email Messages and Threads

import java.util.List;

import com.nylas.*;
import com.nylas.Thread;

public class ReadMessagesThreads {
public static void main(String[] args) throws Exception {
// Create client object and connect it to Nylas using
// an account's access token

NylasClient client = new NylasClient();

// Provide the access token for a specific account
NylasAccount account = client.account("ACCESS_TOKEN");
// Return the most recent email message
RemoteCollection<Message> messagesList = account.messages().list(new MessageQuery().limit(1));

for (Message message : messagesList) {
System.out.printf("Subject: %s | Unread: %s | ID: %s\n",
message.getSubject(),
message.getUnread(),
message.getId()
);
}

// Return the 5 most recent unread threads.
ThreadQuery unread = new ThreadQuery().limit(5).unread(true);
RemoteCollection<Thread> threads = account.threads().list(unread);

for (Thread thread : threads) {
StringBuilder participants = new StringBuilder();
for (NameEmail participant : thread.getParticipants()) {
participants.append(participant.getEmail()).append(" ");
}
System.out.printf("Subject: %s | Participants: %s\n",
thread.getSubject(),
participants
);
}

}
}

Learn More

Read the API reference for messages and threads to learn more. You can also check the email API guide to learn more about the functionality of the Nylas Email API.

Search Messages and Threads

The search sub-endpoint is used to run a full-text search, that is proxied to the account's provider. Results are matched with objects that have been synced, and then returned.

import java.io.IOException;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Message;
import com.nylas.Thread;

public class SearchMessagesThreads {

public static void main(String[] args) throws IOException, RequestFailedException {

// Create client object and connect it to Nylas using
// an account's access token
NylasClient client = new NylasClient();
// Provide the access token for a specific account
NylasAccount account = client.account("ACCESS_TOKEN");

// Search for the most recent email from a specific address
Message message = account.messages().search("to:[email protected]").get(0);
System.out.println(message.getSubject());

// You can also search threads
Thread thread = account.threads().search("to:[email protected]").get(0);
System.out.println(thread.getSubject());
}

}

Learn More

View the API reference for messages and threads to learn more. You can also check out the Email API guide to learn more about the functionality of the Nylas Email API.

Send an Email

import java.util.Arrays;

import java.io.IOException;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Draft;
import com.nylas.NameEmail;

public class SendEmail {

public static void main(String[] args) throws IOException, RequestFailedException {
// Create client object and connect it to Nylas using
// an account's access token
NylasClient client = new NylasClient();
// Provide the access token for a specific account
NylasAccount account = client.account("ACCESS_TOKEN");

Draft draft = new Draft();
draft.setSubject("With Love, from Nylas");
draft.setBody("This email was sent using the Nylas Email API. Visit https://nylas.com for details.");
draft.setTo(Arrays.asList(new NameEmail("My Nylas Friend", "[email protected]")));

account.drafts().send(draft);
}
}

Reply to an Email

import java.util.List;

import java.io.IOException;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Thread;
import com.nylas.ThreadQuery;
import com.nylas.Message;
import com.nylas.Draft;

public class ReplyEmail {
public static void main(String[] args) throws IOException, RequestFailedException {

// Create client object and connect it to Nylas using
// an account's access token
NylasClient client = new NylasClient();
// Provide the access token for a specific account
NylasAccount account = client.account("ACCESS_TOKEN");

// Get the most recent email thread
Thread thread = account.threads().expanded(new ThreadQuery().limit(1)).get(0);

// Send a reply to a thread
Draft reply = thread.createReply();
reply.setTo(message.getFrom());
reply.setCc(message.getCc());
reply.setBody("This is my reply.");
account.drafts().send(reply);

// Alternatively, you can send replies with setReplyToMessageId
List<Message> messages = thread.getMessages();
// Get the first latest message from the thread
Message message = messages.get(messages.size() - 1);
Draft directReply = new Draft();
directReply.setReplyToMessageId(message.getId());
directReply.setTo(message.getFrom());
directReply.setCc(message.getCc());
directReply.setBody("This is my reply.");
account.drafts().send(reply);
}
}

Attach a File to an Email

import java.util.Arrays;
import java.nio.file.Paths;

import java.io.IOException;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.File;
import com.nylas.Files;
import com.nylas.NameEmail;
import com.nylas.Draft;

public class AttachFile {

public static void main(String[] args) throws IOException, RequestFailedException {

// Create client object and connect it to Nylas using
// an account's access token
NylasClient client = new NylasClient();
// Provide the access token for a specific account
NylasAccount account = client.account("ACCESS_TOKEN");
Files files = account.files();

byte[] myFile = java.nio.file.Files.readAllBytes(Paths.get("/path/to/myFile.pdf"));
// .files.upload() saves the file to Nylas, file.id can then be used to attach the file to an email
File upload = files.upload("My Upload.pdf", "application/pdf", myFile);

//Create a new email draft to attach the file to.
Draft draft = new Draft();
draft.setSubject("With Love, From Nylas");
draft.setBody("This email was sent using the Nylas Email API. Visit https://nylas.com for details.");
draft.setTo(Arrays.asList(new NameEmail("My Nylas Friend", "[email protected]")));

File attachment = account.files().get(upload.getId());
draft.attach(attachment);
account.drafts().send(draft);

}
}

Learn More

View the API reference for sending to learn more. You can also check out the Email API guide to learn more about the functionality of the Nylas Email API.

Organize Inboxes with Folders and Labels

import java.util.List;
import java.io.IOException;

import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Label;
import com.nylas.Folder;
import com.nylas.AccountDetail;
import com.nylas.Message;
import com.nylas.MessageQuery;
import com.nylas.ThreadQuery;
import com.nylas.Thread;

public class OrganizeFoldersLabels {
public static void main(String[] args) throws IOException, RequestFailedException {
// Create client object and connect it to Nylas using
// an account's access token
NylasClient client = new NylasClient();
// Provide the access token for a specific account
NylasAccount account = client.account("ACCESS_TOKEN");
AccountDetail accountDetail = nylas.account(accessToken).fetchAccountByAccessToken();

// The organizationUnit attribute for the account object lets you know if the account uses folders or labels for organization
// Gmail uses labels, all other providers use folders
// Account object reference:/docs/api/v2/#tag--Accounts
if (accountDetail.getOrganizationUnit().equals("label")) { // Gmail uses labels

// Labels reference: /docs/api/v2/#tag--Labels
List<Label> labels = account.labels().list();

// Gmail includes a number of default labels,
// including Inbox, Important, Trash, Spam, and more
labels.stream().forEach((Label label) -> {
System.out.println(label.getDisplayName());
});

// Create a new label by passing it's display name
Label label = account.labels().create("My Label");

// Assign this label to the most recent message in the account's inbox
Message firstMessage = account.messages().list(
new MessageQuery().in("Inbox").limit(1)).get(0);
account.threads().addLabel(
firstMessage.getId(),
label.getId());
// Messages can have multiple labels
// You can also pass a list of id strings to .updateLabels() to batch update.
// .updateLabels() will overwrite all labels for the message
// Remove the label with account.messages().removeLabel(messageId, labelId)
}else if (accountDetail.getOrganizationUnit().equals("folder")){ // All other providers use folders

// Folders reference: /docs/api/v2/#tag--Folders
List<Folder> folders = account.folders().list();

// Microsoft accounts include a number of default folders,
// including Inbox, Important, Trash, Spam, and more
folders.stream().forEach((Folder folder) -> {
System.out.println(folder.getDisplayName());
});

//// Create a new folder by passing it's display name
Folder folder = account.folders().create("My Folder");

// Now we'll move the most recent email thread to our new folder
Thread firstThread = account.threads().list(
new ThreadQuery().in("Inbox").limit(1)).get(0);
account.messages().setFolderId(
firstThread.getId(),
folder.getId());
// Note: an email message can only be contained in a single folder, but
// a thread with multiple messages can span multiple folders
}
}
}
``` -->
<!--
## Calendar API

The Nylas Calendar API acts as a layer of abstraction on top of all calendar providers. The Nylas calendar API offers full Create, Read, Update, and Delete (CRUD) operations for all major calendar providers, with just a few lines of code you can add full-featured scheduling & calendar sync to your application.

### Read Calendars and Events

```java
import java.util.List;
import java.io.IOException;

import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Calendar;
import com.nylas.CalendarQuery;
import com.nylas.Event;
import com.nylas.EventQuery;

public class ReadCalendarsEvents {

public static void main(String[] args) throws IOException, RequestFailedException {

// Create client object and connect it to Nylas using
// an account's access token
NylasClient client = new NylasClient();
// Provide the access token for a specific account
NylasAccount account = client.account("ACCESS_TOKEN");

// Most user account have multiple calendars
List<Calendar> calendars = account.calendars().list();
calendars.stream().forEach((Calendar calendar) -> {
// Print the name and description for each calendar
// and whether or not the calendar is read only.
System.out.printf(
"Name: %s | Description %s | Read Only: %s\n",
calendar.getName(),
calendar.getDescription(),
calendar.isReadOnly());
});

Calendar calendar = account.calendars().list(
new CalendarQuery().limit(1)).get(0);

// List the 5 first events from a specified calendar.
List<Event> events = account.events().list(
new EventQuery().calendarId(calendar.getId()).limit(5));
events.stream().forEach((Event event) -> {
System.out.printf(
"Title: %s | When %s | Participants: %s\n",
event.getTitle(),
event.getWhen(),
event.getParticipants());
});
}
}

Create an Event

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.io.IOException;
import java.util.Arrays;

import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Participant;
import com.nylas.Event;
import com.nylas.Event.Timespan;

public class CreateEvent {
public static void postEventExample() throws IOException, RequestFailedException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("YOUR_ACCESS_TOKEN");

// The event "when" (date/time) can be set as one of 4 types.
// For details: https://developer.nylas.com/docs/api/v2/#event-subobjects
Event.When when = null;
LocalDate today = LocalDate.now();
when = new Event.Date(today);
when = new Event.Datespan(today, today.plusDays(1));
Instant sixPmUtc = today.atTime(18, 0).toInstant(ZoneOffset.UTC);
when = new Event.Time(sixPmUtc);
when = new Event.Timespan(sixPmUtc, sixPmUtc.plus(1, ChronoUnit.HOURS));

// Create a new event object
// Provide the appropriate id for a calendar to add the event to a specific calendar
Event event = new Event("{calendarId}", when);

// save() must be called to save the event to the third party provider
// notifyParticipants='true' will send a notification email to
// all email addresses specified in the participants
account.events().create(event, true);

event.setTitle("Party!");
event.setLocation("My House!");
event.setDescription("Let's celebrate our calendar integration!!");
event.setBusy(true);

// Metadata can be added to an event to store extra information and
// add custom fields. You can also query on metadata by keys, values, and key-value pairs
Map<String, String> metadata = new HashMap<>();
metadata.put("event_category", "gathering");
event.setMetadata(metadata);

// Participants are added as a list of Participant objects, which require email
// and may contain name, status, or comment as well
event.setParticipants(Arrays.asList(new Participant("[email protected]").name("My Nylas Friend")));

// Update the event with the new values and notify the participants
account.events().update(event, true);
}

// Use events().create() to save the event to the third party provider
// 2nd argument is a boolean notification to send to all participants
Event event1 = account.events().create(event, true);
System.out.println(event1.getId());
System.out.println(event1.getJobStatusId());

Learn More

Check out the API reference docs for calendars and events to learn more about the features of these endpoints. You can also take a look at the Calendar API guide to learn more about the functionality of the Nylas Calendar API.
::: -->

What's Next?

Tutorials