All Projects → mailjet → Mailjet Apiv3 Java

mailjet / Mailjet Apiv3 Java

Licence: mit
[API v3] Mailjet Java API Wrapper

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Mailjet Apiv3 Java

Mailjet Gem
[API v3] Mailjet official Ruby GEM
Stars: ✭ 119 (+124.53%)
Mutual labels:  wrapper, transactional-emails, email
Mailjet Apiv3 Nodejs
[API v3] Official Mailjet API v3 NodeJS wrapper
Stars: ✭ 137 (+158.49%)
Mutual labels:  wrapper, transactional-emails, email
Mailjet Apiv3 Php
[API v3] Mailjet PHP Wrapper
Stars: ✭ 194 (+266.04%)
Mutual labels:  wrapper, transactional-emails, email
Sendgrid Nodejs
The Official Twilio SendGrid Led, Community Driven Node.js API Library
Stars: ✭ 2,543 (+4698.11%)
Mutual labels:  transactional-emails, email
Sendgrid Php
The Official Twilio SendGrid Led, Community Driven PHP API Library
Stars: ✭ 1,257 (+2271.7%)
Mutual labels:  transactional-emails, email
Laravel Postmark
A Postmark adapter for Laravel
Stars: ✭ 143 (+169.81%)
Mutual labels:  transactional-emails, email
mailersend-laravel-driver
The official MailerSend Laravel Driver
Stars: ✭ 14 (-73.58%)
Mutual labels:  email, transactional-emails
laravel-mjml
Laravel MJML offers support for rendering MJML syntax into in-line HTML that can be sent within mails.
Stars: ✭ 26 (-50.94%)
Mutual labels:  wrapper, email
Grunt Email Workflow
A Grunt workflow for designing and testing responsive HTML email templates with SCSS.
Stars: ✭ 3,010 (+5579.25%)
Mutual labels:  transactional-emails, email
Sendgrid Java
The Official Twilio SendGrid Led, Community Driven Java API Library
Stars: ✭ 380 (+616.98%)
Mutual labels:  transactional-emails, email
Sendgrid Ruby
The Official Twilio SendGrid Led, Community Driven Ruby API Library
Stars: ✭ 520 (+881.13%)
Mutual labels:  transactional-emails, email
Sendgrid Python
The Official Twilio SendGrid Led, Community Driven Python API Library
Stars: ✭ 1,125 (+2022.64%)
Mutual labels:  transactional-emails, email
Sendgrid Csharp
The Official Twilio SendGrid Led, Community Driven C#, .NetStandard, .NetCore API Library
Stars: ✭ 835 (+1475.47%)
Mutual labels:  transactional-emails, email
Magento2 Gmail Smtp App
Configure Magento 2 to send email using Google App, Gmail, Amazon Simple Email Service (SES), Microsoft Office365 and many other SMTP (Simple Mail Transfer Protocol) servers
Stars: ✭ 281 (+430.19%)
Mutual labels:  transactional-emails, email
Sendgrid Go
The Official Twilio SendGrid Led, Community Driven Golang API Library
Stars: ✭ 710 (+1239.62%)
Mutual labels:  transactional-emails, email
Cuttlefish
Transactional email server with a lovely web interface
Stars: ✭ 985 (+1758.49%)
Mutual labels:  transactional-emails, email
Termux Mpv
Wrapper for Mpv on Termux. Displays play controls in the notification
Stars: ✭ 43 (-18.87%)
Mutual labels:  wrapper
Ost2pst
OST2PST - converts Outlook OST files to PST format
Stars: ✭ 46 (-13.21%)
Mutual labels:  email
2018 Fake Mail Sender
PHP Fake Mail Sender Script with nicEditor - Send fake mails to anyone.
Stars: ✭ 43 (-18.87%)
Mutual labels:  email
Node Prince
Node API for executing PrinceXML via prince(1) CLI
Stars: ✭ 42 (-20.75%)
Mutual labels:  wrapper

alt text

Official Mailjet Java Wrapper

Build Status

Overview

This repo features the official Java wrapper for the Mailjet API.

Check out all the resources and all the Java code examples in the Official Documentation.

Table of contents

Release notes

v5.1.1

  • fixes adding additional quotes during serialization of string variables adn headers in TransactionalEmailBuilder

v5.1.0

  • downgraded OkHttpClient to v3.12 to be compatible with the current version in Spring Boot
  • adds transactional email builder to make possible sending messages easier

v5.0.0

  • migrated to more reliable OkHttpClient
  • removed ApiVersion from the MailjetClient configuration: Now the client will determine the needed API version from the resource itself.
  • added ClientOptions builder to make configuration more explicit. If you have troubles with migration, please, check tests for more examples.

Compatibility

This library requires Java version 1.8 or higher.

Installation (Maven)

Add the following in your pom.xml

    <dependencies>
        <dependency>
            <groupId>com.mailjet</groupId>
            <artifactId>mailjet-client</artifactId>
            <version>5.1.1</version>
        </dependency>
    </dependencies>

Authentication

The Mailjet Email API uses your API and Secret keys for authentication. Grab and save your Mailjet API credentials.

export MJ_APIKEY_PUBLIC='your API key'
export MJ_APIKEY_PRIVATE='your API secret'

Note: The SMS API authorization is based on a Bearer token. See information about it in the SMS API section of the readme.

Initialize your Mailjet Client:

        ClientOptions options = ClientOptions.builder()
                .apiKey(System.getenv("MJ_APIKEY_PUBLIC"))
                .apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE"))
                .build();

        MailjetClient client = new MailjetClient(options);

Make your first call

Here's an example on how to send a transactional email:

        TransactionalEmail message1 = TransactionalEmail
                .builder()
                .to(new SendContact(senderEmail, "stanislav"))
                .from(new SendContact(senderEmail, "Mailjet integration test"))
                .htmlPart("<h1>This is the HTML content of the mail</h1>")
                .subject("This is the subject")
                .trackOpens(TrackOpens.ENABLED)
                .attachment(Attachment.fromFile(attachmentPath))
                .header("test-header-key", "test-value")
                .customID("custom-id-value")
                .build();

        SendEmailsRequest request = SendEmailsRequest
                .builder()
                .message(message1) // you can add up to 50 messages per request
                .build();

        // act
        SendEmailsResponse response = request.sendWith(client);

Or using an old JSONObject syntax:

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.ClientOptions;
import com.mailjet.client.resource.Emailv31;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Run:
     */
    public static void main(String[] args) throws MailjetException {
      MailjetRequest request;
      MailjetResponse response;

      ClientOptions options = ClientOptions.builder()
            .apiKey(System.getenv("MJ_APIKEY_PUBLIC"))
            .apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE"))
            .build();
      
      MailjetClient client = new MailjetClient(options);

      request = new MailjetRequest(Emailv31.resource)
            .property(Emailv31.MESSAGES, new JSONArray()
                .put(new JSONObject()
                    .put(Emailv31.Message.FROM, new JSONObject()
                        .put("Email", "$SENDER_EMAIL")
                        .put("Name", "Me"))
                    .put(Emailv31.Message.TO, new JSONArray()
                        .put(new JSONObject()
                            .put("Email", "$RECIPIENT_EMAIL")
                            .put("Name", "You")))
                    .put(Emailv31.Message.SUBJECT, "My first Mailjet Email!")
                    .put(Emailv31.Message.TEXTPART, "Greetings from Mailjet!")
                    .put(Emailv31.Message.HTMLPART, "<h3>Dear passenger 1, welcome to <a href=\"https://www.mailjet.com/\">Mailjet</a>!</h3><br />May the delivery force be with you!")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

Client / Call configuration specifics

To instantiate the library you can use the following constructor:

        ClientOptions options = ClientOptions.builder()
                .apiKey(System.getenv("MJ_APIKEY_PUBLIC"))
                .apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE"))
                .build();

        MailjetClient client = new MailjetClient(options);

Options

Set connection timeouts and log requests

You can pass a custom configured HttpClient to the Mailjet client to get request logs or custom timeouts:

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(Level.BASIC);
    	OkHttpClient customHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .build();

        ClientOptions options = ClientOptions.builder()
                .apiKey(System.getenv("MJ_APIKEY_PUBLIC"))
                .apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE"))
                .okHttpClient(customHttpClient)
                .build();

for more configuration options, please, refer to the OkHttpClient documentation

API Versioning

The Mailjet API is spread among three distinct versions:

  • v3 - The Email API
  • v3.1 - Email Send API v3.1, which is the latest version of our Send API
  • v4 - SMS API

You can skip version specification during the request, as MailJet client will determine the needed API version by himself.

For additional information refer to our API Reference.

Base URL

The default base domain name for the Mailjet API is api.mailjet.com. You can modify this base URL by adding a different URL in ClientOptions:

        ClientOptions options = ClientOptions.builder()
                .baseUrl("https://api.us.mailjet.com")
                .apiKey(System.getenv("MJ_APIKEY_PUBLIC"))
                .apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE"))
                .build();

        MailjetClient client = new MailjetClient(options);

If your account has been moved to Mailjet's US architecture, the URL you need to add is https://api.us.mailjet.com.

Use HTTP proxy

The proxy can be set using the following system properties:

HTTP proxy
-Dhttp.proxyHost=
-Dhttp.proxyPort=

HTTPS proxy
-Dhttps.proxyHost=
-Dhttps.proxyPort=

If you communicate with other endpoints using java.net.HttpURLConnection and you don't need proxy for them:

-Dhttp.nonProxyHosts=<any host you don't want to be proxied>

List of resources

You can find the list of all available resources for this library, as well as their configuration, in src/main/java/com/mailjet/client/resource.

Request examples

POST Request

Use the Post method of the Mailjet CLient (i.e. response = client.post(request);). request will be a MailjetRequest object.

Simple POST request

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Contact;

public class MyClass {
    /**
     * Create a contact
     */
    public static void main(String[] args) throws MailjetException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(ClientOptions.builder().apiKey(System.getenv("MJ_APIKEY_PUBLIC")).apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE")).build());
      request = new MailjetRequest(Contact.resource)
            .property(Contact.EMAIL, "[email protected]");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

Using actions

To access endpoints with action, you will be able to find Resources object definition. For example, the /Contact/$ID/Managecontactslists endpoint can be used with the object ContactManagecontactslists available in com.mailjet.client.resource

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.ContactManagecontactslists;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : Manage a contact subscription to a list
     */
    public static void main(String[] args) throws MailjetException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(ClientOptions.builder().apiKey(System.getenv("MJ_APIKEY_PUBLIC")).apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE")).build());
      request = new MailjetRequest(ContactManagecontactslists.resource, ID)
            .property(ContactManagecontactslists.CONTACTSLISTS, new JSONArray()
                .put(new JSONObject()
                    .put("ListID", "$ListID_1")
                    .put("Action", "addnoforce"))
                .put(new JSONObject()
                    .put("ListID", "$ListID_2")
                    .put("Action", "addforce")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

GET Request

Use the get method of the Mailjet CLient (i.e. response = client.get(request);). request will be a MailjetRequest object.

Retrieve all objects

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Contact;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Run :
     */
    public static void main(String[] args) throws MailjetException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(ClientOptions.builder().apiKey(System.getenv("MJ_APIKEY_PUBLIC")).apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE")).build());

      request = new MailjetRequest(Contact.resource);
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

Use filtering and sorting

You can add filter to your API call on the MailjetRequest by using the filter method. Sorting is also possible, with specification the field name and order (ASC or DESC) separated by space. Note: Both the Sort query parameter, and the option to select a descending order are not available for every property. Example:

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Message;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Run :
     */
    public static void main(String[] args) throws MailjetException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(ClientOptions.builder().apiKey(System.getenv("MJ_APIKEY_PUBLIC")).apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE")).build());

      request = new MailjetRequest(Contact.resource)
            .filter(Contact.ISEXCLUDEDFROMCAMPAIGNS, "false")
            .filter("Sort", "CreatedAt DESC");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

Retrieve a single object

When instantiating the MailjetRequest, you can specify the Id of the resource you want to access. (example: request = new MailjetRequest(Contact.resource, ID);).

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Contact;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Run :
     */
    public static void main(String[] args) throws MailjetException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(ClientOptions.builder().apiKey(System.getenv("MJ_APIKEY_PUBLIC")).apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE")).build());

      request = new MailjetRequest(Contact.resource, ID);
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

PUT Request

A PUT request in the Mailjet API will work as a PATCH request - the update will affect only the specified properties. The other properties of an existing resource will neither be modified, nor deleted. It also means that all non-mandatory properties can be omitted from your payload.

Use the put method of the Mailjet CLient (i.e. response = client.put(request);). request will be a MailjetRequest object.

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Contactdata;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Modify : Modify the static custom contact data
     */
    public static void main(String[] args) throws MailjetException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(ClientOptions.builder().apiKey(System.getenv("MJ_APIKEY_PUBLIC")).apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE")).build());

      request = new MailjetRequest(Contactdata.resource, ID)
            .property(Contactdata.DATA, new JSONArray()
                .put(new JSONObject()
                    .put("Name", "Age")
                    .put("value", "30"))
                .put(new JSONObject()
                    .put("Name", "Country")
                    .put("value", "US")));
      response = client.put(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

DELETE Request

Upon a successful DELETE request the response will not include a response body, but only a 204 No Content response code.

Here's an example of a DELETE request:

package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.resource.Template;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Delete a Template
     */
    public static void main(String[] args) throws MailjetException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(ClientOptions.builder().apiKey(System.getenv("MJ_APIKEY_PUBLIC")).apiSecretKey(System.getenv("MJ_APIKEY_PRIVATE")).build());

      request = new MailjetRequest(Template.resource, ID);
      response = client.delete(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

SMS API

Token Authentication

Authentication for the SMS API endpoints is done using a bearer token. The bearer token generated in the SMS section of your Mailjet account.

Example request

An example SMS API request:

MailjetClient client;
MailjetRequest request;
MailjetResponse response;

MailjetClient mailjetClient = new MailjetClient(ClientOptions
                .builder()
                .bearerAccessToken(System.getenv("MJ_APITOKEN"))
                .build());

String germanyPhoneNumber = "+4915207831169";

MailjetRequest mailjetRequest = new MailjetRequest(SmsSend.resource)
                .property(SmsSend.FROM, "MJPilot")
                .property(SmsSend.TO, germanyPhoneNumber)
                .property(SmsSend.TEXT, "Have a nice SMS flight with Mailjet!");

// send the request
MailjetResponse response = mailjetClient.post(mailjetRequest);

// assert response
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("Message is being sent", response.getData().getJSONObject(0).getJSONObject("Status").getString("Description"));

Also, you can check integration tests how to work with Mailjet client.

Contribute

Mailjet loves developers. You can be part of this project!

This wrapper is a great introduction to the open source world, check out the code!

Feel free to ask anything, and contribute:

  • Fork the project.
  • Create a new branch.
  • Implement your feature or bug fix.
  • Add documentation for it.
  • Add specs for your feature or bug fix.
  • Commit and push your changes.
  • Submit a pull request.

If you have suggestions on how to improve the guides, please submit an issue in our Official API Documentation repo.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].