Version:
Only show these results:

Send email messages with Kotlin/Java

This page explains how to use the Nylas Kotlin/Java SDK and Email API to send email messages, reply to an email message, and attach files to a draft. For more information, see the Email documentation.

Before you begin

Before you start, you must have done the following tasks:

Create and send an email draft

This section walks through how to create and send an email draft with the Nylas Kotlin/Java SDK.

The following example creates a Draft object and assigns it a subject and some body text.

CreateDraftRequest requestBody = new CreateDraftRequest.Builder().
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. Visit https://nylas.com for details.")
val test = CreateDraftRequest.Builder().
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. Visit https://nylas.com for details.")

You can also add file attachments, message tracking features, and reply-to values. For more information about the data you can add to a draft, see the Drafts reference documentation.

Next, add a recipient to the draft.

to(Collections.singletonList(new EmailName("swag@example.com", "Nylas"))).build()   
to(listOf(EmailName("swag@example.com", "Nylas"))).build()   

You can also set the CC and BCC contacts using a similar construction.

Finally, it's time to send the draft!

nylas.drafts().send("<NYLAS_GRANT_ID>", drafts.getData().getId());   
val draft = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody).data   

Below are the full examples showing how to draft and send an email message.

import com.nylas.NylasClient;
import com.nylas.models.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

CreateDraftRequest requestBody = new CreateDraftRequest.Builder().
to(Collections.singletonList(new EmailName("swag@example.com",
"Nylas"))).
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. Visit https://nylas.com for details.").
build();

Response<Draft> drafts = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody);

System.out.println("Draft " + drafts.getData().getSubject() +
" was created with ID " + drafts.getData().getId());

nylas.drafts().send("<NYLAS_GRANT_ID>", drafts.getData().getId());
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import com.nylas.util.FileUtils

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")

val requestBody = CreateDraftRequest.Builder().
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. Visit https://nylas.com for details.").
to(listOf(EmailName("swag@example.com", "Nylas"))).
build()

val draft = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody).data
}

Reply to an email message

The first step to reply to an email message is to find the thread you want to reply to. The examples below get the most recent email message in an end user's inbox by returning only the first thread.

ListThreadsQueryParams queryParams = new ListThreadsQueryParams.Builder().
limit(1).
inFolder(Collections.singletonList("inbox")).
build();

ListResponse<Thread> thread = nylas.threads().list("<NYLAS_GRANT_ID>", queryParams);
assert thread.getData().get(0).getMessageIds() != null;

int len = thread.getData().get(0).getMessageIds().size() - 1;
String reply = thread.getData().get(0).getMessageIds().get(len);
val queryParams = ListThreadsQueryParams(limit = 1, 
inFolder = Collections.singletonList("inbox"))

val threads : List<Thread> = nylas.threads().list(dotenv["CALENDAR_ID"], queryParams).data
val len : Int? = threads[0].messageIds?.size
val reply = len?.minus(1)?.let { threads[0].messageIds?.get(it) }

Next, create a draft that has the same thread_id and subject as the thread you're replying to.

CreateDraftRequest request_body = new CreateDraftRequest.Builder().
replyToMessageId(reply).
subject(thread.getData().get(0).getSubject()).build();
val requestBody = CreateDraftRequest.Builder().
replyToMessageId(reply).
subject(threads[0].subject).
build()

Finally, assign the appropriate recipients and send the email message.

Response<Draft> draft = nylas.drafts().create("<NYLAS_GRANT_ID>", request_body);
Response<Message> msg = nylas.drafts().send("<NYLAS_GRANT_ID>", draft.getData().getId());
val draft = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody)

val msg = nylas.drafts().send(
dotenv["NYLAS_GRANT_ID"],
draft.data.id
)

Below are the full examples showing how to reply to an email message.

import com.nylas.NylasClient;
import com.nylas.models.*;
import com.nylas.models.Thread;
import java.util.Collections;

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

ListThreadsQueryParams queryParams = new ListThreadsQueryParams.Builder().
limit(1).
inFolder(Collections.singletonList("inbox")).
build();

ListResponse<Thread> thread = nylas.threads().list("<NYLAS_GRANT_ID>", queryParams);
assert thread.getData().get(0).getMessageIds() != null;

int len = thread.getData().get(0).getMessageIds().size() - 1;
String reply = thread.getData().get(0).getMessageIds().get(len);

CreateDraftRequest request_body = new CreateDraftRequest.Builder().
replyToMessageId(reply).
subject(thread.getData().get(0).getSubject()).
build();

Response<Draft> draft = nylas.drafts().create("<NYLAS_GRANT_ID>", request_body);
Response<Message> msg = nylas.drafts().send("<NYLAS_GRANT_ID>", draft.getData().getId());
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import java.util.*

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")

val queryParams = ListThreadsQueryParams(limit = 1,
inFolder = Collections.singletonList("inbox"))

val threads : List<Thread> = nylas.threads().list("<NYLAS_GRANT_ID>", queryParams).data
val len : Int? = threads[0].messageIds?.size
val reply = len?.minus(1)?.let { threads[0].messageIds?.get(it) }

val requestBody = CreateDraftRequest.Builder().
replyToMessageId(reply).
subject(threads[0].subject).
build()

val draft = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody)

val msg = nylas.drafts().send(
dotenv["NYLAS_GRANT_ID"],
draft.data.id
)
}

Attach a file to an email message

The Attachments endpoint allows you to create and modify files that you can attach to email messages. The following examples show how to take a file that's saved locally and upload it to Nylas for use with the Email API.

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

request.add(attachment);
val attachment: CreateAttachmentRequest = FileUtils.attachFileRequestBuilder("src/main/kotlin/myFile.png")   

Next, create a draft to attach the file to.

CreateDraftRequest requestBody = new CreateDraftRequest.Builder().
to(Collections.singletonList(new EmailName("swag@example.com", "Nylas"))).
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. Visit https://nylas.com for details.").
attachments(request).
build();
val requestBody = CreateDraftRequest.Builder().
replyToMessageId(reply).
subject(threads[0].subject).
attachments(listOf(attachment)).
build()

val draft = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody)

Finally, attach the file that you uploaded to the draft, and send the draft as an email message.

Response<Draft> drafts = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody);

nylas.drafts().send("<NYLAS_GRANT_ID>", drafts.getData().getId());
val draft = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody).data

nylas.drafts().send(dotenv["NYLAS_GRANT_ID"], draft.id)

Below are the full examples showing how to attach a file to an email message.

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

public class CreateDraft {
public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();
CreateAttachmentRequest attachment = FileUtils.attachFileRequestBuilder("src/main/java/myFile.pdf");
List<CreateAttachmentRequest> request = new ArrayList<>();

request.add(attachment);

CreateDraftRequest requestBody = new CreateDraftRequest.Builder().
to(Collections.singletonList(new EmailName("swag@example.com", "Nylas"))).
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. Visit https://nylas.com for details.").
attachments(request).
build();

Response<Draft> drafts = nylas.drafts().create(dotenv.get("NYLAS_GRANT_ID"), requestBody);

nylas.drafts().send(dotenv.get("NYLAS_GRANT_ID"), drafts.getData().getId());
}
}
import com.nylas.NylasClient
import com.nylas.models.*
import com.nylas.util.FileUtils

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
val attachment: CreateAttachmentRequest = FileUtils.attachFileRequestBuilder("src/main/kotlin/myFile.png")

val requestBody = CreateDraftRequest.Builder().
subject("With Love, from Nylas").
body("This email was sent using the Nylas Email API. Visit https://nylas.com for details.").
to(listOf(EmailName("swag@example.com", "Nylas"))).
build()

val draft = nylas.drafts().create("<NYLAS_GRANT_ID>", requestBody).data

nylas.drafts().send("<NYLAS_GRANT_ID>", draft.id);
}

Track email messages

The Nylas Email API allows you to track email messages, and Nylas generates webhook notifications when certain conditions are met. For more information, see the message tracking documentation.

The examples below enable message open, link clicked, and thread replied tracking for an email message, then send the message.

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

public class EmailTracking {
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("swag@example.com", "Nylas"));

TrackingOptions options = new TrackingOptions("Track this message",true, true, true);

SendMessageRequest requestBody = new SendMessageRequest.Builder(emailNames).
subject("With Love, from Nylas").
body("This email was sent using the <b>Kotlin/Java SDK</b> for the Nylas Email API. " +
"Visit the <a href='https://developer.nylas.com/docs/sdks/kotlin-java/'>Nylas documentation</a> for details.").
trackingOptions(options).
build();

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

System.out.println("Message " + email.getData().getSubject() + " was sent with ID " + email.getData().getId());
}
}
import com.nylas.NylasClient
import com.nylas.models.*

fun main(args: Array<String>) {
val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
val emailNames : List<EmailName> = listOf(EmailName("swag@example.com", "Nylas"))
val options : TrackingOptions = TrackingOptions("Track this message", true, true, true)

val requestBody : SendMessageRequest = SendMessageRequest.
Builder(emailNames).
subject("With Love, from Nylas").
body("This email was sent using the <b>Kotlin/Java SDK</b> for the Nylas Email API. " +
"See the <a href='https://developer.nylas.com/docs/sdks/kotlin-java/'>Nylas documentation</a> for details.").
trackingOptions(options).
build()

val email = nylas.messages().send("<NYLAS_GRANT_ID>", requestBody)

print("Message " + email.data.subject + " was sent with ID " + email.data.id)
}

Explore the Email API

If you've made it to this point, congratulations! You've learned how to send an email message with the Nylas Kotlin/Java SDK and Email API! 🎉

There's plenty more that you can do with Nylas. Take a look at the following resources to learn more: