Only show these results:

Using the Nylas Email API

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

  • Read content from an account's inbox.
  • Search for email messages and threads.
  • Send email messages.
  • Update an email message's labels, file attachments, unread status, stars, folders, and more.
  • Delete drafts, files, and folders.

Before you begin

To follow along with the samples on this page, you first need to sign up for a Nylas developer account, which gets you a free Nylas application and API key.

For a guided introduction, you can follow the Getting started guide to set up a Nylas account and Sandbox application. When you have those, you can connect an account from a calendar provider (such as Google, Microsoft, or iCloud) and use your API key with the sample API calls on this page to access that account's data.

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 using Nylas, include the custom_headers object in your Send Message or Create Draft 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: [email protected]?subject=unsubscribe>, <http://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 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.

curl --request GET \
--url "https://api.us.nylas.com/v3/grants/NYLAS_GRANT_ID/messages?limit=5" \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>' \
--header 'Content-Type: application/json'
{
"request_id": "d0c951b9-61db-4daa-ab19-cd44afeeabac",
"data": [
{
"starred": false,
"unread": true,
"folders": [
"UNREAD",
"CATEGORY_PERSONAL",
"INBOX"
],
"grant_id": "1",
"date": 1706811644,
"attachments": [
{
"id": "1",
"grant_id": "1",
"filename": "invite.ics",
"size": 2504,
"content_type": "text/calendar; charset=\"UTF-8\"; method=REQUEST"
},
{
"id": "2",
"grant_id": "1",
"filename": "invite.ics",
"size": 2504,
"content_type": "application/ics; name=\"invite.ics\"",
"is_inline": false,
"content_disposition": "attachment; filename=\"invite.ics\""
}
],
"from": [
{
"name": "Nylas DevRel",
"email": "[email protected]"
}
],
"id": "1",
"object": "message",
"snippet": "Send Email with Nylas APIs",
"subject": "Learn how to Send Email with Nylas APIs",
"thread_id": "1",
"to": [
{
"name": "Nyla",
"email": "[email protected]"
}
],
"created_at": 1706811644,
"body": "Learn how to send emails using the Nylas APIs!"
}
],
"next_cursor": "123"
}

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

from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")

messages = nylas.messages.list(
grant_id,
query_params={
"limit": 5
}
)

print(messages)
app.get("/nylas/recent-emails", async (req, res) => {
try {
const identifier = process.env.USER_GRANT_ID;
const messages = await nylas.messages.list({
identifier,
queryParams: {
limit: 5,
},
});

res.json(messages);
} catch (error) {
console.error("Error fetching emails:", error);
}
});
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
query_params = { limit: 5 }
messages, _ = nylas.messages.list(identifier: '<GRANT_ID>', query_params: query_params)

messages.each {|message|
puts "[#{Time.at(message[:date]).strftime("%d/%m/%Y at %H:%M:%S")}] \
#{message[:subject]}"

}
import com.nylas.NylasClient;
import com.nylas.models.*;
import java.text.SimpleDateFormat;

public class ReadInbox {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
ListMessagesQueryParams queryParams = new ListMessagesQueryParams.Builder().limit(5).build();
ListResponse<Message> message = nylas.messages().list("<GRANT_ID>", queryParams);

for(Message email : message.getData()) {
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
format(new java.util.Date((email.getDate() * 1000L)));

System.out.println("[" + date + "] | " + email.getSubject());
}
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import java.text.SimpleDateFormat
import java.util.*

fun dateFormatter(milliseconds: String): String {
return SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Date(milliseconds.toLong() * 1000)).toString()
}

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
val queryParams = ListMessagesQueryParams(limit = 5, inFolder = listOf("Inbox"))
val messages : List<Message> = nylas.messages().list("<GRANT_ID>", queryParams).data

for(message in messages) {
println("[" + dateFormatter(message.date.toString()) + "] |" + message.subject + " | " + message.folders)
}
}

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 --request GET \
--url "https://api.us.nylas.com/v3/grants/NYLAS_GRANT_ID/threads?limit=5" \
--header 'Accept: application/json' \
--header "Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>' \
--header '
Content-Type: application/json'
{
"request_id": "1",
"data": [
{
"starred": false,
"unread": true,
"folders": [
"CATEGORY_PERSONAL",
"INBOX",
"UNREAD"
],
"grant_id": "1",
"id": "1",
"object": "thread",
"latest_draft_or_message": {
"starred": false,
"unread": true,
"folders": [
"UNREAD",
"CATEGORY_PERSONAL",
"INBOX"
],
"grant_id": "1",
"date": 1707836711,
"from": [
{
"name": "Nyla",
"email": "[email protected]"
}
],
"id": "1",
"object": "message",
"snippet": "Send Email with Nylas APIs",
"subject": "Learn how to Send Email with Nylas APIs",
"thread_id": "1",
"to": [
{
"email": "[email protected]"
}
],
"created_at": 1707836711,
"body": "Learn how to send emails using the Nylas APIs!"
},
"has_attachments": false,
"has_drafts": false,
"earliest_message_date": 1707836711,
"latest_message_received_date": 1707836711,
"participants": [
{
"email": "[email protected]"
}
],
"snippet": "Send Email with Nylas APIs",
"subject": "Learn how to Send Email with Nylas APIs",
"message_ids": [
"1"
]
}
],
"next_cursor": "123"
}
import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)

async function fetchRecentThreads() {
try {
const identifier = process.env.NYLAS_GRANT_ID
const threads = await nylas.threads.list({
identifier,
queryParams: {
limit: 5,
}
})

console.log('Recent Threads:', threads)
} catch (error) {
console.error('Error fetching threads:', error)
}
}

fetchRecentThreads()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")

threads = nylas.threads.list(
grant_id,
query_params={
"limit": 5
}
)

print(threads)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
query_params = { limit: 5 }
threads, _ = nylas.threads.list(identifier: '<GRANT_ID>', query_params: query_params)

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 com.nylas.NylasClient;
import com.nylas.models.*;
import com.nylas.models.Thread;
import java.text.SimpleDateFormat;
import java.util.List;

public class ReadThreads {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
ListThreadsQueryParams queryParams = new ListThreadsQueryParams.Builder().limit(5).build();
ListResponse<Thread> thread = nylas.threads().list("<GRANT_ID>", queryParams);

for(Thread message : thread.getData()) {
List<EmailName> participants = message.getParticipants();
assert participants != null;

for(EmailName participant : participants) {
System.out.println("Subject: " + message.getSubject() +
" | Participant: " + participant.getName() +
" | Email: " + participant.getEmail());
}
}
}
}
import com.nylas.NylasClient
import com.nylas.models.*

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
val queryParams = ListThreadsQueryParams(limit = 5)
val threads : List<Thread> = nylas.threads().list("<GRANT_ID>", queryParams).data

for(message in threads) {
var participants = message.participants

if (participants != null) {
for(participant : EmailName in participants){
println("Subject: " + message.subject + " | Participant: " + participant.name + " | " + participant.email)
}
}
}
}

Search an inbox for email messages

In Nylas v3 you add query parameters to a Return all Messages request to search for email messages. For more information, see the Messages reference documentation.

The following examples show how to search an end user's inbox for email messages using the Nylas SDKs.

import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)

async function searchInbox(): Promise<void> {
try {
const result = await nylas.messages.list({
identifier: process.env.GRANT_ID,
queryParams: {
search_query_native: 'nylas',
limit: 5
}
})

console.log('search results:', result)
} catch (error) {
console.error('Error to complete search:', error)
}
}

searchInbox()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("GRANT_ID")

messages = nylas.messages.list(
grant_id,
query_params={
"limit": 5,
"search_query_native": 'nylas'
}
)

print(messages)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
query_params = {limit: 5, search_query_native: "subject: hello"}
messages, _ = nylas.messages.list(identifier: '<GRANT_ID>', query_params: query_params)

messages.each {|message|
puts "[#{Time.at(message[:date]).strftime("%d/%m/%Y at %H:%M:%S")}] \
#{message[:subject]}"

}
import com.nylas.NylasClient;
import com.nylas.models.*;
import java.text.SimpleDateFormat;
import com.nylas.models.Thread;
import java.util.List;

public class SearchInbox {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

ListMessagesQueryParams queryParams = new ListMessagesQueryParams.Builder().
searchQueryNative("subject: hello").
limit(5).
build();

ListResponse<Message> message = nylas.messages().list("<GRANT_ID>", queryParams);

for(Message email : message.getData()) {
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
format(new java.util.Date((email.getDate() * 1000L)));

System.out.println("[" + date + "] | " + email.getSubject());
}
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import java.text.SimpleDateFormat
import java.util.*

fun dateFormatter(milliseconds: String): String {
return SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(Date(milliseconds.toLong() * 1000)).toString()
}

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = "NYLAS_API_KEY")
val queryParams = ListMessagesQueryParams(limit = 5, searchQueryNative = "subject: hello")
val messages : List<Message> = nylas.messages().list("<GRANT_ID>", queryParams).data

for(message in messages) {
println("[" + dateFormatter(message.date.toString()) + "] |" + message.subject)
}
}

Search an inbox for threads

In Nylas v3 you add query parameters to a Return all Threads request to search for threads. For more information, see the Threads reference documentation.

The following examples show how to search an end user's inbox for threads using the v3 Nylas SDKs.

import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)

async function searchInbox(): Promise<void> {
try {
const result = await nylas.threads.list({
identifier: process.env.GRANT_ID,
queryParams: {
search_query_native: 'nylas',
limit: 5
}
})

console.log('search results:', result)
} catch (error) {
console.error('Error to complete search:', error)
}
}

searchInbox()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("GRANT_ID")

messages = nylas.threads.list(
grant_id,
query_params={
"limit": 5,
"search_query_native": 'nylas'
}
)

print(messages)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
query_params = { search_query_native: "subject: hello" }
threads, _ = nylas.threads.list(identifier: '<GRANT_ID>', query_params: query_params)

threads.each { | thread |
puts thread[:subject]
}
import com.nylas.NylasClient;
import com.nylas.models.*;
import java.text.SimpleDateFormat;
import com.nylas.models.Thread;
import java.util.List;

public class SearchThreads {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

ListThreadsQueryParams queryParams = new ListThreadsQueryParams.Builder().
searchQueryNative("subject: hello").
limit(5).
build();

ListResponse<Thread> thread = nylas.threads().list("<GRANT_ID>", queryParams);

for(Thread email : thread.getData()) {
System.out.println(email.getSubject());
}
}
}
import com.nylas.NylasClient
import com.nylas.models.*

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = dotenv["NYLAS_API_KEY"])
val queryParams = ListThreadsQueryParams(limit = 5, searchQueryNative = "subject: hello")
val threads : List<com.nylas.models.Thread> = nylas.threads().list("GRANT_ID>", queryParams).data

for(thread in threads) {
println(thread.subject)
}
}

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.us.nylas.com/v3/grants/<NYLAS_GRANT_ID>/messages/send \
--header 'Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>' \
--header 'Content-Type: application/json' \
--data '{
"subject": "Hey Reaching Out with Nylas",
"body": "Hey I would like to track this link <a href='https://espn.com'>My Example Link</a>",
"to": [
{
"name": "John Doe",
"email": "[email protected]"
}
],
"tracking_options": {
"opens": true,
"links": true,
"thread_replies": true,
"label": "hey just testing"
}
}'
{
"request_id": "1",
"data": {
"bcc": null,
"body": "Learn how to Send Email with Nylas APIs",
"cc": null,
"attachments": [],
"from": [
{
"email": "[email protected]"
}
],
"reply_to": null,
"subject": "Hey Reaching Out with Nylas",
"to": [
{
"name": "DevRel",
"email": "[email protected]"
}
],
"use_draft": false,
"tracking_options": {
"label": "hey just testing",
"links": true,
"opens": true,
"thread_replies": true
},
"date": 1707839231,
"grant_id": "1",
"id": "1",
"thread_id": "2"
}
}

You can also send email messages using the Nylas SDKs.

app.get("/nylas/send-email", async (req, res) => {
try {
const sentMessage = await nylas.messages.send({
identifier: process.env.USER_GRANT_ID,
requestBody: {
to: [{ name: "Name", email: process.env.EMAIL }],
replyTo: [{ name: "Name", email: process.env.EMAIL }],
subject: "Your Subject Here",
body: "Your email body here.",
},
});

res.json(sentMessage);
} catch (error) {
console.error("Error sending email:", error);
}
});
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")
email = os.environ.get("EMAIL")

message = nylas.messages.send(
grant_id,
request_body={
"to": [{ "name": "Name", "email": email }],
"reply_to": [{ "name": "Name", "email": email }],
"subject": "Your Subject Here",
"body": "Your email body here.",
}
)

print(message)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
file = Nylas::FileUtils.attach_file_request_builder("RubyLogo.png")

request_body = {
subject: 'From Nylas',
body: 'This email was sent using the Nylas email API. Visit https://nylas.com for details.',
to: [{name: "Nylas", email: "[email protected]"}],
cc: [{name: "Dorothy Vaughan", email: "[email protected]"}],
bcc: [{name: "Hedy Lamar", email: "[email protected]"}],
attachments: [file]
}

email = nylas.messages.send(identifier: ENV["GRANT_ID"], request_body: request_body)

puts email
import com.nylas.NylasClient;
import com.nylas.models.*;
import com.nylas.util.FileUtils;
import java.util.ArrayList;
import java.util.List;

public class SendEmails {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

List<EmailName> emailNames = new ArrayList<>();
emailNames.add(new EmailName("[email protected]", "Nylas"));
List<EmailName> cc_emails = new ArrayList<>();
cc_emails.add(new EmailName("[email protected]", "Dorothy Vaughan"));
List<EmailName> bcc_emails = new ArrayList<>();
bcc_emails.add(new EmailName("[email protected]", "Hedy Lamarr"));

CreateAttachmentRequest attachment = FileUtils.attachFileRequestBuilder("src/main/java/JavaLogo.png");
List<CreateAttachmentRequest> request = new ArrayList<>();
request.add(attachment);

SendMessageRequest requestBody = new
SendMessageRequest.Builder(emailNames).
cc(cc_emails).
bcc(bcc_emails).
subject("From Nylas").
body("This email was sent using the Nylas Email API. \n" +
"Visit <a href='https://nylas.com'>Nylas.com</a> for details.").
attachments(request).
build();

Response<Message> email = nylas.messages().send("<GRANT_ID>", requestBody);

System.out.println(email.getData());
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import com.nylas.util.FileUtils

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = dotenv["NYLAS_API_KEY"])
val attachment: CreateAttachmentRequest = FileUtils.attachFileRequestBuilder("src/main/kotlin/Kotlin_Logo.png")
val emailNames : List<EmailName> = listOf(EmailName("[email protected]", "Nylas"))

val requestBody : SendMessageRequest = SendMessageRequest.
Builder(emailNames).
cc(listOf(EmailName("[email protected]", "Dorothy Vaughan"))).
bcc(listOf(EmailName("[email protected]", "Hedy Lamarr"))).
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. " +
"Visit https://nylas.com for details.").
attachments(listOf(attachment)).
build()

val email = nylas.messages().send(dotenv["GRANT_ID"], requestBody)

print(email.data)
}

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 reference documentation for more information.
  • Files: Upload files to use as attachments. See the Attachments 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 have been combined in Nylas v3. For more information, see Changes to 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 reference documentation.

View an account's folders and labels

To view all folders and labels, make a Return all Folders request. Nylas returns, among other things, an id that you can use to modify the labels and attach them to email messages and threads.

curl --request GET \
--url https://api.us.nylas.com/v3/grants/NYLAS_GRANT_ID/folders/FOLDER_ID \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>' \
--header 'Content-Type: application/json'
{
"request_id": "1",
"data": [
{
"id": "CATEGORY_FORUMS",
"grant_id": "2",
"name": "CATEGORY_FORUMS",
"system_folder": true
},
{
"id": "CATEGORY_PERSONAL",
"grant_id": "2",
"name": "CATEGORY_PERSONAL",
"system_folder": true
},
{
"id": "CATEGORY_PROMOTIONS",
"grant_id": "2",
"name": "CATEGORY_PROMOTIONS",
"system_folder": true
},
{
"id": "CATEGORY_SOCIAL",
"grant_id": "2",
"name": "CATEGORY_SOCIAL",
"system_folder": true
},
{
"id": "CATEGORY_UPDATES",
"grant_id": "2",
"name": "CATEGORY_UPDATES",
"system_folder": true
},
{
"id": "CHAT",
"grant_id": "2",
"name": "CHAT",
"system_folder": true
},
{
"id": "DRAFT",
"grant_id": "2",
"name": "DRAFT",
"system_folder": true
},
{
"id": "IMPORTANT",
"grant_id": "2",
"name": "IMPORTANT",
"system_folder": true
},
{
"id": "INBOX",
"grant_id": "2",
"name": "INBOX",
"system_folder": true
},
{
"id": "SENT",
"grant_id": "2",
"name": "SENT",
"system_folder": true
},
{
"id": "SPAM",
"grant_id": "2",
"name": "SPAM",
"system_folder": true
},
{
"id": "STARRED",
"grant_id": "2",
"name": "STARRED",
"system_folder": true
},
{
"id": "TRASH",
"grant_id": "2",
"name": "TRASH",
"system_folder": true
},
{
"id": "UNREAD",
"grant_id": "2",
"name": "UNREAD",
"system_folder": true
}
]
}

You can also use the v3 Nylas SDKs, as in the examples below.

import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)

async function fetchFolders() {
try {
const folders = await nylas.folders.list({
identifier: process.env.NYLAS_GRANT_ID,
})

console.log('folders:', folders)
} catch (error) {
console.error('Error fetching folders:', error)
}
}

fetchFolders()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")
folder_id = os.environ.get("FOLDER_ID")

folder = nylas.folders.find(
grant_id,
folder_id
)

print(folder)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
labels, _ = nylas.folders.list('<GRANT_ID>')

labels.map.with_index { |label, i|
puts("Label #{i}")
puts("#{label[:id]} | #{label[:name]} | #{label[:system_folder]}")
}
import com.nylas.NylasClient;
import com.nylas.models.*;

public class ReadLabels {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
ListResponse<Folder> labels = nylas.folders().list("<GRANT_ID>");
int index=0;

for(Folder label : labels.getData())
System.out.println((index++)+": "+ label.getId() +
" | " + label.getName() + " | " +
" | " + label.getObject());
}
}
import com.nylas.NylasClient

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = dotenv["NYLAS_API_KEY"])
val labels = nylas.folders().list(dotenv["GRANT_ID"])
var index = 0

for (label in labels.data) println(
index++.toString() + ": " + label.id +
" | " + label.name + " | " +
" | " + label.getObject()
)
}

Create folders and labels

To create a folder or label, make a Create Folder request.

curl --location 'https://api.us.nylas.com/v3/grants/NYLAS_GRANT_ID/folders' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>' \
--data '{
"text_color": "#000000",
"name": "new folder",
"background_color": "#434343"
}'
{
"request_id": "1",
"data": {
"id": "Label_10",
"grant_id": "2",
"name": "name",
"total_count": 0,
"unread_count": 0,
"system_folder": false,
"text_color": "#000000",
"background_color": "#000000"
}
}

You can also use the v3 Nylas SDKs to create a folder or label.

import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)
const identifier = process.env.NYLAS_GRANT_ID

const createFolder = async () => {
try {
const folder = await nylas.folders.create({
identifier,
requestBody: {
name: 'New Folder'
}
})

console.log('Folder created:', folder)
} catch (error) {
console.error('Error creating folder:', error)
}
}

createFolder()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")

folder = nylas.folders.create(
grant_id,
request_body={
"name": 'New Folder',
"parent": None,
}
)

print(folder)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
request_body = { name: 'My Custom label' }
label, _ = nylas.folders.create(identifier: ENV["GRANT_ID"], request_body: request_body)

puts label
import com.nylas.NylasClient;
import com.nylas.models.*;

public class CreateLabels {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<V3_TOKEN_API")).build();
CreateFolderRequest request = new CreateFolderRequest("My Custom label", "", "", "");
Response<Folder> label = nylas.folders().create("<GRANT_ID>"), request);

System.out.println(label);
}
}
import com.nylas.NylasClient
import com.nylas.models.CreateFolderRequest

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = dotenv["NYLAS_API_KEY"])
val request = CreateFolderRequest("My Custom label")
val label = nylas.folders().create(dotenv["GRANT_ID"], request)

print(label)
}

Delete folders and labels

You can delete folders and labels by making a Delete Folder request, as in the following example.

curl --location --request DELETE 'https://api.us.nylas.com/v3/grants/NYLAS_GRANT_ID/folders/FOLDER_ID' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>'
{
"request_id": "1"
}

You can also delete a folder or label using the v3 Nylas SDKs.

import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)
const identifier = process.env.NYLAS_GRANT_ID
const folderId = process.env.FOLDER_ID

const deleteFolder = async () => {
try {
await nylas.folders.destroy({ identifier, folderId })
console.log(`Folder with ID ${folderId} deleted successfully.`)
} catch (error) {
console.error(`Error deleting folder with ID ${folderId}:`, error)
}
}

deleteFolder()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")
folder_id = os.environ.get("FOLDER_ID")

request = nylas.folders.destroy(
grant_id,
folder_id,
)

print(request)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
status, _ = nylas.folders.destroy(identifier: ENV["GRANT_ID"], folder_id: "Label_7")

puts status
import com.nylas.NylasClient;
import com.nylas.models.*;

public class DeleteLabels {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
DeleteResponse label = nylas.folders().destroy("<GRANT_ID>"), "<LABEL_ID>");

System.out.println(label);
}
}
import com.nylas.NylasClient
import com.nylas.models.UpdateMessageRequest

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = dotenv["NYLAS_API_KEY"])
val label = nylas.folders().destroy("<GRANT_ID>", "<LABEL_ID>")

print(label)
}

Add labels to email messages

To add a label to an email message, 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 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 --location --request PUT 'https://api.us.nylas.com/v3/grants/NYLAS_GRANT_ID/messages/MESSAGE_ID' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer <NYLAS_API_KEY_OR_ACCESS_TOKEN>' \
--data '{
"folders": [
"FOLDER_ID"
]
}'
{
"request_id": "1",
"data": {
"folders": [
"Label_10",
],
"bcc": null,
"body": "Learn how to Send Email with Nylas APIs",
"cc": null,
"attachments": [],
"from": [
{
"email": "[email protected]"
}
],
"reply_to": null,
"subject": "Hey Reaching Out with Nylas",
"to": [
{
"name": "DevRel",
"email": "[email protected]"
}
],
"use_draft": false,
"tracking_options": {
"label": "hey just testing",
"links": true,
"opens": true,
"thread_replies": true
},
"date": 1707839231,
"grant_id": "1",
"id": "1",
"thread_id": "2"
}
}

You can also use the v3 Nylas SDKs, as in the examples below.

import 'dotenv/config'
import Nylas from 'nylas'

const NylasConfig = {
apiKey: process.env.NYLAS_API_KEY,
apiUri: process.env.NYLAS_API_URI,
}

const nylas = new Nylas(NylasConfig)
const identifier = process.env.NYLAS_GRANT_ID
const folderId = process.env.FOLDER_ID
const messageId = process.env.MESSAGE_ID

const updateMessageFolder = async () => {
try {
const updatedMessage = await nylas.messages.update({
identifier,
messageId,
requestBody: {
folders: [folderId]
}
})

console.log('Message updated:', updatedMessage)
} catch (error) {
console.error('Error updating message folder:', error)
}
}

updateMessageFolder()
from dotenv import load_dotenv
load_dotenv()

import os
import sys
from nylas import Client

nylas = Client(
os.environ.get('NYLAS_API_KEY'),
os.environ.get('NYLAS_API_URI')
)

grant_id = os.environ.get("NYLAS_GRANT_ID")
folder_id = os.environ.get("FOLDER_ID")
message_id = os.environ.get("MESSAGE_ID")

message = nylas.messages.update(
grant_id,
message_id,
request_body={
"folders": [folder_id]
}
)

print(message)
require 'nylas'

nylas = Nylas::Client.new(api_key: 'API_KEY')
request_body = { folders: ['{folder_id}'] }
message, _ = nylas.messages.update(identifier: ENV["GRANT_ID"], message_id: "{message_id}", request_body: request_body)

puts message
import com.nylas.NylasClient;
import com.nylas.models.*;
import java.util.List;

public class UpdateMessage {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
List<String> folder = List.of("<LABEL_ID>");
UpdateMessageRequest request = new UpdateMessageRequest.Builder().folders(folder).build();
Response<Message> message = nylas.messages().update("<GRANT_ID>", "<MESSAGE_ID>", request);

System.out.println(message);
}
}
import com.nylas.NylasClient
import com.nylas.models.UpdateMessageRequest

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = dotenv["NYLAS_API_KEY"])
val folder = listOf("<LABEL_ID>")
val request: UpdateMessageRequest = UpdateMessageRequest(folders = folder)
val message = nylas.messages().update("<GRANT_ID>","<MESSAGE>", request)

print(message)
}