Version:
Only show these results:

Using the v2 Nylas Email API

This page explains how to use the Nylas Email API. You'll learn how to do the following tasks:

  • Read email messages and threads.
  • Search email messages and threads.
  • Modify and delete email messages, threads, folders, labels, and attachments.
  • Manage folders and labels.

One-click unsubscribe requirements for Google messages

As of February 2024, Google requires that users who send more than 5,000 email messages per day to Gmail email addresses include one-click unsubscribe headers in each of their marketing and subscribed emails (see Google’s official Email sender guidelines). This is along with the visible unsubscribe links that must be in the body content of all marketing and subscribed email messages.

To set up one-click unsubscribe headers, include the custom_headers object in your Send Message request. This object accepts a set of key-value pairs, each of which represents the header’s name and its value. You must include the following headers:

  • List-Unsubscribe-Post: List-Unsubscribe=One-Click
  • List-Unsubscribe: The unsubscribe link (for example, a mailto link that uses the end user’s email address, or a link to your list management software).
"custom_headers":[
{
"name": "List-Unsubscribe-Post",
"value": "List-Unsubscribe=One-Click"
},
{
"name": "List-Unsubscribe",
"value": "<mailto: nyla@example.com?subject=unsubscribe>, <https://mailinglist.example.com/unsubscribe.html>"
}
]

Read email messages from inboxes

Messages are the fundamental object in the Nylas platform, and the core building block for most email applications. They contain several pieces of information, such as the message's timestamp, the sender's address, the recipients, and the body of the message. They can also contain file attachments, calendar invites, and more.

By default, the Messages endpoint returns the 100 most recent messages, but the following examples limit the number of results to five. See the Pagination reference documentation to learn how to use limits and offsets to control the number of objects that Nylas returns.

The following examples show how to return the five most recent email messages from an account's inbox by making a request to the Nylas Email API.

[{
"account_id": "qmlclekd5d3bgscbhhkf",
"bcc": [],
"body": "<html>\n<head>\n <meta charset=\"UTF-8\">\n <style type=\"text/css\">\n html {\n -webkit-text-size-adjust:none;\n }\n body {\n width:100%;\n margin:0 auto;\n padding:0;\n}\n p {\n width:280px;\n line-height: 16px;\n letter-spacing: 0.5px;\n }\n </style>\n <title>Welcome ... </html>",
"cc": [],
"date": 1557950729,
"events": [],
"files": [],
"folder": {
"display_name": "Inbox",
"id": "kekzhtt9hmrsad98xjzj",
"name": "inbox"
},
"from": [{
"email": "swag@example.com",
"name": "My Nylas Friend"
}],
"id": "j2zpf8cju20cmzj64uj6",
"object": "message",
"reply_to": [{
"email": "swag@example.com",
"name": "My Nylas Friend"
}],
"snippet": "Use Nylas for your email integration!",
"starred": false,
"subject": "Welcome to Nylas",
"thread_id": "w2kh2bfjvzsgfpkb3b0t",
"to": [{
"email": "you@example.com",
"name": "Your Company"
}],
"unread": true
}]

You can also get email messages from your end users' inboxes using the Nylas SDKs.

require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
messages = nylas.messages.limit(5)

messages.each{ |message|
date = Time.at(message.date)
puts("[#{date}] #{message.subject}")
}
import java.io.IOException;
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 com.nylas.MessageQuery;

public class ReadInbox {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Messages messages = account.messages();
RemoteCollection<Message> messageList = messages.list(new MessageQuery().limit(5));

for(Message email : messageList) {
System.out.println(email.getDate() + " " + email.getSubject());
}
}
}

Read threads from inboxes

Threads are first-class objects that represent collections of email messages that are related to one another. They result from participants replying to an email conversation. As objects, Threads enable you to build beautiful email applications which behave in the ways your end users have come to expect. For Google and Microsoft Exchange accounts, Nylas threads email messages together so they are as similar as possible to their representation in those environments.

Similar to the examples in Read email messages from inboxes, the examples in this section limit the number of threads that Nylas returns to five.

The following examples show how to return the five most recent threads from an account using the Nylas APIs.

curl -X GET 'https://api.nylas.com/threads?limit=5' \
-H 'Authorization: Bearer ACCESS_TOKEN'
[{
"account_id": "qmlclekd5d3bgscbhhkf",
"draft_ids": [],
"first_message_timestamp": 1557950729,
"folders": [{
"display_name": "Inbox",
"id": "j2zpf8cju20cmzj64uj6",
"name": "inbox"
}],
"has_attachments": false,
"id": "kekzhtt9hmrsad98xjzj",
"last_message_received_timestamp": 1557950729,
"last_message_sent_timestamp": null,
"last_message_timestamp": 1557950729,
"message_ids": [ "mf4jy5rf06d4l9upl8xb" ],
"object": "thread",
"participants": [
{
"email": "swag@example.com",
"name": "My Nylas Friend"
},
{
"email": "you@example.com",
"name": "Your Company"
}
],
"snippet": "Use Nylas for your email integration!",
"starred": false,
"subject": "Welcome to Nylas!",
"unread": false,
"version": 1
}]

You can also use the Nylas SDKs to get the most recent threads in an end user's inbox.

require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
threads = nylas.threads.limit(5)

threads.map.with_index { |thread, i|
puts("Thread #{i}")
participants = thread.participants

participants.each{ |participant|
puts(
"Subject: #{thread.subject} | "\
"Participant: #{participant.name} | "\
"Email: #{participant.email}"
)
}
}
import java.io.IOException;
import java.util.List;
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Thread;
import com.nylas.Threads;
import com.nylas.ThreadQuery;
import com.nylas.NameEmail;

public class ReadThreads {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Threads threads = account.threads();
List<Thread> thread = threads.list(new ThreadQuery().in("inbox").limit(5)).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();
}
}
}
}

These examples use the views feature, which allows you to customize Nylas' response. In this case, the request specifies the expanded view, which expands the Threads object to include all Message and Draft sub-objects.

Search an inbox for email messages

You can use the Search sub-endpoint and the Nylas SDKs to run a full-text search for email messages on an account's provider, as in the examples below. Nylas returns 40 results by default.

curl -X GET \
https://api.nylas.com/messages/search?q=hello \
-H 'Authorization: Basic WVVUWjZ****' \
require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
messages = nylas.messages.search("hello")

messages.each{ |message|
puts(message.subject)
}
import java.io.IOException;
import java.util.List;
import com.nylas.*;

public class SearchInbox {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Messages messages = account.messages();
List<Message> results = messages.search("hello", 5, 0).fetchAll();

for(Message message : results) {
System.out.println(message.getSubject());
}
}
}

Search an inbox for threads

The following examples show how to search an inbox for threads using the v2 Nylas APIs and SDKs.

curl -X GET \
https://api.nylas.com/threads/search?q=hello \
-H 'Authorization: Basic WVVUWjZ****' \
require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
messages = nylas.threads.search("hello")

messages.each{ |message|
puts(message.subject)
}
import java.io.IOException;
import java.util.List;
import com.nylas.*;
import com.nylas.Thread;

public class SearchThreads {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Threads threads = account.threads();
List<Thread> results = threads.search("hello",5, 0).fetchAll();

for(Thread thread : results) {
System.out.println(thread.getSubject());
}
}
}

Send an email message

Nylas sends all email messages through end users' original SMTP/ActiveSync gateways, just as if they were sent using any other app. This means that email messages sent through Nylas have very high deliverability, but might be subject to rate-limiting and abuse detection from the provider. See Improve email deliverability for more information and best practices.

⚠️ These examples send real email messages. Be sure to send it to an email address that is different than the account you're sending it from.

The following examples show how to send an email message with the Nylas Email API.

curl --request POST \
--url https://api.nylas.com/send \
--header 'Accept: application/json, application/gzip' \
--header 'Authorization: Bearer <ACCESS_TOKEN>' \
--header 'Content-Type: application/json' \
--data '{
"subject": "From Nylas",
"to": [{
"email": "swag@example.com",
"name": "Nylas"
}],
"cc": [{
"name": "Dorothy Vaughan",
"email": "dorothy@example.com"
}],
"bcc": [{
"name": "Hedy Lamarr",
"email": "Lamarr@example.com"
}],
"from": [{
"name": "Your Name",
"email": "you@example.com"
}],
"reply_to": [{
"name": "Nylas",
"email": "swag@example.com"
}],
"reply_to_message_id": "<MESSAGE_ID>",
"body": "This email was sent using the Nylas Email API. Visit https://nylas.com for details.",
"file_ids": [
"<FILE_ID>",
"<FILE_ID>"
]
}'
{
"account_id": "{account_id}",
"bcc": [{
"email": "Albert Einstein",
"name": "al@example.com"
}],
"body": "<html>\\n<head>\\n <meta charset=\\\"UTF-8\\\">\\n <style type=\\\"text/css\\\">\\n html {\\n -webkit-text-size-adjust:none;\\n }\\n body {\\n width:100%;\\n margin:0 auto;\\n padding:0;\\n}\\n p {\\n width:280px;\\n line-height: 16px;\\n letter-spacing: 0.5px;\\n }\\n </style>\\n <title>Welcome ... </html>",
"cc": [{
"email": "George Washington Carver",
"name": "carver@example.com"
}],
"date": 1557950729,
"events": [{}],
"files": [{
"content_disposition": "attachment",
"content_type": "image/jpeg",
"filename": "image.jpeg",
"id": "{image_id}",
"size": 2648890
}],
"folder": {
"display_name": "string",
"id": "string",
"name": "string"
},
"from": [{
"name": "Marie Curie",
"email": "marie@example.com"
}],
"id": "string",
"object": "message",
"reply_to": [{
"email": "skwolek@example.com",
"name": "Stephanie Kwolek"
}],
"snippet": "string",
"starred": true,
"subject": "string",
"thread_id": "string",
"to": [{
"email": "dorothy@example.com",
"name": "Dorothy Vaughan"
}],
"unread": true,
"labels": [{
"display_name": "Important",
"id": "{label_id}",
"name": "important"
}]
}

You can also send email messages using the Nylas SDKs.

require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
file = nylas.files.create(file: File.open(File.expand_path('RubyLogo.png'), 'r')).to_h

draft = nylas.drafts.create(to: [{ email: 'swag@example.com', name: 'Nylas' }],
cc: [{ email: 'dorothy@example.com',
name: 'Dorothy Vaughan' }],
bcc: [{ email: 'Lamarr@example.com',
name: 'Hedy Lamarr' }],
subject: 'From Nylas',
body: 'This email was sent using the Nylas Email API. Visit https://nylas.com for details.',
file_ids: [file[:id]])

begin
nylas.outbox.send(draft)
rescue StandardError => e
puts e.message
end
import java.lang.Exception;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
import com.nylas.*;

public class SendEmail {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");

Files files = account.files();
byte[] myFile = java.nio.file.Files.readAllBytes(Paths.get("src/main/java/JavaLogo.png"));
File upload = files.upload("JavaLogo.png", "image/png", myFile);

Draft draft = new Draft();

draft.setSubject("From Nylas");
draft.setBody("This email was sent using the Nylas email API. Visit https://nylas.com for details.");
draft.setTo(List.of(new NameEmail("Nylas", "swag@example.com")));
draft.setCc(List.of(new NameEmail("Dorothy Vaughan", "dorothy@example.com")));
draft.setBcc(List.of(new NameEmail("Hedy Lamarr", "Lamarr@example.com")));
draft.attach(upload);

try {
account.drafts().send(draft);
System.out.println( "The Email was sent successfully" );
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
}

Modify and delete inbox content

Most Nylas Email API endpoints allow you to modify objects using PUT and POST requests. You can make the following changes:

  • Threads and Messages: Modify labels, unread status, stars, and folders. See the Threads and Messages reference documentation for more information.
  • Folders and Labels: Update folder and label names. See the Folders and Labels reference documentation for more information.
  • Files: Upload files to use as attachments. See the Files reference documentation for more information.

You can also make DELETE requests to certain endpoints. This allows you to delete existing objects, such as Folders.

Inbox folders and labels

Folders and labels are fundamental when organizing and managing email inboxes. All accounts that are authenticated to Nylas provide access to only one of these two objects, but they behave in a similar manner. Email messages can have multiple labels, but are contained in only one folder. For more information, see the Folders and Labels reference documentation.

Check Organization Unit parameter

You can use Nylas v2 to determine whether a connected account supports folders or labels by making a GET /account request and checking the organization_unit value.

curl -X GET \
https://api.nylas.com/account \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-H 'Content-Type: application/json' \
-H 'cache-control: no-cache'
{
"id": "awa6ltos76vz5hvphkp8k17nt",
"account_id": "awa6ltos76vz5hvphkp8k17nt",
"object": "account",
"name": "Ben Bitpusher",
"email_address": "benbitpusher@example.com",
"provider": "gmail",
"organization_unit": "label",
"sync_state": "running",
"linked_at": 1470231381,
}
require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
account = nylas.current_account

puts "#{account.id} | #{account.account_id} | #{account.object}" \
"#{account.name} | #{account.email_address} | " \
"#{account.provider} | #{account.organization_unit} | " \
"#{account.sync_state} | #{account.linked_at}"
import java.io.IOException;
import com.nylas.*;

public class GetAccount {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
NylasApplication application = client.application("<NYLAS_CLIENT_ID>", "<NYLAS_CLIENT_SECRET>");
Accounts accounts = application.accounts();

for(Account current_account : accounts.list()) {
System.out.println(current_account.getId() + " | " +
current_account.getEmail() + " | " +
current_account.getProvider() + " | " +
current_account.getSyncState());
}
}
}

View an account's folders and labels

To view all labels that an account has configured in Nylas v2, make a GET /labels request or use the Nylas SDKs.

curl -X GET 'https://api.nylas.com/labels' \
-H 'Authorization: Bearer ACCESS_TOKEN'
require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
labels = nylas.labels

labels.map.with_index { |label, i|
puts("Label #{i}")
puts("#{label.display_name} | #{label.name} | #{label.object}" \
"#{label.account_id} | #{label.account_id} | " \
"#{label.provider_id} #{label.id}")
}
import java.lang.Exception;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.nylas.*;

public class ReadLabels {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Labels labels = account.labels();
int index=0;

for(Label label : labels.list())
System.out.println((index++)+": "+ label.getDisplayName() +
" | " + label.getName() + " | " +
" | " + label.getObjectType() +
" | " + label.getAccountId() +
" | " + label.getId());
}
}

Create folders and labels

To create a folder or label in Nylas v2, make one of the following requests:

The examples below show how to create a label by making a request to the Nylas Email API and by using the Nylas SDKs.

curl -X POST 'https://api.nylas.com/labels' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-d '{ "display_name": "My New Label" }'
require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
label = nylas.labels.create(display_name: "My Custom label")

puts "#{label.id} | #{label.display_name}"
import java.io.IOException;
import com.nylas.*;

public class CreateLabels {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");

Labels labels = account.labels();
Label label = labels.create("My Custom label");

System.out.println(label.getId() + " | " + label.getDisplayName());
}
}

Delete folders and labels

You can delete folders and labels in Nylas v2 by making one of the following requests:

The examples below show how to delete a label by making a request to the Nylas Email API, and using the Nylas SDKs.

curl -X DELETE 'https://api.nylas.com/labels/{id}' \
-H 'Authorization: Bearer ACCESS_TOKEN'
require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
label = nylas.labels.find('{id}')

label.destroy
import java.io.IOException;
import com.nylas.*;

public class UpdateMessage {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");
Labels label = account.labels();
String output = label.delete("<LABEL_ID>");

System.out.println("Job Id: " + output);
}
}

Add labels to email messages

To add a label to an email message in Nylas v2, you need the id of both the folder or label you want to add, and the message you want to modify.

To get the folder or label ID, make a Return all Folders request or Return all Labels request and find the folder or label you want to use. To get the message ID, make a Return all Messages request and find the email message that you want to modify.

When you have both IDs, make an Update Message request. This overwrites any labels that are currently assigned to the email message.

curl -X PUT 'https://api.nylas.com/messages/{message_id}' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-d '{ "label_ids": ["{label_id}", "{label_id}"] }'
require 'nylas'

nylas = Nylas::API.new(APP_ID, APP_SECRET, ACCESS_TOKEN)
message = nylas.messages.find('{id}')

message.update(label_ids: ['{label_id}'])
message.save
import java.io.IOException;
import java.util.Collections;
import com.nylas.*;

public class UpdateMessage {
public static void main(String[] args) throws RequestFailedException, IOException {
NylasClient client = new NylasClient();
NylasAccount account = client.account("<ACCESS_TOKEN>");

Messages messages = account.messages();
messages.setLabelIds("<MESSAGE_ID>", Collections.singleton("<LABEL_ID>"));
Message message = account.messages().get("<MESSAGE_ID>");

System.out.println(message.getFolder());
}
}