Giter Club home page Giter Club logo

java-sparkpost's Introduction

Sign up for a SparkPost account and visit our Developer Hub for even more content.

SparkPost Java Library

Build Status Slack Status

Use this library in Java applications to easily access the SparkPost Email API in your application.

Version Compatibility Note

Version 0.6.2 -> 0.6.3

Due to issue 57 and to maintain compatibility with old and new version of Apache HTTP Client SPARKPOST_BASE_URL must not end with a / slash.

Version 0.12 -> 0.13

Although we try to maintain library backward compatibility this migration may require some minor changes to your code. Substitution data was changed from Map<String, String> to Map<String, Object>. Most client code will just need to change their map to this new signature.

Getting Started

The SparkPost Java Library is available in this Maven Repository or in GitHub Releases.

<dependency>
	<groupId>com.sparkpost</groupId>
	<artifactId>sparkpost-lib</artifactId>
	<version>0.27</version>
</dependency>

Building SparkPost4J

Basic Send Email Example

package com.sparkpost;

import com.sparkpost.exception.SparkPostException;

public class SparkPost {

    public static void main(String[] args) throws SparkPostException {
        String API_KEY = "YOUR API KEY HERE!!!";
        Client client = new Client(API_KEY);

        client.sendMessage(
                "[email protected]",
                "[email protected]",
                "The subject of the message",
                "The text part of the email",
                "<b>The HTML part of the email</b>");

    }
}

Basic Send Email through SparkPost EU

package com.sparkpost;

import com.sparkpost.exception.SparkPostException;
import com.sparkpost.transport.IRestConnection;

public class SparkPost {

    public static void main(String[] args) throws SparkPostException {
        String API_KEY = "YOUR API KEY HERE!!!";

        // To use the SparkPost EU use the IRestConnection.SPC_EU_ENDPOINT endpoint
        Client client = new Client(API_KEY, IRestConnection.SPC_EU_ENDPOINT);

        client.sendMessage(
                "[email protected]",
                "[email protected]",
                "The subject of the message",
                "The text part of the email",
                "<b>The HTML part of the email</b>");

    }
}

Advanced Send Email Example

With SparkPost you have complete control over all aspects of an email and a powerful templating solution.

private void sendEmail(String from, String[] recipients, String email) throws SparkPostException {
	TransmissionWithRecipientArray transmission = new TransmissionWithRecipientArray();

	// Populate Recipients
	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
    Map<String, Object> substitutionData = new HashMap<String, Object>();
    substitutionData.put("yourContent", "You can add substitution data too.");
    transmission.setSubstitutionData(substitutionData);

    // Populate Email Body
    TemplateContentAttributes contentAttributes = new TemplateContentAttributes();
    contentAttributes.setFrom(new AddressAttributes(from));
    contentAttributes.setSubject("Your subject content here. {{yourContent}}");
    contentAttributes.setText("Your Text content here.  {{yourContent}}");
    contentAttributes.setHtml("<p>Your <b>HTML</b> content here.  {{yourContent}}</p>");
    transmission.setContentAttributes(contentAttributes);

	// Send the Email
	RestConnection connection = new RestConnection(client, getEndPoint());
	Response response = ResourceTransmissions.create(connection, 0, transmission);

	logger.debug("Transmission Response: " + response);
}

Running The Sample Apps

The sample apps are held in apps/sparkpost-samples-app with each sample's source code in apps/sparkpost-samples-app/src/main/java/com/sparkpost/samples/.

To build the samples:

cd apps/sparkpost-samples-app
mvn compile

One the samples are built, create config.properties by copying apps/sparkpost-samples-app/config.properties.example and filling in your SparkPost API key and other test parameters.

You can now run your chosen sample through maven:

mvn exec:java -Dexec.mainClass=com.sparkpost.samples.SendEmailCCSample

java-sparkpost's People

Contributors

aleksandrbeljakov avatar aydrian avatar bdeanindy avatar dominicgunn avatar ewandennis avatar guirava avatar kalnik-a-a avatar richleland avatar svenwoltmann avatar yepher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-sparkpost's Issues

Json syntax error parsing "from" field from retrieved template

Using sparkpost-lib 0.16.1.

When using ResourceTemplates.retrieve to retrieve a template, the following JsonSyntaxException occurs when parsing the from field.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 242 path $.results.content.from
	com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
	com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
	com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
	com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
	com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
	com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
	com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
	com.google.gson.Gson.fromJson(Gson.java:810)
	com.google.gson.Gson.fromJson(Gson.java:775)
	com.google.gson.Gson.fromJson(Gson.java:724)
	com.sparkpost.model.responses.Response.decode(Response.java:47)
	com.sparkpost.resources.ResourceTemplates.retrieve(ResourceTemplates.java:38)

It seems like the java code expects a JSON object but the API returns a simple string.
Here is what the from field looks like when manually hitting the API at https://api.sparkpost.com/api/v1/templates/mytemplate with postman

"from": "My Company <[email protected]>",

Unit test should not hit SparkPost.com

Each time this project is built with mvn clean install and the unit tests runs and it clutters up the users SparkPost account. The unit tests should be unit tests and not integration tests.

There should be integration level samples that hit the live site and perform specific tasks.

Here is an example of the SparkPost account after just a few builds:

image

Fix broken build

Travis build is broken. It looks like Java 7 is no longer available on the build machine.

See here

Make HTTP connection more configurable

There are some use cases where users would like to not call HTTPUrlConnection.disconnect() after a request to the server.

Enable user of the SparkPost Library to be able to configure this behavior.

Include Sparkpost LICENSE

Need to include the LICENSE that has been approved by @SparkPost/legal team (we should be able to use the one from the NodeSDK.

Avoid having duplicate slashes

According to ESCSP-1390, java-sparkpost sometimes request to endpoint with duplicate slashes. While it used to work earlier and broken now which we're fixing it may not work in future (when we move to ALB routing).

/api/v1//transmissions

Add SparkPost Logo

Need to add the SparkPost logo (most recent and appropriate version) to the main README.md file

Add subaccount resource

Unless I am missing something there seems to be no support for managing subaccounts. Would be nice to add so we don't have to write seperate clients.

Wrong maven dependency

Hi,

In readme defined lib

com.sparkpost
client-server-protocol-lib
0.10

need to define

com.sparkpost sparkpost-lib 0.10

CI Integration

We need to include continuous integration testing using Travis CI.

  • Integrate with Travis CI
  • Add build status button on README.md file similar to the status on this page above the logo in the README.md

Add ability to GZIP post data

Currently, the Java SparkPost library sends/receives HTTP data uncompressed. It should provide a way to compress and decompress HTTP streams.

Switch to using SLF4J

Instead of directly depending on log4j, using the SLF4J logging facade will allow dependent applications of the Sparkpost library to pick/configure a logging library of their choice or at least not conflict with different versions of log4j.

The use case for me was that I'm using the logback logging library in my application, but the sparkpost library required me to configure both log4j and logback to have the same kind of logging formats, levels, and appenders.

I'll be submitting a PR in a few that contains the changes necessary for this.

Examples don't work 400 and 422 returned

Hi,

Neither the basic not the template example from the README.md works. I get a 400 error on the basic example and 422 on the template example. There is no detail provided as to why I get the errors. A simple curl sample works though. I have setup an API key.

I also added the template ID to the example for templates in the README.md but still get a 422

{
"recipients": [
{
"address": {
"email": "[email protected]"
}
}
],
"substitution_data": {
"from": "[email protected]"
},
"return_path": "[email protected]",
"content": {
"template_id": "my-first-email",
"email_rfc822": "testing an email here"
}
}

Add Message Event API

Add support for Message Events API

The Message Events API allows searching for recent events, and supports various types of result filtering. Available events include message status - injection, delivery, bounce - as well as recipient engagement - clicks and opens. Message Events is an on-demand (pull) interface to the same underlying event data that gets delivered in a near-real-time (push) fashion via Webhooks.

You can get all event types or only specific ones, such as bounces, deliveries, or clicks. You can filter by date range, campaign, or just about any other field. Event data is retained for 10 days and is generally available within 1 minute. Of course, aggregate reporting data is available via our metrics endpoint or the UI reports for much longer.

GET/api/v1/message-events{?bounce_classes,campaign_ids,delimiter,events,friendly_froms,from,message_ids,page,per_page,reason,recipients,subaccounts,template_ids,timezone,to,transmission_ids}

Changing Email for each recepint

Does substitutionData changes the data for all the recipients or is there a way to substitute the data according to each recipient.
For example, if I had a country field in my Email and I wanted to change it according to each recipient's country, something like this:

hello, Mr.X from country_filed

Could I write something like below to substitute that field according to each recipient:

 Map<String, Object> substitutionData = new HashMap<String, Object>();
        substitutionData.put("country_filed", recipient.country);
        transmission.setSubstitutionData(substitutionData);

is that possible to do it with one transmission or I have to create separate transmissions for each recipient and call transmission.setSubstitutionData for each one?

Exceptions should be easier to parse

For example, this gets thrown as SparkPostErrorServerResponseException:
SEVERE: Error reading server response: { "errors": [ { "message": "Message generation rejected", "description": "recipient address suppressed due to customer policy", "code": "1902" } ], "results": { "total_rejected_recipients": 0, "total_accepted_recipients": 1, "id": "84509310299791535" } }(Bad Request)
..which is not really developer friendly. Basically, when exceptions for responses like 4XX are thrown the whole response body is concat to the exception message. If I want to get the internal error code (1902) to store it somewhere I need to first remove the "Error reading server response" from message, then write a custom POJO to parse the remaining body into it.

It would be way nicer if we could grab the error response body directly from SparkPostException as an object, not needing to parse the text message ourself. Or at least get the clean response text.

Right now the library basically hides the response body from us and I don't see any good way to retreive it other than the way mentioned above.

Substitution data as string

Hi,

It looks like substitution data can only be strings key/value pairs but the value should be an array too.

Am I missing something to do so ?

Thanks

Webhook active property missing from model

Being able to detect whether a webhook is active as well as being able to perform a PUT and re-activating a webhook is not currently possible since the WebhookDescription/Webhook model does not have the active property on it.

Refactor to use packages

Packages are a more common convention than using class names to namespace, we should refactor the SDK to make it follow Java conventions

Some recommendations:

  • Change the top level package to com.sparkpost.sdk
  • Remove the SP prefix from class names since we already scoped within a sparkpost package
  • Create a dto package for DTO's. Remove DTO from class names.
  • Create a resource package for resources and SPEndpoint. Remove Resource from class names.
  • Create a common package for SPResponse and SPRestConn

Possible NPE

i got this today:

java.lang.Thread.run(Thread.java:745) Caused by: java.lang.NullPointerException at com.sparkpost.transport.RestConnection.receiveResponse(RestConnection.java:226) at com.sparkpost.transport.RestConnection.doHttpMethod(RestConnection.java:279) at com.sparkpost.transport.RestConnection.post(RestConnection.java:322) at com.sparkpost.resources.ResourceTransmissions.create(ResourceTransmissions.java:28) at

retry on 50x errors (i'm new to java and sparkpost client)

I tried to implement it in our code with logic like this, but it's not working. I'd totally appreciate any assistance/guidance in checking the response code properly:

catch (SparkPostErrorServerResponseException spex) {
...
else if (500 <= spex.getResponseCode() && spex.getResponseCode() < 510){
	Logger.log("Sparkpost " + spex.getResponseCode() + " errors, skipping for now: " + em.id);
...

Thanks!

Text field missing in TemplatePreviewData

Currently the text field is not mapped to TemplatePreviewData when previewing templates although it is present in the returned json from the server.

I created a PR for this issue: #81

Ability to set from name

At the moment I see no possibility to set the from name when sending an email. Only the from address can be set.

Sample that converts Mandrills Blacklist to SparkPost suppression list

As use migrate from Mandrill to SparkPost they will find it to their benefit to convert their Mandrill Blacklist to SparkPosts suppression list otherwise they will start seeing deliverability issues that they did not see at Mandrill.

TODO: add a sample that imports Mandrill's blacklist into SparkPost suppression list.

Remove `@deprecated` from RestConnection.get(EndPoint)

This should not have been deprecated when the string path methods were deprecated:

/*
     * (non-Javadoc)
     * @see com.sparkpost.transport.IRestConnection#get(com.sparkpost.resources.Endpoint)
     */
    @Override
    @Deprecated
    public Response get(Endpoint endpoint) throws SparkPostException {
        Response response = new Response();
        return doHttpMethod(endpoint, Method.GET, null, response);
    }

Android Gradle Release

Hi team,

I used Gradle please but that's giving me concurrent exception error while building also , depency is ignored 'org.apache:commons' httpclient

Please provide clear instruction on how to use sparkpost from android.

Thanks and Regards,

Resource stream handling is duplicated

In RestConnection.java there is some duplication of HTTP response stream. This should be refactored out into it's own method.

Here is one suggestion from @kalnik-a-a:

What about separate method for reading Response from InputStream?
Now it is duplicated in 3 places(2 in receiveSuccessResponse and 1 in receiveErrorResponse).

Something like this:

private Response readResponseFromInputStream(InputStream inputStream, StringBuilder sb, Response response) throws IOException {

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
        String line = "";
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        response.setResponseBody(sb.toString());
        logger.error("Server Response:\n" + sb.toString() + "\n");

        return response;
    }

Unable to send bulk mail getting undermine type boune

Hi there,
I have build sparkpost interface by using jsp and sevrlets,I can send test mail through it, but when I am trying to send bulk mail by connecting to my local mysql database then it send only first mail in the list and rest of the are appear as bounced back

While running still I am using log4j properties file in my webapp
I got one warning every time by log4j frame still I am using log4j properties file in my webapp

capture

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.