Nylas Docs

The Nylas Developer Hub

Welcome to the Nylas developer hub. You'll find comprehensive guides and documentation to help you start working with Nylas as quickly as possible, as well as support if you get stuck. Let's jump right in!

Developer Guide

Java SDK

The Nylas Java SDK Quickstart Guide

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.

👍

Setup your developer account first!

Before following this guide, sign up for a Nylas developer account, and follow our guide to get your developer API keys.

Create Your Developer Account

Before you install the SDK, sign up for a Nylas developer account, and follow our guide to get your developer API keys. You will need three values from this guide to run the code examples found here:

  • 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 that is provided when you authenticate an account to your Nylas App

Install the Nylas Java SDK

Note: The Nylas Java SDK requires Java 8 or above.

For the following examples, replace X.X.X with the version you want to use. Take a look at the list of releases to learn about the versions that are available.

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

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

Install via 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>

Quickstart Examples

Create a Client Object to Connect to Your Nylas App

All of the functionality of the Nylas Communications Platform is available through the NylasClient object. There are two ways to initialize a NylasClient: for a Nylas App and for an individual user account.

*Create Nylas App Client For Account Management
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()
        );
    }   
}
Ready to Build Your Integration?

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. They contain several pieces of information, such as when a 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 to match the format of third-party accounts as close as possible.

Read Email Messages and Threads

import java.util.List;

import com.nylas.Message;
import com.nylas.MessageQuery;
import com.nylas.Thread;
import com.nylas.ThreadQuery;
import com.nylas.NameEmail;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;

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
        Message message = messages.list(new MessageQuery().limit(1)).get(0);
        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);        
        List<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                        
            );
        }
    }    
}
Ready to Build Your Email Integration?

View the API reference for messages and threads to learn more. You can also check out the email API quickstart 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());   
        }
    
}

View the API reference for messages and threads to learn more. You can also check out the email API quickstart 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);

  } 
}
Ready to Build Your Email Integration?

View the API reference for sending to learn more. You can also check out the email API quickstart 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: https://docs.nylas.com/reference#account
    if (accountDetail.getOrganizationUnit().equals("label")) { // Gmail uses labels

      // Labels reference: https://docs.nylas.com/reference#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: https://docs.nylas.com/reference#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 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");

    // Event times are set via UTC timestamps
    long time = LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond();
    // CALENDAR_ID must be the value of a calendar the user account has write access to.
    Event event = new Event("CALENDAR_ID", new Timespan(time, time+3600));
    event.setTitle("Party!");
    event.setLocation("My House!");

    // Participants can be added via a list of participant subobjects
    Participant participant = new Participant("[email protected]");
    participant.name("My Friend");
    event.setParticipants(Arrays.asList(participant));

    // Pass the event and boolean to represent notify_participants to create a new event
    Event createdEvent = account.events().create(event, true);
    System.out.println(createdEvent);
  } 
}
Ready to Build Your Calendar Integration?

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 quickstart 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);
  } 
}
Ready to Build Your Contacts Integration?

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:

  1. You redirect the user to our login page, along with your App Id and Secret
  2. Your user logs in
  3. They are redirected to a callback URL you provide which includes a one-time-use access code
  4. You use this access code to get an account access token that provides full access to the account
  5. 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://docs.nylas.com/reference#oauthtoken
    }
}

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://docs.nylas.com/reference#oauthauthorize
        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);
  } 
}

Updated 3 months ago

Java SDK


The Nylas Java SDK Quickstart Guide

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.