Install the 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>
Initialize the API Client
There are 2 ways to initialize APIClient
:
- Nylas App
- Individual user account
Create Nylas App Client
A Nylas App client allows you to access and modify the Account Management endpoint, which lets you check the status of user accounts connected to your Nylas app and upgrade/downgrade them. To create a Nylas App client object, initialize an NylasApplication
object, passing only the CLIENT_ID
and CLIENT_SECRET
for your Nylas app.
import java.io.IOException;
import java.util.List;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.NylasApplication;
import com.nylas.Account;
public class AccountManagement {
public static void main(String[] args) throws IOException, RequestFailedException {
// Create client object and connect it to Nylas using
// your Nylas App ID and secret
NylasClient nylas = new NylasClient();
NylasApplication application = nylas.application("{CLIENT_ID}", "{CLIENT_SECRET}");
List<Account> accounts = application.accounts().list();
accounts.stream().forEach((Account account) -> {
System.out.printf(
"Email: %s | Billing State: %s | Sync State: %s | Account ID: %s",
account.getEmail(),
account.getBillingState(),
account.getSyncState(),
account.getId()
);
});
}
}
Create Nylas User Account Client
A Nylas account client object lets you access all email, calendar, and contacts functionality and data for a specific user account. To create a Nylas account client object, initialize an Account
object, passing the ACCESS_TOKEN
for the specific user account.
import java.io.IOException;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Account;
import com.nylas.AccountDetail;
public class UserAccount {
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 = account.fetchAccountByAccessToken();
System.out.printf(
"Email: %s | Provider: %s | Organization: %s",
account.getEmailAddress(),
account.getProvider(),
account.getOrganizationUnit()
);
}
}
Learn More
Read the API reference for the accounts endpoint to learn more about the information you can access for accounts. Now, you should be ready to take a look at how to use the Nylas Java SDK to leverage the Nylas email, calendar, and contacts APIs.
Email API
The Nylas Email API makes it easy to integrate Gmail, Outlook, Microsoft Exchange, Office 365, and every other email service provider into your application, and it offers full Create, Read, Update, and Delete (CRUD) operations.
Messages and Threads
The Nylas Email API allows you to work with both messages and threads.
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
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.
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
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.
Contacts API
The Nylas Contacts API connects address books and contact databases associated with users' email accounts directly into your application. It offers full Create, Read, Update, and Delete (CRUD) operations to perform bi-directional sync with contact data including addresses, email addresses, birthdays, job titles, and more.
Read Contact Information
import java.io.IOException;
import java.util.List;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Contact;
import com.nylas.ContactQuery;
public class ReadContacts {
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");
List<Contact> contacts = account.contacts().list(new ContactQuery().limit(10));
contacts.stream().forEach((Contact contact) -> {
System.out.printf(
"Name: %s %s | Email %s | ID: %s\n",
contact.getGivenName(),
contact.getSurname(),
contact.getEmails().get(0).getEmail(),
contact.getId());
});
}
}
Create New Contact
import java.io.IOException;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Contact;
import java.util.Arrays;
public class CreateContact {
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");
Contact contact = new Contact();
// The contact's given name is typically their first name,
// you can specify a last name with 'surname'
contact.setGivenName("My Nylas Friend");
// Email address 'type' must be either 'work' or 'personal'
contact.setEmails(Arrays.asList(new Contact.Email("work", "[email protected]")));
contact.setNotes("Email, Calendar, and Contacts APIs");
// Phone number type must be one of 'business', 'organization_main',
// 'mobile', 'assistant', 'business_fax', 'home_fax', 'radio', 'car', 'home', or 'pager'
// Google labels 'business' phone numbers as the contact's Work phone number
contact.setPhoneNumbers(Arrays.asList(new Contact.PhoneNumber("mobile", "555-555-5555")));
// Web page type must be one of 'homepage', 'profile', 'work', or 'blog'
contact.setWebPages(Arrays.asList(new Contact.WebPage("homepage", "https://nylas.com")));
// Save the contact to Nylas and the 3rd party provider
contact = account.contacts().create(contact);
System.out.println(contact);
}
}
Learn More
Check out the API reference docs for the contacts endpoint to learn more. You can also take a look at the contacts API quickstart guide to learn more about the functionality of the Nylas contacts API.
Additional Functionality
The Java SDK GitHub repo contains a number of useful examples in the examples directory that demonstrate how to handle things like webhooks, native authentication for Gmail and Exchange, and hosted OAuth.
Authentication
The Nylas REST API uses server-side (three-legged) OAuth, and this library provides convenience methods to simplify the OAuth process. Here's how it works:
- You redirect the user to our login page, along with your App Id and Secret
- Your user logs in
- They are redirected to a callback URL you provide which includes a one-time-use access code
- You use this access code to get an account access token that provides full access to the account
- For more information about authenticating with Nylas, check our the Authentication Guide.
In practice, the Nylas REST API client simplifies this down to two steps.
Step 1: Redirect User to Nylas
import java.io.IOException;
import com.nylas.RequestFailedException;
import com.nylas.NylasApplication;
import com.nylas.NylasClient;
import com.nylas.HostedAuthentication;
import com.nylas.Scope;
public class RedirectUser {
public static void hostedAuthExample() throws IOException, RequestFailedException {
NylasClient nylas = new NylasClient();
NylasApplication application = nylas.application("{CLIENT_ID}", "{CLIENT_SECRET}");
HostedAuthentication authentication = application.hostedAuthentication();
String hostedAuthUrl = authentication.urlBuilder()
.redirectUri("https://example.com/redirect")
.responseType("code") // Use token for client-side apps
.scopes(Scope.EMAIL, Scope.CALENDAR, Scope.CONTACTS)
.loginHint("[email protected]")
.state("example_csrf_token")
.buildUrl();
// This is the URL you need to send the user to to authenticate their account.
System.out.println(hostedAuthUrl);
// If you use response type "code", Nylas will return a unique, one-time-use code after your user authenticates.
// This code can be used to create an access token that grants access to the user account.
// See: https://developer.nylas.com/docs/api/v2/#post-/oauth/token
}
}
The Nylas API provides granular authentication scopes that empower users with control over what level of access your application has to their data. Pass a comma-separated string of scopes
to the scopes argument for the authentication_url
method. See supported authentication scopes for a full list of scopes and details behind the scopes.
Step 2: Handle the Authentication Response
import java.io.IOException;
import com.nylas.RequestFailedException;
import com.nylas.NylasApplication;
import com.nylas.NylasClient;
import com.nylas.NylasAccount;
import com.nylas.HostedAuthentication;
public class NylasExamples {
public static void hostedTokenExample() throws IOException, RequestFailedException {
NylasClient nylas = new NylasClient();
// Create a client that has access to your Nylas app.
NylasApplication application = nylas.application("{CLIENT_ID}", "{CLIENT_SECRET}");
HostedAuthentication authentication = application.hostedAuthentication();
// Get an access token that grants access to user data and functionality.
// You need to generate a one-time-use code via Nylas to pass to this function.
// See: https://developer.nylas.com/docs/api/v2/#get-/oauth/authorize
String accessToken = authentication.fetchToken("{code}").getAccessToken();
// Now you have a Nylas client object that has access to user data and functionality
NylasAccount account = nylas.account(accessToken);
}
}
Message Tracking
import com.nylas.NylasClient;
import com.nylas.NylasAccount;
import com.nylas.Tracking;
import com.nylas.Draft;
import com.nylas.NameEmail;
import java.util.Arrays;
public class NylasExamples {
public static void messageTrackingExample() throws Exception {
NylasClient nylas = new NylasClient();
NylasAccount account = nylas.account("{ACCESS_TOKEN}");
Draft draft = new Draft();
draft.setSubject("With Love, From Nylas");
draft.setTo(Arrays.asList(new NameEmail("My Nylas Friend", "[email protected]")));
draft.setBody("This email was sent using the Nylas email API. Visit https://nylas.com for details.");
Tracking tracking = new Tracking();
tracking.setOpens(true);
tracking.setLinks(true);
tracking.setThreadReplies(true);
tracking.setPayload("my-payload");
draft.setTracking(tracking);
account.drafts().send(draft);
}
}