# Send messages with Kotlin/Java

Source: https://developer.nylas.com/docs/v3/sdks/kotlin-java/send-email/

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

## Before you begin

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

- [Installed and set up the Nylas Kotlin/Java SDK](/docs/v3/sdks/kotlin-java/).
- [Authenticated one or more users](/docs/v3/sdks/kotlin-java/#authenticate-users).

## 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.

```java
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.")
```

```kt
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 references](/docs/reference/api/drafts/).

Next, add a recipient to the draft.

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

```kt
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!

```java
nylas.drafts().send("<NYLAS_GRANT_ID>", drafts.getData().getId());
```

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

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

```java
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());
  }
}
```

```kt
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 a message

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

```java
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);
```

```kt
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.

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

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

Finally, assign the appropriate recipients and send the message.

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

```kt
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 a message.

```java
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());
  }
}
```

```kt
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 a message

The [Attachments endpoint](/docs/reference/api/attachments/) allows you to create and modify files that you can attach to 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.

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

request.add(attachment);
```

```kt
val attachment: CreateAttachmentRequest = FileUtils.attachFileRequestBuilder("src/main/kotlin/myFile.png")
```

Next, create a draft to attach the file to.

```java
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();
```

```kt
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 a message.

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

nylas.drafts().send("<NYLAS_GRANT_ID>", drafts.getData().getId());
```

```kt
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 a message.

```java
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());
  }
}
```

```kt
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 messages

The Nylas Email API allows you to track messages, and Nylas generates webhook notifications when certain conditions are met. For more information, see the [message tracking documentation](/docs/v3/email/message-tracking/).

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

```java
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/v3/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());
  }
}
```

```kt
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/v3/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)
}
```