How to send emails with the Nylas Java SDK

How to send emails with the Nylas Java SDK

13 min read
Tags:

Being able to send an email that will land in the recipient’s inbox and not the spam folder, it’s critical for any application, and by using the Nylas APIs we can ensure that will happen. The emails will look the same as any other sent an email from the sender’s account, but we will have API-level control over the creation and sending of the message.

To make things even easier for Java developers, we offer the Nylas Java SDK. Today we’re going to review how to send emails and attachments with Java using the SDK.

BTW, you can check these other posts if you’re more into Ruby, Node or Python. And if you want to use raw APIs, we have you covered as well. Low code? Using Node-Red?, no problem either.

Installing Java

Chances are that we already have Java installed on our machines. We can check our version by doing the following:

$ java --version

Java 18.0.2 2002-07-19
Java(TM) SE Runtime Environment (build 18.0.2+9-61)
Java HotSpot(TM) 64-Bit Server VM (build 18.0.2+9-61, mixed mode, sharing)

If we don’t happen to have Java installed, we download it from here depending on our operating system.

Installing Maven

Our project is going to be compiled using Maven, so if we don’t have it installed on our system, we do so by using Homebrew.

$ brew install maven

Installing IntelliJ

While we can use any IDE of our choice, having one that is dedicated to Java is usually a better option. IntelliJ offers a nice community edition that will serve our needs.

Creating our Java project

Once IntelliJ is installed, we can proceed to create our project.

Create new Java project

Our new project is going to be called Nylas_Email_Send and it’s going to be built using Maven. The GroupId will be Nylas.

Setup Maven

When we hit create, we’re going to be presented with the pom.xml file first. We’re going to update this file to include what we need for this project.

Configure pom.xml

Here’s the content of the pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>Nylas</groupId>
   <artifactId>Nylas_Email_Send</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <maven.compiler.source>18</maven.compiler.source>
       <maven.compiler.target>18</maven.compiler.target>
   </properties>

</project>

And here it is how it should be:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>Nylas</groupId>
   <artifactId>Nylas_Email_Send</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <maven.compiler.source>17</maven.compiler.source>
       <maven.compiler.target>17</maven.compiler.target>
   </properties>

   <dependencies>
       <dependency>
           <groupId>com.nylas.sdk</groupId>
           <artifactId>nylas-java-sdk</artifactId>
           <version>1.15.0</version>
       </dependency>
       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-jdk14</artifactId>
           <version>1.7.25</version>
       </dependency>
       <dependency>
           <groupId>io.github.cdimascio</groupId>
           <artifactId>dotenv-java</artifactId>
           <version>2.2.4</version>
       </dependency>
   </dependencies>

   <build>
       <pluginManagement>
           <plugins>
               <plugin>
                   <!-- Build an executable JAR -->
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-jar-plugin</artifactId>
                   <version>3.1.0</version>
                   <configuration>
                       <archive>
                           <manifest>
                               <addClasspath>true</addClasspath>
                               <mainClass>Nylas.SendEmail</mainClass>
                           </manifest>
                       </archive>
                   </configuration>
               </plugin>
               <plugin>
                   <artifactId>maven-assembly-plugin</artifactId>
                   <configuration>
                       <archive>
                           <manifest>
                               <mainClass>Nylas.SendEmail</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                         <descriptorRef>jar-with-dependencies</descriptorRef>
                       </descriptorRefs>
                   </configuration>
               </plugin>
           </plugins>
       </pluginManagement>
   </build>

</project>

Looks like we added a lot of things, so let’s review them quickly.

<dependencies>
        <dependency>
            <groupId>com.nylas.sdk</groupId>
            <artifactId>nylas-java-sdk</artifactId>
            <version>1.15.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>io.github.cdimascio</groupId>
            <artifactId>dotenv-java</artifactId>
            <version>2.2.4</version>
        </dependency>
    </dependencies>

Here we are adding the dependencies for the Nylas Java SDK, for slf4j Logger and for DotEnv which will allow us to read .env files.

<build>
       <pluginManagement>
           <plugins>
               <plugin>
                   <!-- Build an executable JAR -->
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-jar-plugin</artifactId>
                   <version>3.1.0</version>
                   <configuration>
                       <archive>
                           <manifest>
                               <addClasspath>true</addClasspath>
                               <mainClass>SendEmail</mainClass>
                           </manifest>
                       </archive>
                   </configuration>
               </plugin>
               <plugin>
                   <artifactId>maven-assembly-plugin</artifactId>
                   <configuration>
                       <archive>
                           <manifest>
                               <mainClass>SendEmail</mainClass>
                           </manifest>
                       </archive>
                       <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                       </descriptorRefs>
                   </configuration>
               </plugin>
           </plugins>
       </pluginManagement>
   </build>

This adds maven-jar-plugin and maven-assembly-plugin which will help us to generate the JAR file and also to embed all the dependencies on the JAR file.

Now we can go ahead and create the class of our project, which will be called SendEmail.

Create new Java class
SendEmail class

Once the file is created, we can add the following code:

//Import Java Utilities
import java.lang.Exception;
import java.util.Arrays;
import java.io.IOException;

//Import Nylas Packages
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Draft;
import com.nylas.NameEmail;

//Import DotEnv to handle .env files
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;

public class SendEmail {
   public static void main(String[] args) throws RequestFailedException, 
                                                 IOException{
       Dotenv dotenv = Dotenv.load();
       // Create the client object
       NylasClient client = new NylasClient();
       // Connect it to Nylas using the Access Token from the .env file
       NylasAccount account = client.account(dotenv.get("ACCESS_TOKEN"));

       //Create a new draft
       Draft draft = new Draft();
       //Set the subject of the message
       draft.setSubject("With Love, from Nylas");
       draft.setBody("This email was sent using the Nylas Java Email API. 
                               Visit https://www.nylas.com for details.");
       draft.setTo(Arrays.asList(new NameEmail("Blag", 
                                               "[email protected]")));

       try {
           //Send the email draft
           account.drafts().send(draft);
           //Print a friendly message
           System.out.println( "The Email was sent successfully" );
       } catch (Exception e) {
           //Something went wrong, display the error
           System.out.print(e.getMessage());
       }
   }
}

In order for this to work, we need to create first an .env file and then a log4j file.

In our root folder, we need to create a new file and call it .env

Create new file

And then type the following:

ACCESS_TOKEN=YOUR_ACCESS_TOKEN

We need to replace YOUR_ACCESS_TOKEN with our Nylas Token

Storing our Nylas tokens

Let’s go to the Nylas Dashboard (creating a new account if necessary) and get our CLIENT_ID, CLIENT_SECRET, and ACCESS_TOKEN.

Nylas Dashboard settings

If we go to App Settings on the left-side menu, we will find a “Developer Details” section. The CLIENT_ID and CLIENT_SECRET, our Nylas account credentials, are there.

For the connected user account’s ACCESS_TOKEN, we can go to Accounts in the left-side menu, select our account, and then press “Generate New Token”. This will generate a new token for the connected account, allowing us to take actions on the user’s behalf via API.

Creating the Logger

The Nylas Java SDK uses a logger to log information regarding warning or error messages. If we don’t set this, we will receive a warning message every time we run our code.

Simply, go to the resources folder, and choose New and Resource Bundle.

Create new resource bundle

Name this new file log4j and press Ok.

Configure log4j

The file will be created properly.

log4j.properties file created

Now we should be ready to compile everything and generate our JAR file.

Send Emails with Java

At this point, we’re ready to send our email. We just need to select our SendEmail class and press Run ‘SendEmail.main()’.

Send an email using Java

The output should look like this indicating that our email was sent successfully.

Successfully sent email

Building our project

As we’re using Maven, we want Maven to build our project and we need to tell IntelliJ about this.

We need to go to IntelliJ IDEA → Preferences

Setup preferences

We need to go to Build, Execution, Deployment Build ToolsMavenRunner.

Choose Build, Execution, Deployment → Build Tools → Maven → Runner

And simply tick Delegate IDE build/run actions to Maven.

Delegate build to Maven

With that done, we can continue.

On the root folder, we need to press Control + Click or Right-Click depending on our operating system and choose Build Module.

Build the Nylas_Email_Send module

Everything should look good from the output window

Module successfully built

Now, in order to create the JAR file, we need to execute a Maven command, so we need to go to the upper right corner and select Run Anything.

Choose run anything to run the Maven command

We need to type the following on the Debug window:

mvn clean compile assembly:single
mvn clean compile assembly:single

This will create a new folder called Target that will contain our JAR file.

JAR file created

If we go to the terminal we can run our JAR file and send an email.

We need to type the following:

$ java -jar target/Nylas_Email_Send-1.0-SNAPSHOT-jar-with-dependencies.jar
Send emails with Java

We can verify that the email was sent by going to our inbox.

Check out inbox

You see how easy it is to send emails with Java and the Nylas Java SDK!

Building an email complaint form

We received a comment in one of our YouTube videos on creating a complaint form that will take the feedback and send it as an email. Of course, we needed to do something to address this comment. So here we go; we’ll learn how to send emails using Java via a web form.

Choosing a web framework

Choosing a web framework can be a daunting task, there are so many options and so many pros and cons, so let’s make things easy for everybody and choose a Micro Framework like Spark which is super friendly and Sinatra-like.

Creating our project

We already know how to create a project, so let’s move on to the interesting part, which will be adding our dependencies on the pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>friendly-letter</groupId>
   <artifactId>friendly-letter</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <maven.compiler.source>17</maven.compiler.source>
       <maven.compiler.target>17</maven.compiler.target>
   </properties>

   <dependencies>
       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-simple</artifactId>
           <version>1.7.25</version>
       </dependency>
       <dependency>
           <groupId>com.sparkjava</groupId>
           <artifactId>spark-core</artifactId>
           <version>2.9.4</version>
       </dependency>
       <dependency>
           <groupId>com.nylas.sdk</groupId>
           <artifactId>nylas-java-sdk</artifactId>
           <version>1.15.0</version>
       </dependency>
       <dependency>
           <groupId>io.github.cdimascio</groupId>
           <artifactId>dotenv-java</artifactId>
           <version>2.2.4</version>
       </dependency>
   </dependencies>

</project>

So far, it looks almost like the first section, although shorter, as we’re going to generate a JAR file at all, and we’re just adding what we need to be able to call Spark.

We’re going to create a class named Main and type the following:

//Import Java Utilities
import java.lang.Exception;
import java.util.Arrays;
import java.io.IOException;

//Import Nylas Packages
import com.nylas.NylasAccount;
import com.nylas.NylasClient;
import com.nylas.RequestFailedException;
import com.nylas.Draft;
import com.nylas.NameEmail;

//Import DotEnv to handle .env files
import io.github.cdimascio.dotenv.Dotenv;
import io.github.cdimascio.dotenv.DotenvException;

//Import to handle the SparkJava Web Framework
import static spark.Spark.*;

public class Main {

   static String SendEmail(String name, String email, String comments){
       Dotenv dotenv = Dotenv.load();
       // Create the client object
       NylasClient client = new NylasClient();
       // Connect it to Nylas using the Access Token from the .env file
       NylasAccount account = client.account(dotenv.get("ACCESS_TOKEN"));

       //Create a new draft
       Draft draft = new Draft();
       //Set the subject of the message
       draft.setSubject("Complaint from " + name + " - " + email);
       draft.setBody(comments);
       draft.setTo(Arrays.asList(new NameEmail("Blag", 
                                               "[email protected]")));

       try {
           //Send the email draft
           account.drafts().send(draft);
           //Print a friendly message
           return ("<!DOCTYPE html>" +
                   "<html><head>" +
                   "<meta http-equiv=\"refresh\" content=\"5; 
                          URL=/feedback\">" +
                   "<script src=\"https://cdn.tailwindcss.com\"></script>" +
                   "</head>" +
                   "<body>" +
                   "<div class=\"bg-neutral-200 border-neutral-600 border-b 
                         p-4 m-4 rounded\">" +
                   "<h2 class=\"font-semibold\">Thanks! We received your 
                        feedback.</h1>" +
                   "<br><p class=\"font-semibold\">You will be automatically 
                           redirected." +
                   "</div>" +
                   "</body>" +
                   "<html>");
       } catch (Exception e) {
           //Something went wrong, display the error
           return (e.getMessage());
       }
   }

   public static void main(String[] args) throws RequestFailedException, 
                                                 IOException{
       get("/feedback", (request, response) ->
               "<!DOCTYPE html>" +
                       "<html>" +
                       "<head>" +
                       "<title>Complaint Form</title>" +
                       "<script src=\"https://cdn.tailwindcss.com\">
                        </script>" +
                       "</head>" +
                       "<body>" +
                       "<div class=\"bg-neutral-200 border-neutral-600 
                             border-b p-4 m-4 rounded\">" +
                       "<h1 class=\"font-black\">If you're not happy 
                            with the provided service, " +
                       "please let us know</h1>" +
                       "<br>" +
                       "<form method=\"post\">" +
                       "<label for=\"name\" 
                               class=\"font-bold\">Name  </label>" +
                       "<input type=\"text\" name=\"name\" 
                               placeholder=\"Your name\"></input>" +
                       "<br><br>" +
                       "<label for=\"email\" 
                               class=\"font-bold\">Email  </label>" +
                       "<input type=\"text\" name=\"email\" 
                               placeholder=\"Your email\"></input>" +
                       "<br><br>" +
                       "<p class=\"font-bold\">Comments</p>" +
                       "<textarea name=\"comments\"\n" +
                       "        placeholder=\"Your comments\"\n" +
                       "        rows=5\n" +
                       "        cols=50></textarea>" +
                       "<br><br>" +
                       "<button type=\"submit\" class=\"bg-blue-500 
                                hover:bg-blue-700 " +
                       "text-white font-bold py-2 px-4 
                        rounded-full\">Submit</button>" +
                       "</form>" +
                       "</div>" +
                       "</body>" +
                       "</html>"
       );

       post("/feedback", (request, response) ->
               SendEmail(request.queryParams("name"), 
                         request.queryParams("email"), 
                         request.queryParams("comments"))
       );
   }
}

Basically, what we are doing is defining a method called get(“/feedback”, (request, response) which will be called when we call our web server using /feedback.

This will present us with a form where we need to fill in our name, email and comments. When we press submit, we will call the form post(“/feedback”, (request, response) which will call the SendEmail method providing all the information that we filled in the form.

SendEmail will then send the email. Nice and simple.

Remember to enable Maven before even trying to run this project:

Delegate build to Maven

Build the module and then simply go to the class Main and run it.

If we head to our web browser and type:

localhost:4567/feedback

We will be presented with the following form:

Form that will send the email using Java

And when we click on Submit.

Email was sent

Now, we can go into our mailbox and check that we received the email.

Check out inbox

If you want the full source code, you can go to our Github repo java-email-send-form.

And that’s it! As you can see, learning how to send emails with Java using the Nylas Java SDK becomes an easy task. If you want to learn more, visit our Documentation Page.

Don’t miss the action, watch our LiveStream Coding with Nylas:

Related resources

How to Send Emails Using an API

Key Takeaways This post will provide a complete walkthrough for integrating an email API focused…

How to build a CRM in 3 sprints with Nylas

What is a CRM? CRM stands for Customer Relationship Management, and it’s basically a way…

How to create an appointment scheduler in your React app

Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.