Getting Started with SparkPost in Java
Tags: sdk, api, java, beginners
Published: 2017-09-21 18:01:04

---
title: "Getting Started with SparkPost in Java"
published: true
tags: sdk,api,java,beginners
canonical_url: https://www.sparkpost.com/blog/sparkpost-in-java/
---

The [SparkPost Java library](https://github.com/SparkPost/java-sparkpost) is a popular way to integrate with SparkPost. If this describes your current task, this article will help you send email in a matter of a few minutes. If you’re a visual learner, check out this [Getting Started video](https://www.youtube.com/watch?v=KyBXABMe4mo) we have for the SparkPost Java Client Library.

I assume you have already [created a SparkPost account](https://pages.sparkpost.com/bl-account-signup-generic.html?src=Blog&pc=bl-rfi-generic-2017&utm_source=blog&utm_medium=blog&utm_campaign=all&utm_content=signup) and an [API key](https://www.sparkpost.com/docs/getting-started/create-api-keys/).

### Setting up a new project

As a Java developer I am sure you are more than familiar with how to add dependencies to your project. I will demonstrate doing so with Maven (mvn) in the code snippet below. If you are not using Maven, you’ll need to create the project and add the SparkPost library to it your normal way.

Let’s create the project.

```java
> mvn archetype:generate -DgroupId=com.example -DartifactId=SparkPostDemo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO] 
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO] 
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: /private/tmp
[INFO] Parameter: package, Value: com.example
[INFO] Parameter: groupId, Value: com.example
[INFO] Parameter: artifactId, Value: SparkPostDemo
[INFO] Parameter: packageName, Value: com.example
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: /private/tmp/SparkPostDemo
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.888 s
[INFO] Finished at: 2017-08-11T10:52:54-05:00
[INFO] Final Memory: 18M/317M
[INFO] ------------------------------------------------------------------------
```

Using the code above, we just created the following project structure:.

```java
> cd SparkPostDemo
> find .
.
./pom.xml
./src
./src/main
./src/main/java
./src/main/java/com
./src/main/java/com/example
./src/main/java/com/example/App.java
./src/test
./src/test/java
./src/test/java/com
./src/test/java/com/example
./src/test/java/com/example/AppTest.java
```

Now let’s build the base project:

```java
> mvn clean install

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building SparkPostDemo 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
                 :
   [Snipped out lots of output]
                 :
 -------------------------------------------------------
 T E S T S
 -------------------------------------------------------
Running com.example.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ SparkPostDemo ---
[INFO] Building jar: /private/tmp/SparkPostDemo/target/SparkPostDemo-1.0-SNAPSHOT.jar
[INFO] 
[INFO] --- maven-install-plugin:2.4:install (default-install) @ SparkPostDemo 
---
[INFO] Installing 
/private/tmp/SparkPostDemo/target/SparkPostDemo-1.0-SNAPSHOT.jar to 
/Users/user/.m2/repository/com/example/SparkPostDemo/1.0-SNAPSHOT/SparkPostDem
o-1.0-SNAPSHOT.jar
[INFO] Installing /private/tmp/SparkPostDemo/pom.xml to 
/Users/user/.m2/repository/com/example/SparkPostDemo/1.0-SNAPSHOT/SparkPostDem
o-1.0-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.128 s
[INFO] Finished at: 2017-08-11T10:55:57-05:00
[INFO] Final Memory: 19M/286M
[INFO] ------------------------------------------------------------------------
```

### Adding SparkPost Library Dependency

Now let’s edit the Maven Project Object Model `(pom.xml)` and add the SparkPost library dependency. You can find the code snippet with the latest version [here](https://github.com/SparkPost/java-sparkpost#getting-started). Add that to the `“dependencies”` element of the `“pom.xml”` file. Here is an example with the latest version as of the writing of this post:

```java
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>SparkPostDemo</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SparkPostDemo</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- SparkPost Dependency -->
    <dependency>
        <groupId>com.sparkpost</groupId>
        <artifactId>sparkpost-lib</artifactId>
        <version>0.19</version>
    </dependency>
    
  </dependencies>
</project>
```

Once the dependency is added, build the project again like this:

```java
mvn clean install
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building SparkPostDemo 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
                 :
   [Snipped out some output]
                 :
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ SparkPostDemo ---
[INFO] Building jar: /private/tmp/SparkPostDemo/target/SparkPostDemo-1.0-SNAPSHOT.jar
[INFO] 
[INFO] --- maven-install-plugin:2.4:install (default-install) @ SparkPostDemo ---
[INFO] Installing /private/tmp/SparkPostDemo/target/SparkPostDemo-1.0-SNAPSHOT.jar to /Users/user/.m2/repository/com/example/SparkPostDemo/1.0-SNAPSHOT/SparkPostDemo-1.0-SNAPSHOT.jar
[INFO] Installing /private/tmp/SparkPostDemo/pom.xml to /Users/user/.m2/repository/com/example/SparkPostDemo/1.0-SNAPSHOT/SparkPostDemo-1.0-SNAPSHOT.pom
[INFO] --------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] --------------------------------------------------------------------
[INFO] Total time: 2.793 s
[INFO] Finished
[INFO] Final Memory:
[INFO] --------------------------------------------------------------------
```

And with that, we’re ready to try it out!

### Sending Your First Email

The easiest way to send an email is by using the `SendMessage` call. Here is an example:

```java
package com.example;

import com.sparkpost.Client;
import com.sparkpost.exception.SparkPostException;

/**
 * My First Email Example
 *
 */
public class App 
{
    public static void main(String[] args) throws SparkPostException {
        String API_KEY = "YOUR API KEY HERE";
        Client client = new Client(API_KEY);

        client.sendMessage(
                "from@example.com",
                "to@example.com",
                "The subject of the message",
                "The text part of the email",
                "<b>The HTML part of the email</b>");

    }
}
```

To make this work for your own SparkPost account, you’ll want to make the following changes:

1. In the above sample code, replace `YOUR API KEY HERE` with your SparkPost [API key](https://app.sparkpost.com/account/credentials).
2. Change `from@example.com` to an email address for your [verified domain](https://app.sparkpost.com/account/sending-domains).
3. Change `to@example.com` to the address to which you want to send the email.
4. Compile and run your code, and you will see the email arrive in the inbox.

### More Advanced Examples

The `sendMessage(...)` function is helpful for getting up and running very quickly. However, you may need to do more advanced operations in the future. Here is an example to help you leverage the full power of the SparkPost API.

```java
package com.example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sparkpost.Client;
import com.sparkpost.exception.SparkPostException;
import com.sparkpost.model.AddressAttributes;
import com.sparkpost.model.RecipientAttributes;
import com.sparkpost.model.TemplateContentAttributes;
import com.sparkpost.model.TransmissionWithRecipientArray;
import com.sparkpost.model.responses.TransmissionCreateResponse;
import com.sparkpost.resources.ResourceTransmissions;
import com.sparkpost.transport.IRestConnection;
import com.sparkpost.transport.RestConnection;

public class TemplateExample {
    private Client client;

    public static final void main(String[] args) throws SparkPostException {
        TemplateExample example = new TemplateExample();
        example.sendEmail();
    }

    public void sendEmail() throws SparkPostException {

        // Setup a SparkPost client
        client = new Client("YOUR API KEY HERE");
        client.setFromEmail("from@example.com");

        // Create our Transmission object that will be used to send the transmission
        TransmissionWithRecipientArray transmission = new TransmissionWithRecipientArray();

        // Populate Recipients
        String[] recipients = new String[] {
                "to1@example.com",
                "to2@example.com"
        };

        List<RecipientAttributes> recipientArray = new ArrayList<RecipientAttributes>();
        for (String recipient : recipients) {
            RecipientAttributes recipientAttribs = new RecipientAttributes();
            recipientAttribs.setAddress(new AddressAttributes(recipient));
            recipientArray.add(recipientAttribs);
        }
        transmission.setRecipientArray(recipientArray);

        // Populate Substitution Data. This will replace content in the template with the value defined here.
        Map<String, Object> substitutionData = new HashMap<String, Object>();
        substitutionData.put("extraSubjectContent", "More Subject Content");
        substitutionData.put("extraBodyContent", "You can add substitution data too.");
        transmission.setSubstitutionData(substitutionData);
                
        // Populate Email Body
        TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
        contentAttributes.setFrom(new AddressAttributes(client.getFromEmail()));
        contentAttributes.setSubject("Your subject content here. {{extraSubjectContent}}");
        contentAttributes.setText("Your Text content here. {{extraBodyContent}}");
        contentAttributes.setHtml("<p>Your <b>HTML</b> content here. {{extraBodyContent}}</p>");
        transmission.setContentAttributes(contentAttributes);

        transmission.setContentAttributes(contentAttributes);

        IRestConnection connection = new RestConnection(this.client);
        TransmissionCreateResponse transmissionResponse = ResourceTransmissions.create(connection, 0, transmission);
        
        System.out.println(transmissionResponse);
    }
}
```

To make this work for your SparkPost account, you’ll want to make the same sort of changes as before:

1. In that sample code, replace `YOUR API KEY HERE` with your SparkPost [API key](https://app.sparkpost.com/account/credentials).
2. Change `from@example.com` to an email address for your [verified domain](https://app.sparkpost.com/account/sending-domains).
3. Change `to1@example.com` and `to2@example.com` to the address to which you want to send the email.
4. Compile and run your code, and you will see the email arrive in the inbox.

You can find many more examples of leveraging the SparkPost API [here](https://github.com/SparkPost/java-sparkpost/tree/master/apps/sparkpost-samples-app/src/main/java/com/sparkpost/samples).

### Conclusion

We’ve tried to make using SparkPost with Java as simple and enjoyable as writing any other Java code. If you run into any issues or have any questions, feel free to submit an issue on the Github [repo](https://github.com/SparkPost/java-sparkpost) or join us on our community Slack team in the #java channel. I’d love to hear from you.  

_This post was originally published on [sparkpost.com](https://www.sparkpost.com/blog/sparkpost-in-java/)_