NAV
cURL PHP NODE RUBY PYTHON GO JAVA

Getting Started

This is a quick tutorial to get you started using our API.

We will show you how to send your first email, how to authenticate with our API and tell you more about Mailjet RESTful API.

We will also show you how to verify your domain to get a better deliverability of your emails.

Make your first request

Give it a go and send your first email…

This simple example shows how to send an email with the API in a few easy steps.

First, you need to have at least one active sender address in the Mailjet system. Visit the Sender domains & addresses section to check and setup your domain and sender.

Second, you need to find your credentials, the API Key and the API Private Key, in the account/API Keys section.

Example available only with CURL

curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H "Content-Type: application/json" \
    -d '{
        "FromEmail":"$SENDER_EMAIL",
        "FromName":"Me",
        "Recipients": [ 
            {
            "Email":"$RECIPIENT_EMAIL"
            }
        ],
        "Subject":"My first Mailjet Email!",
        "Text-part":"Greetings from Mailjet."
    }'

Now run the Curl command line, after replacing:

About the Mailjet RESTful API

API in a Nutshell

The Mailjet API is designed to be RESTful compliant. This means that the API communicate over HTTP (including the use of HTTP verbs) . The API allows you to create, read, update and delete (CRUD) resources. Also, each single resource has a URI (Unique Resource Identifier) to help access its properties.

The CRUD methods on the Mailjet API correspond to HTTP’s verbs POST, GET, PUT and DELETE, so that depending on the resources and providing you have the access rights, you can do the following :

Each resource has a list of properties and methods you can see in our API reference.

Authenticate

In order to use the Mailjet API you have to authenticate using HTTP Basic Auth. HTTP Basic Auth requires you to provide a username and a password for each API request. The username is your API Key and the password is your API Secret Key, which are both generated for you after registration.

#To make better use of our cURL examples you can set your keys in your environment variables with the following commands: 
export MJ_APIKEY_PUBLIC=xxxxxxxxxxxxxxxxxxxxxx
export MJ_APIKEY_PRIVATE=xxxxxxxxxxxxxxxxxxxxxxx

#View user information : now, you don't need to replace $MJ_APIKEY_PUBLIC and $MJ_APIKEY_PRIVATE when running a cURL command
curl --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" https://api.mailjet.com/v3/REST/user

The server should respond with the following data:

{
    "Count": 1,
    "Data": [
        {
            "ACL": "",
            "CreatedAt": "",
            "Email": "miss@mailjet.com",
            "ID": "",
            "LastIp": "",
            "LastLoginAt": "",
            "Locale": "",
            "MaxAllowedAPIKeys": "5",
            "Timezone": "",
            "Username": "",
            "WarnedRatelimitAt": ""
        }
    ],
    "Total": 1
}

Most developers use one of our API libraries for their production systems and the respective library documentation tells you where to place your API Keys. However for testing purposes it can be nice to query the API directly from the shell.

In this example :

Both these keys can be found in your control panel, once you’re logged-in and your account is provisioned (activated).

The usual json payload response will have the following structure : {"Count": int, "Data": array, "Total": int} where Count and Total represent the number of lines affected by your API call. When using the countOnly filter Total will be the global number of elements corresponding to your API call.

Status Codes

These status codes will be sent back by the API to notify of the success or failure of your calls.

Code Description
200 OK All went well. Congrats!
201 Created The POST request was successfully executed.
204 No Content No content found or expected to return. Returned when DELETE was successful.
304 Not Modified The PUT request didn’t affect any record.
400 Bad Request One or more parameters are missing or maybe mispelled (unknown resource or action)
401 Unauthorized You have specified an incorrect Api Key / API Secret Key. You may be unauthorized to access the API or your API key may be expired. Visit API keys Management section to check your keys.
403 Forbidden You are not authorised to access this resource.
404 Not Found The resource with the specified ID you are trying to reach does not exist.
405 Method Not Allowed The method requested on the resource does not exist.
429 Too Many Requests Oops! You have reach the maximum number of calls allowed per minute by our API. Please review your integration to reduce the number of call issued by your system.
500 Internal Server Error Ouch! Something went wrong on our side and we apologize! When such error occurs, it will contain an error identifier in it’s description (e.g. “ErrorIdentifier” : “D4DF574C-0C5F-45C7-BA52-7AA8E533C3DE”), which is crucial for us to track the problem and identify the root cause. Please contact our support team , providing the error identifier and we will do our best to help.
{
    "ErrorInfo": "Bad Request",
    "ErrorMessage": "Unknown resource: \"contacts\"",
    "StatusCode": 400
}

In addition to the status codes, in case of error, you can find hints in a standardised JSON response with the reason under ErrorMessage.

In case of a 429 Too Many Requests error, keep in mind that Mailjet API offers multiple bulk functionalities to replace and ease some heavy duty API needs :

Verify Your Domain

We strongly recommend that you verify the domain or subdomain you will use for sending emails. To do so you have to go to your account settings and add the domain you want to use for sending emails. Once the domain is successfully set up we generate an SPF and a DKIM record for you.

SPF is a DNS TXT record and acts as a filter. It is used to specify a whitelist of IP addresses. This whitelist can be queried by mail clients to see whether a sender IP is in the list.

DKIM is another DNS TXT record and contains a public key. We automatically generate a public/private key pair for you after registration. The private key is used to sign every message you send. Email clients can then check your DKIM record and use it to verify the signature. Together, SPF and DKIM form the technical basis of email deliverability.

Tip: You can find both records together with instructions in your account settings. Go to your account setup page and click on the info button for your domain.

Once your domain is verified you should add the SPF and DKIM records to your domain using the domain configuration tool of your DNS Provider.

You can refer to our step-by-step user guides on creating DNS records:

You can also visit the offical and third-party documentations for DNS providers :

With some DNS providers the setup can be quite tedious, but we would be happy to help you out. Just contact our support!

Where to go from here?

In the next sections of this guide, you will find 2 common user cases:

You can also discover our real time notification API that allows you to monitor every event (sent, opened, clicked, bounced…) on the emails you will send.

Mailjet also offers an inbound emails parsing solution that allows to easily manage your contacts replies.

Filtering resources

https://api.mailjet.com/v3/REST/endpoint?filter1=this&filter2=that&filter3=it

The Mailjet API provides a set of general filters that can be applied to a GET request for each resource. In addition to these general filters, each API resource has its own filters that can be used when performing the GET. You can find these filters in their respective resource description.

To use a filter in a GET, you can amend the resource URL with a standard query string (?filter1=this&filter2=that&filter3=it).

Mailjet API supports filter combination following these rules:

The Limit Filter

# View : List of 150 contacts
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact?Limit=150 
<?php
/*
View : List of 150 contacts
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'Limit' => '150'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
/**
 *
 * View : List of 150 contacts
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .request({
        "Limit":"150"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : List of 150 contacts
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.all(limit: "150")
"""
View : List of 150 contacts
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'Limit': '150'
}
result = mailjet.contact.get(filters=filters)
print result.status_code
print result.json()
/*
View : List of 150 contacts
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    _, _, err := mailjetClient.List("contact", &data, Filter("Limit", "150"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * View : List of 150 contacts
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                  .filter(Contact.LIMIT, "150");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

You can limit the number of results by applying the Limit filter. The default value is 10 and the maximum value is 1000. ‘Limit=0’ delivers the maximum amount of results - 1000.

The Offset Filter

<?php
/*
View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'Offset' => '25000'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact?Offset=25000 
/**
 *
 * View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .request({
        "Offset":"25000"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.all(offset: "25000")
"""
View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'Offset': '25000'
}
result = mailjet.contact.get(filters=filters)
print result.status_code
print result.json()
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 {
    /**
     * View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                  .filter(Contact.OFFSET, "25000");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
/*
View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    _, _, err := mailjetClient.List("contact", &data, Filter("Offset", "25000"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}

You can use the Offset filter to retrieve a list starting from a certain offset.

<?php
/*
View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'Limit' => '150',
  'Offset' => '25000'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact?Limit=150\&Offset=25000 
/**
 *
 * View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .request({
        "Limit":"150",
        "Offset":"25000"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.all(limit: "150",offset: "25000")
"""
View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'Limit': '150',
  'Offset': '25000'
}
result = mailjet.contact.get(filters=filters)
print result.status_code
print result.json()
/*
View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    _, _, err := mailjetClient.List("contact", &data, Filter("Limit", "150"), Filter("Offset", "25000"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                  .filter(Contact.LIMIT, "150")
                  .filter(Contact.OFFSET, "25000");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

The Offset filter can be combined with the Limit filter.

The Sort Filter

<?php
/*
View : List of contact ordered by email in an ascending order
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'Sort' => 'email'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : List of contact ordered by email in an ascending order
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact?Sort=email 
/**
 *
 * View : List of contact ordered by email in an ascending order
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .request({
        "Sort":"email"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : List of contact ordered by email in an ascending order
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.all(sort: "email")
/*
View : List of contact ordered by email in an ascending order
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    _, _, err := mailjetClient.List("contact", &data, Filter("Sort", "email"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
"""
View : List of contact ordered by email in an ascending order
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'Sort': 'email'
}
result = mailjet.contact.get(filters=filters)
print result.status_code
print result.json()
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 {
    /**
     * View : List of contact ordered by email in an ascending order
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                  .filter(Contact.SORT, "email");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

You can sort a GET query by specifying a property name as the value of the 'Sort’ filter. The default sorting is ascending. When a property name is postfixed with DESC (ie property_name DESC, seperated by a space) , the sort order is descending.

Please note that the Sort filter does not work with all properties and that the DESC is not available for all properties.

<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'Sort' => 'email DESC'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : List of contact ordered by email in reverse order
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact?Sort=email+DESC 
/**
 *
 * View : List of contact ordered by email in reverse order
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .request({
        "Sort":"email DESC"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : List of contact ordered by email in reverse order
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.all(sort: "email DESC")
"""
View : List of contact ordered by email in reverse order
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'Sort': 'email DESC'
}
result = mailjet.contact.get(filters=filters)
print result.status_code
print result.json()
/*
View : List of contact ordered by email in reverse order
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    _, _, err := mailjetClient.List("contact", &data, Filter("Sort", "email DESC"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * View : List of contact ordered by email in reverse order
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                  .filter(Contact.SORT, "email DESC");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

To retrieve the same query only in descending order, amend the sort filter with DESC:

Resource Filters

<?php
/*
View : Contacts in ContactsList
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'ContactsList' => '$ContactsListID'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : Contacts in ContactsList
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact?ContactsList=$ContactsListID 
/**
 *
 * View : Contacts in ContactsList
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .request({
        "ContactsList":"$ContactsListID"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : Contacts in ContactsList
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.all(contacts_list: "$ContactsListID")
"""
View : Contacts in ContactsList
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'ContactsList': '$ContactsListID'
}
result = mailjet.contact.get(filters=filters)
print result.status_code
print result.json()
/*
View : Contacts in ContactsList
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    _, _, err := mailjetClient.List("contact", &data, Filter("ContactsList", "$ContactsListID"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * View : Contacts in ContactsList
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                  .filter(Contact.CONTACTSLIST, "$ContactsListID");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

On each resource, the API provide specific filters. Visit the reference to see what is available.

Unique Key Filters

<?php
/*
View : Contact from email address
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$response = $mj->get(Resources::$Contact, ['id' => $id]);
$response->success() && var_dump($response->getData());
?>
# View : Contact from email address
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact/$EMAIL_ADDRESS_OR_CONTACT_ID 
/**
 *
 * View : Contact from email address
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .id($EMAIL_ADDRESS_OR_CONTACT_ID)
    .request()
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : Contact from email address
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.find($EMAIL_ADDRESS_OR_CONTACT_ID)
"""
View : Contact from email address
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$EMAIL_ADDRESS_OR_CONTACT_ID'
result = mailjet.contact.get(id=id)
print result.status_code
print result.json()
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 {
    /**
     * View : Contact from email address
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource, ID);
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
/*
View : Contact from email address
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    mr := &Request{
      Resource: "contact",
      ID: RESOURCE_ID,
    }
    err := mailjetClient.Get(mr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}

You can access each unique element using unique key filter. Visit the reference to see the keys available for each resource.

<?php
/*
View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$response = $mj->get(Resources::$Eventcallbackurl, ['id' => $id]);
$response->success() && var_dump($response->getData());
?>
# View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/eventcallbackurl/$EventType|$isBackup 
/**
 *
 * View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("eventcallbackurl")
    .id($EventType|$isBackup)
    .request()
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Eventcallbackurl.find($EventType|$isBackup)
"""
View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$EventType|$isBackup'
result = mailjet.eventcallbackurl.get(id=id)
print result.status_code
print result.json()
/*
View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Eventcallbackurl
    mr := &Request{
      Resource: "eventcallbackurl",
      ID: RESOURCE_ID,
    }
    err := mailjetClient.Get(mr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.Eventcallbackurl;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Eventcallbackurl.resource, ID);
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

In some case the unique key consist of several informations, you can call this unique key combination by using the seperator |.

Like and Case Sensitive Filters

<?php
/*
View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'NameLike' => '$Name'
];
$response = $mj->get(Resources::$Liststatistics, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/liststatistics?NameLike=$Name 
/**
 *
 * View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("liststatistics")
    .request({
        "NameLike":"$Name"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Liststatistics.all(name_like: "$Name")
"""
View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'NameLike': '$Name'
}
result = mailjet.liststatistics.get(filters=filters)
print result.status_code
print result.json()
/*
View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Liststatistics
    _, _, err := mailjetClient.List("liststatistics", &data, Filter("NameLike", "$Name"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.Liststatistics;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Liststatistics.resource)
                  .filter(Liststatistics.NAMELIKE, "$Name");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

The Mailjet API allows Like and Case Sensitive filtering on selected properties. Visit the reference to see if a filter allows this functionality.

This fonctionality works by adding predefined keywords at the end of a filter:

Example : Name filter on /contact/liststatistics resource. You can use Name, NameCI, NameLike and NameLikeCI.

The Count Filter

<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'countOnly' => '1'
];
$response = $mj->get(Resources::$Contact, ['filters' => $filters]);
$response->success() && var_dump($response->getTotal());
?>
/**
 *
 * View : Total number of contact
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("contact")
    .request({
        "countOnly":"1"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : Total number of contact
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact?countOnly=1 
# View : Total number of contact
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.all(count_only: "1")
"""
View : Total number of contact
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'countOnly': '1'
}
result = mailjet.contact.get(filters=filters)
print result.status_code
print result.json()
/*
View : Total number of contact
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    _, _, err := mailjetClient.List("contact", &data, Filter("countOnly", "1"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * View : Total number of contact
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                  .filter(Contact.COUNTONLY, "1");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

API response:

{
    "Count": 152,
    "Data": [ ],
    "Total": 152
}

Use the filter countOnly to retrieve the number of records a resource will return. This filter will not extract any list of results but only count them.

To navigate on a full set of results, we advise you to either use the filter countOnly to know how many pages of results you will need to extract or to simply loop with a change of Offset until you reach an empty set of results.

Send transactional email

Choose sending method

Mailjet offers two ways to send transactional emails : SMTP Relay or Send API

SMTP Relay

SMTP Relay to send email in a fairly easy way, requiring minimum integration effort on your side.

The SMTP Relay is useful if you have an existing solution for transactional email by SMTP or if you cannot use the Send API. Using the SMTP relay, you have to take care of email headers, MIME type handling and completely format and personalize your message content.

The best and fastest way to use the SMTP Relay is to have your own local mail server relaying messages to the Mailjet SMTP. Your local mail server will give you reliable management of the messages and connections between our 2 systems. In case of breakage in the connection, your mail server will handle properly the error and retry to send your messages.

In case you don’t have a local mail server, you can still use the SMTP Relay by using one of the many SMTP libraries available or configuring your exiting system (frameworks, CMS, CRM…). However, some of these libraries or systems can lack the advanced error handling necessary to queue and resend the messages in case of error. The use of Send API can be a better choice has it require less interactions between our systems and limits the risk of failures. The error handling is also a lot simpler with the API as we are managing for you the delivery and queuing of your messages.

Using Mailjet’s SMTP servers to send your transactional emails is very simple. All you have to do is update your SMTP server settings to use our server as a “relay” or “smarthost” with the credentials provided by Mailjet. The credentials are your $MJ_APIKEY_PUBLIC as a login and $MJ_APIKEY_PRIVATE as a password.

You can find your SMTP credentials in your Account Setup page

You can find more information on how to configure the SMTP Relay and custom email headers in our SMTP Relay Guide.

Send API

Mailjet’s Send API allows you to send transactional emails using our HTTP API, using POST requests. This solution is aimed at users needing a programmatically way to send messages.

Send API allows to send single messages but also to mutualise the calls by leveraging templating and personalisation of the content.

The API will return a simple response indicating if the message is ready to be processed on the Mailjet system. This makes the error management on your side simple and efficient.

Verify a Sender

<?php
/*
Create : Manage an email sender for a single API key. An e-mail address or a complete domain (*) has to be registered and validated before being used to send e-mails. In order to manage a sender available across multiple API keys, see the related MetaSender resource.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Email' => "anothersender@example.com"
];
$response = $mj->post(Resources::$Sender, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : Manage an email sender for a single API key. An e-mail address or a complete domain (*) has to be registered and validated before being used to send e-mails. In order to manage a sender available across multiple API keys, see the related MetaSender resource.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/sender \
    -H 'Content-Type: application/json' \
    -d '{
        "Email":"anothersender@example.com"
    }'
/**
 *
 * Create : Manage an email sender for a single API key. An e-mail address or a complete domain (*) has to be registered and validated before being used to send e-mails. In order to manage a sender available across multiple API keys, see the related MetaSender resource.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("sender")
    .request({
        "Email":"anothersender@example.com"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : Manage an email sender for a single API key. An e-mail address or a complete domain (*) has to be registered and validated before being used to send e-mails. In order to manage a sender available across multiple API keys, see the related MetaSender resource.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Sender.create(email: "anothersender@example.com")
"""
Create : Manage an email sender for a single API key. An e-mail address or a complete domain (*) has to be registered and validated before being used to send e-mails. In order to manage a sender available across multiple API keys, see the related MetaSender resource.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Email': 'anothersender@example.com'
}
result = mailjet.sender.create(data=data)
print result.status_code
print result.json()
/*
Create : Manage an email sender for a single API key. An e-mail address or a complete domain (*) has to be registered and validated before being used to send e-mails. In order to manage a sender available across multiple API keys, see the related MetaSender resource.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Sender
    mr := &Request{
      Resource: "sender",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Sender {
      Email: "anothersender@example.com",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.Sender;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : Manage an email sender for a single API key. An e-mail address or a complete domain (*) has to be registered and validated before being used to send e-mails. In order to manage a sender available across multiple API keys, see the related MetaSender resource.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Sender.resource)
                        .property(Sender.EMAIL, "anothersender@example.com");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

To create a sender, provide the email address of the sender as part of a POST on the resource /sender.

A verification email will be sent to the address you added to activate this new sender.

Setup SPF/DKIM on DNS

To increase the deliverability of your emails, dont forget to setup properly your DNS record.

You can either visit the Mailjet user interface or use the Domains and DNS API guide to setup SPF and DKIM.

Sending a basic email

from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
    'FromEmail': 'pilot@mailjet.com',
    'FromName': 'Mailjet Pilot',
    'Subject': 'Your email flight plan!',
    'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
    'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
    'Recipients': [{'Email':'passenger@mailjet.com'}]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
/*
This calls sends an email to one recipient.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [
        [
            'Email' => "passenger@mailjet.com"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
        from_email: "pilot@mailjet.com",
        from_name: "Mailjet Pilot",
        subject: "Your email flight plan!",
        text_part: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        recipients: [{ 'Email'=> 'passenger@mailjet.com'}])
package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to one recipient.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
# This calls sends an email to one recipient.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}]
    }'
/**
 *
 * This calls sends an email to one recipient.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}]
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })

To send an email, you need the following mandatory properties:

Optionally, in place of Recipients, you can use To, Cc and Bcc properties. To, Cc and Bcc can’t be used in conjunction with Recipients. The properties can contain several recipients seperated by comma using the following format john@example.com, <john@example.com> or "John Doe" <john@example.com>.

Important: Recipients and To have a different behaviors. The recipients listed in To will recieve a common message showing every other recipients and carbon copies recipients. The recipients listed in Recipients will each recieve an seperate message without showing all the other recipients.

API response:

{
    "Sent": [
        {
            "Email": "passenger@mailjet.com",
            "MessageID": 111111111111111
        }
    ]
}
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'To' => "Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>",
    'CC' => "Name3 <passenger@mailjet.com>"
];
$response = $mj->post(Resources::$Send, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends an email to two recipients in To and one recipient in CC.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "To":"Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>",
        "CC":"Name3 <passenger@mailjet.com>"
    }'
/**
 *
 * This calls sends an email to two recipients in To and one recipient in CC.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "To":"Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>",
        "CC":"Name3 <passenger@mailjet.com>"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# This calls sends an email to two recipients in To and one recipient in CC.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(from_email: "pilot@mailjet.com",from_name: "Mailjet Pilot",subject: "Your email flight plan!",text_part: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",to: "Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>",cc: "Name3 <passenger@mailjet.com>")
"""
This calls sends an email to two recipients in To and one recipient in CC.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
  'To': 'Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>',
  'CC': 'Name3 <passenger@mailjet.com>'
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
/*
This calls sends an email to two recipients in To and one recipient in CC.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      To: "Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>",
      CC: "Name3 <passenger@mailjet.com>",
    },
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to two recipients in To and one recipient in CC.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.TO, "Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>")
                        .property(Email.CC, "Name3 <passenger@mailjet.com>");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

When using To, Cc and Bcc instead of Recipients, the email addresses need to be presented as SMTP headers in a string and not as an array.

MessageID is the internal Mailjet id of your message. You will be able to use this id to get more information about your message. You can find more information in our Message Statistics Guide

Sending to multiple recipients

"""
This calls sends an email to 2 recipients.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
  'Recipients': [
        {
            "Email": "passenger1@mailjet.com",
            "Name": "passenger 1"
        },
        {
            "Email": "passenger2@mailjet.com",
            "Name": "passenger 2"
        }
    ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to 2 recipients.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger1@mailjet.com")
                    .put("Name", "passenger 1"))
                .put(new JSONObject()
                    .put("Email", "passenger2@mailjet.com")
                    .put("Name", "passenger 2")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [
        [
            'Email' => "passenger1@mailjet.com",
            'Name' => "passenger 1"
        ],
        [
            'Email' => "passenger2@mailjet.com",
            'Name' => "passenger 2"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
        from_email: "pilot@mailjet.com",
        from_name: "Mailjet Pilot",
        subject: "Your email flight plan!",
        text_part: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        recipients: [{'Email'=> 'passenger@mailjet.com', 'Name' => 'passenger 1'}, {'Email' => 'passenger2@mailjet.com', 'Name' => 'passenger 2'}])
# This calls sends an email to 2 recipients.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    }'
/*
This calls sends an email to 2 recipients.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger1@mailjet.com",
          Name: "passenger 1",
        },
        Recipient {
          Email: "passenger2@mailjet.com",
          Name: "passenger 2",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}
/**
 *
 * This calls sends an email to one recipient.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })

API response:

{
    "Sent": [
        {
            "Email": "passenger1@mailjet.com",
            "MessageID": 20547681647433000
        },
        {
            "Email": "passenger2@mailjet.com",
            "MessageID": 20547681647433001
        }
    ]
}

To send the same email to multiple contacts, add Email addresses in the Recipients list.

Each recipient will receive a dedicated message.

Sending with attached files

"""
This calls sends an email to the given recipient.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3>May the delivery force be with you!',
  'Recipients': [{ "Email": "passenger@mailjet.com"}],
  'Attachments':
        [{
            "Content-type": "text/plain",
            "Filename": "test.txt",
            "content": "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"
        }]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to the given recipient.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.ATTACHMENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Content-type", "text/plain")
                    .put("Filename", "test.txt")
                    .put("content", "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK")));
      response = client.post(request);
      System.out.println(response.getData());
    }
}
/*
This calls sends an email to the given recipient.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
      Attachments: []MailjetAttachment {
        MailjetAttachment {
          ContentType: "text/plain",
          Filename: "test.txt",
          Content: "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [
        [
            'Email' => "passenger@mailjet.com"
        ]
    ],
    'Attachments' => [
        [
            'Content-type' => "text/plain",
            'Filename' => "test.txt",
            'content' => "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends an email to the given recipient.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
        from_email: "pilot@mailjet.com",
        from_name: "Mailjet Pilot",
        subject: "Your email flight plan!",
        text_part: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        recipients: [{'Email'=> 'passenger@mailjet.com'}],
    attachments: [{'Content-Type' => 'text/plain', 'Filename' => 'test.txt', 'content' => 'VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK'}])
# This calls sends an email to the given recipient.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Attachments":[{"Content-type":"text/plain","Filename":"test.txt","content":"VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"}]
    }'
/**
 *
 * This calls sends an email to one recipient.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Attachments":[{"Content-type":"text/plain","Filename":"test.txt","content":"VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"}]
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log (err.statusCode)
    })

To attach files, use Attachments or Inline_attachments.
The recipient of a email with attachment will have to click to see it. The inline attachment can be visible directly in the body of the message depending of the email client support.

In both calls, the content will need to be Base64 encoded. You will need to specify the MIME type and a file name.

"""
This calls sends an email to the given recipient.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  'Html-part': '<h3>Dear passenger, welcome to <img src="cid:logo.gif">Mailjet!</h3><br />May the delivery force be with you!',
  'Recipients': [ { "Email": "passenger@mailjet.com" }],
  'Inline_attachments': [
                {
                        "Content-type": "image/gif",
                        "Filename": "logo.gif",
                        "content": "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"
                }
        ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to the given recipient.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to <img src=\"cid:logo.gif\">Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.INLINE_ATTACHMENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Content-type", "image/gif")
                    .put("Filename", "logo.gif")
                    .put("content", "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")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to <img src=\"cid:logo.gif\">Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [
        [
            'Email' => "passenger@mailjet.com"
        ]
    ],
    'Inline_attachments' => [
        [
            'Content-type' => "image/gif",
            'Filename' => "logo.gif",
            'content' => "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"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
        from_email: "pilot@mailjet.com",
        from_name: "Mailjet Pilot",
        subject: "Your email flight plan!",
        text_part: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        html_part: "<h3>Dear passenger, welcome to <img src=\"cid:logo.gif\">Mailjet!</h3><br />May the delivery force be with you!",
        recipients: [{'Email'=> 'passenger@mailjet.com'}],
    'inline-attachments' => [{'Content-type' => 'image/gif', 'Filename' => 'logo.gif', 'content' => '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'}])
# This calls sends an email to the given recipient.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to <img src=\"cid:logo.gif\">Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Inline_attachments":[{"Content-type":"image/gif","Filename":"logo.gif","content":"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"}]
    }'
/**
 *
 * This calls sends an email to one recipient.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to <img src=\"cid:logo.gif\">Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Inline_attachments":[{"Content-type":"image/gif","Filename":"logo.gif","content":"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"}]
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(error => {
    console.log(error.statusCode)
    })
/*
This calls sends an email to the given recipient.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to <img src=\"cid:logo.gif\">Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
      InlineAttachments: []MailjetAttachment {
        MailjetAttachment {
          ContentType: "image/gif",
          Filename: "logo.gif",
          Content: "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",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

When using an inline Attachment, it’s possible to insert the file inside the HTML code of the email by using cid:FILENAME.EXT where FILENAME.EXT is the Filename specified in the declaration of the Attachment.

Sending in bulk

"""
This calls sends an email to the given recipient.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Messages': [
     {
        "FromEmail": "pilot@mailjet.com",
        "FromName": "Mailjet Pilot",
        "Recipients": [{ "Email": "passenger1@mailjet.com", "Name": "passenger 1" }],
        "Subject": "Your email flight plan!",
        "Text-part": "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
        "Html-part": "<h3>Dear passenger 1, welcome to Mailjet!</h3><br />May the delivery force be with you!"
      },
      {
        "FromEmail": "pilot@mailjet.com",
        "FromName": "Mailjet Pilot",
        "Recipients": [{ "Email": "passenger2@mailjet.com", "Name": "passenger 2" }],
        "Subject": "Your email flight plan!",
        "Text-part": "Dear passenger 2, welcome to Mailjet! May the delivery force be with you!",
        "Html-part": "<h3>Dear passenger 2, welcome to Mailjet!</h3><br />May the delivery force be with you!"
      }
    ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to the given recipient.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.MESSAGES, new JSONArray()
                .put(new JSONObject()
                    .put("FromEmail", "pilot@mailjet.com")
                    .put("FromName", "Mailjet Pilot")
                    .put("Recipients", new JSONArray()
                        .put(new JSONObject()
                            .put("Email", "passenger1@mailjet.com")
                            .put("Name", "passenger 1")))
                    .put("Subject", "Your email flight plan!")
                    .put("Text-part", "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!")
                    .put("Html-part", "<h3>Dear passenger 1, welcome to Mailjet!</h3><br />May the delivery force be with you!"))
                .put(new JSONObject()
                    .put("FromEmail", "pilot@mailjet.com")
                    .put("FromName", "Mailjet Pilot")
                    .put("Recipients", new JSONArray()
                        .put(new JSONObject()
                            .put("Email", "passenger2@mailjet.com")
                            .put("Name", "passenger 2")))
                    .put("Subject", "Your email flight plan!")
                    .put("Text-part", "Dear passenger 2, welcome to Mailjet! May the delivery force be with you!")
                    .put("Html-part", "<h3>Dear passenger 2, welcome to Mailjet!</h3><br />May the delivery force be with you!")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Messages' => [
        [
            'FromEmail' => "pilot@mailjet.com",
            'FromName' => "Mailjet Pilot",
            'Recipients' => [
                [
                    'Email' => "passenger1@mailjet.com",
                    'Name' => "passenger 1"
                ]
            ],
            'Subject' => "Your email flight plan!",
            'Text-part' => "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
            'Html-part' => "<h3>Dear passenger 1, welcome to Mailjet!</h3><br />May the delivery force be with you!"
        ],
        [
            'FromEmail' => "pilot@mailjet.com",
            'FromName' => "Mailjet Pilot",
            'Recipients' => [
                [
                    'Email' => "passenger2@mailjet.com",
                    'Name' => "passenger 2"
                ]
            ],
            'Subject' => "Your email flight plan!",
            'Text-part' => "Dear passenger 2, welcome to Mailjet! May the delivery force be with you!",
            'Html-part' => "<h3>Dear passenger 2, welcome to Mailjet!</h3><br />May the delivery force be with you!"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  messages: [
    {
      'FromEmail' => 'pilot@mailjet.com',
      'FromName' => 'Mailjet Pilot',
      'Recipients' => [{'Email' => 'passenger1@mailjet.com', 'Name' => 'passenger 1'}],
      'subject' => 'email 1',
      'text-part' => 'Dear passenger 1, welcome to Mailjet! May the delivery force be with you!',
    },
    {
      'fromEmail' => 'pilot@mailjet.com',
      'fromName' => 'Mailjet Pilot',
      'Recipients' => [{'Email' => 'passenger2@mailjet.com', 'Name' => 'passenger 2'}],
      'subject' => 'email 2',
      'text-part' => 'Dear passenger 2, welcome to Mailjet! May the delivery force be with you!',
    }])
# This calls sends an email to the given recipient.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "Messages":[
            {
            "FromEmail":"pilot@mailjet.com",
            "FromName":"Mailjet Pilot",
            "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"}],
            "Subject":"Your email flight plan!",
            "Text-part":"Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
            "Html-part":"<h3>Dear passenger 1, welcome to Mailjet!</h3><br />May the delivery force be with you!"
            },
            {
            "FromEmail":"pilot@mailjet.com",
            "FromName":"Mailjet Pilot",
            "Recipients":[{"Email":"passenger2@mailjet.com","Name":"passenger 2"}],
            "Subject":"Your email flight plan!",
            "Text-part":"Dear passenger 2, welcome to Mailjet! May the delivery force be with you!",
            "Html-part":"<h3>Dear passenger 2, welcome to Mailjet!</h3><br />May the delivery force be with you!"
            }
        ]
    }'
/**
 *
 * This calls sends an email to one recipient.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "Messages":[
            {
            "FromEmail":"pilot@mailjet.com",
            "FromName":"Mailjet Pilot",
            "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"}],
            "Subject":"Your email flight plan!",
            "Text-part":"Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
            "Html-part":"<h3>Dear passenger 1, welcome to Mailjet!</h3><br />May the delivery force be with you!"
            },
            {
            "FromEmail":"pilot@mailjet.com",
            "FromName":"Mailjet Pilot",
            "Recipients":[{"Email":"passenger2@mailjet.com","Name":"passenger 2"}],
            "Subject":"Your email flight plan!",
            "Text-part":"Dear passenger 2, welcome to Mailjet! May the delivery force be with you!",
            "Html-part":"<h3>Dear passenger 2, welcome to Mailjet!</h3><br />May the delivery force be with you!"
            }
        ]
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(error => {
        console.log (error.statusCode);
    })
/*
This calls sends an email to the given recipient.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      Messages: []InfoSendMail {
        InfoSendMail {
          FromEmail: "pilot@mailjet.com",
          FromName: "Mailjet Pilot",
          Recipients: []Recipient {
            Recipient {
              Email: "passenger1@mailjet.com",
              Name: "passenger 1",
            },
          },
          Subject: "Your email flight plan!",
          TextPart: "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
          HTMLPart: "<h3>Dear passenger 1, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        },
        InfoSendMail {
          FromEmail: "pilot@mailjet.com",
          FromName: "Mailjet Pilot",
          Recipients: []Recipient {
            Recipient {
              Email: "passenger2@mailjet.com",
              Name: "passenger 2",
            },
          },
          Subject: "Your email flight plan!",
          TextPart: "Dear passenger 2, welcome to Mailjet! May the delivery force be with you!",
          HTMLPart: "<h3>Dear passenger 2, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

API response:

{
    "Sent": [
        {
            "Email": "passenger1@mailjet.com",
            "MessageID": 20547681647433000
        },
        {
            "Email": "passenger2@mailjet.com",
            "MessageID": 20547681647433001
        }
    ]
}

To send messages in bulk, package the multiple messages inside a Messages property. Each message inside this list of message will enjoy the same properties described above.

Personalisation

Content formatting

Mailjet system allows to insert data in your text or html parts.

To do so, use [[DATA_TYPE:DATA_NAME]] where:

Using vars and custom vars

"""
This calls sends an email to 2 given recipient with global personalisation.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'Text-part': 'Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you!',
  'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you!',
  'Vars': {
            "day": "Monday"
        },
  'Recipients': [
        {
            "Email": "passenger1@mailjet.com",
            "Name": "passenger 1"
        },
        {
            "Email": "passenger2@mailjet.com",
            "Name": "passenger 2"
        }
    ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to 2 given recipient with global personalisation.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! On this [[var:day:\"monday\"]], may the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day:\"monday\"]], may the delivery force be with you!")
                        .property(Email.VARS, new JSONObject()
                .put("day", "Monday"))
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger1@mailjet.com")
                    .put("Name", "passenger 1"))
                .put(new JSONObject()
                    .put("Email", "passenger2@mailjet.com")
                    .put("Name", "passenger 2")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
/*
This calls sends an email to 2 given recipient with global personalisation.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you!",
    'Vars' => [
        'day' => "Monday"
    ],
    'Recipients' => [
        [
            'Email' => "passenger1@mailjet.com",
            'Name' => "passenger 1"
        ],
        [
            'Email' => "passenger2@mailjet.com",
            'Name' => "passenger 2"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  'FromEmail' => 'pilot@mailjet.com',
  'FromName' => 'Mailjet Pilot',
  'Subject' => 'Your email flight plan!',
  'Text-part' => 'Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you!',
  'Html-part' => '<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you!',
  'Vars' => {'day' => 'Monday'},
  'Recipients' => [
      {'Email' => 'passenger1@mailjet.com','Name' => 'passenger 1'},
      {'Email' => 'passenger2@mailjet.com','Name' => 'passenger 2'}
  ]
)
# This calls sends an email to 2 given recipient with global personalisation.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you!",
        "Vars":{"day":"Monday"},
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    }'
/**
 *
 * This calls sends an email to 2 given recipient with global personalisation.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you!",
        "Vars":{"day":"Monday"},
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    })
request
    .then(result => {
        console.log(result.body)
    })
  .catch(e => {
        console.log(e.statusCode)
    })
/*
This calls sends an email to 2 given recipient with global personalisation.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
type  MyVarsStruct  struct {
  Day  string
}
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you!",
      Vars: MyVarsStruct {
        Day: "Monday",
      },
      Recipients: []Recipient {
        Recipient {
          Email: "passenger1@mailjet.com",
          Name: "passenger 1",
        },
        Recipient {
          Email: "passenger2@mailjet.com",
          Name: "passenger 2",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

By using Vars in conjunction with the [[var:VAR_NAME]], you can modify the content of you email.

package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to 2 recipients with global and contact personalisation.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! On this [[var:day:\"monday\"]], may the delivery force be with you! [[var:personalmessage:\"\"]]")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day:\"monday\"]], may the delivery force be with you! [[var:personalmessage:\"\"]]")
                        .property(Email.VARS, new JSONObject()
                .put("day", "Monday"))
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger1@mailjet.com")
                    .put("Name", "passenger 1")
                    .put("Vars", new JSONObject()
                        .put("day", "Tuesday")
                        .put("personalmessage", "Happy birthday!")))
                .put(new JSONObject()
                    .put("Email", "passenger2@mailjet.com")
                    .put("Name", "passenger 2")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
"""
This calls sends an email to 2 recipients with global and contact personalisation.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'Text-part': 'Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]',
  'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]',
  'Vars': {
        "day": "Monday"
  },
  'Recipients': [
        {
            "Email": "passenger1@mailjet.com",
            "Name": "passenger 1",
            "Vars": {
                "day": "Tuesday",
                "personalmessage": "Happy birthday!"
            }
        },
        {
            "Email": "passenger2@mailjet.com",
            "Name": "passenger 2"
        }
    ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
<?php
/*
This calls sends an email to 2 recipients with global and contact personalisation.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
    'Vars' => [
        'day' => "Monday"
    ],
    'Recipients' => [
        [
            'Email' => "passenger1@mailjet.com",
            'Name' => "passenger 1",
            'Vars' => [
                'day' => "Tuesday",
                'personalmessage' => "Happy birthday!"
            ]
        ],
        [
            'Email' => "passenger2@mailjet.com",
            'Name' => "passenger 2"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: "pilot@mailjet.com",
  from_name: "Mailjet Pilot",
  subject: "Your email flight plan!",
  text_part: "Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
  html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
  vars: {'day' => 'Monday'},
  recipients: [
    {'Email' => 'passenger1@mailjet.com', 'Name' => 'passenger 1', 'Vars' => {'day' => 'Tuesday', 'personalmessage' => 'Happy birthday!'}},
    {'Email' => 'passenger2@mailjet.com', 'Name' => 'passenger 2'}]
)
# This calls sends an email to 2 recipients with global and contact personalisation.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
        "Vars":{"day":"Monday"},
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1","Vars":{"day":"Tuesday","personalmessage":"Happy birthday!"}},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    }'
/**
 *
 * This calls sends an email to 2 recipients with global and contact personalisation.
 *
 */
var mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
var request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
        "Vars":{"day":"Monday"},
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1","Vars":{"day":"Tuesday","personalmessage":"Happy birthday!"}},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    })
request
    .then(result => {
        console.log(result.body)
    })
  .catch(error => {
        console.log(error.statusCode)
    })
/*
This calls sends an email to 2 recipients with global and contact personalisation.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
type  MyVarsStruct  struct {
  Day  string
}
type MyRecipientsVarsStruct struct {
  Day               string
  Personalmessage   string
}
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]",
      Vars: MyVarsStruct {
        Day: "Monday",
      },
      Recipients: []Recipient {
        Recipient {
          Email: "passenger1@mailjet.com",
          Name: "passenger 1",
          Vars: MyRecipientsVarsStruct {
            Day: "Tuesday",
            Personalmessage: "Happy birthday!",
          },
        },
        Recipient {
          Email: "passenger2@mailjet.com",
          Name: "passenger 2",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

To go further in personalisation Vars is also available for each recipient. The main Vars will be overidden by the recipient Vars

Using contact properties

package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to the given recipient.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear [[data:firstname:\"passenger\"]], welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear [[data:firstname:\"passenger\"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger1@mailjet.com")
                    .put("Name", "passenger 1"))
                .put(new JSONObject()
                    .put("Email", "passenger2@mailjet.com")
                    .put("Name", "passenger 2")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
    "FromEmail":"pilot@mailjet.com",
    "FromName":"Mailjet Pilot",
    "Subject":"Your email flight plan!",
    "Text-part":"Dear [[data:firstname:\"passenger\"]], welcome to Mailjet! May the delivery force be with you!",
    "Html-part":"<h3>Dear [[data:firstname:\"passenger\"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!",
    "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear [[data:firstname:\"passenger\"]], welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear [[data:firstname:\"passenger\"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!",
    'Recipients' => [
        [
            'Email' => "passenger1@mailjet.com",
            'Name' => "passenger 1"
        ],
        [
            'Email' => "passenger2@mailjet.com",
            'Name' => "passenger 2"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: 'pilot@mailjet.com',
  from_name: 'Mailjet Pilot',
  subject: 'Your email flight plan!',
  text_part: 'Dear [[data:firstname: "passenger"]], welcome to Mailjet! May the delivery force be with you!',
  html_part: '<h3>Dear [[data:firstname: "passenger"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!',
  recipients:[
    {'Email':'passenger1@mailjet.com','Name':'passenger 1'},
    {'Email':'passenger2@mailjet.com','Name':'passenger 2'}])
# This calls sends an email to the given recipient.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear [[data:firstname:\"passenger\"]], welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear [[data:firstname:\"passenger\"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!",
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    }'
/**
 *
 * This calls sends an email to one recipient.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear [[data:firstname:\"passenger\"]], welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear [[data:firstname:\"passenger\"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!",
        "Recipients":[{"Email":"passenger1@mailjet.com","Name":"passenger 1"},{"Email":"passenger2@mailjet.com","Name":"passenger 2"}]
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })
/*
This calls sends an email to the given recipient.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear [[data:firstname:\"passenger\"]], welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear [[data:firstname:\"passenger\"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger1@mailjet.com",
          Name: "passenger 1",
        },
        Recipient {
          Email: "passenger2@mailjet.com",
          Name: "passenger 2",
        },
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

If the contact you are sending an email to is already in Mailjet system with some contact datas, you can leverage this information to personalise your email.

Use [[data:METADATA_NAME]] or [[data:METADATA_NAME:DEFAULT_VALUE]] to insert data in your content.

DEFAULT_VALUEis the default value that will be used if no data found.

More information about how to add contact properties.

Go further with personalisation

Mailjet offers a Templating language that can extend the personalisation of your transactional messages. Visit Transactional templating guide to learn about additional substitutions, modification functions and conditional statements you can use to personalize messages.

Using a Template

package MyClass;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.errors.MailjetClient;
import com.mailjet.client.errors.MailjetRequest;
import com.mailjet.client.errors.MailjetResponse;
import com.mailjet.client.resource.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends a message based on a template.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.MJTEMPLATEID, 1)
                        .property(Email.MJTEMPLATELANGUAGE, true)
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.MJEVENTPAYLOAD, "Eticket,1234,row,15,seat,B");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
/*
This calls sends a message based on a template.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'MJ-TemplateID' => 1,
    'MJ-TemplateLanguage' => true,
    'Recipients' => [['Email' => "passenger@mailjet.com"]]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends a message based on a template.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateID":"1",
        "MJ-TemplateLanguage":true,
        "Recipients":[
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
    }'
/**
 *
 * This calls sends a message based on a template.
 *
 */
var mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
var request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateID":"1",
        "MJ-TemplateLanguage":"true",
        "Recipients":[
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
    });
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })
# This calls sends a message based on a template.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: "pilot@mailjet.com",
  from_name: "Mailjet Pilot",
  subject: "Your email flight plan!",
  "Mj-TemplateID": "1",
  "Mj-TemplateLanguage": true,
  recipients: [{ 'Email'=> 'passenger@mailjet.com'}]
)
"""
This calls sends a message based on a template.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'MJ-TemplateID': '1',
  'MJ-TemplateLanguage': 'true',
  'Recipients': [
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
/*
This calls sends a message based on a template.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      MJTemplateID: 1,
      MJTemplateLanguage: "true",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
    },
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

Mailjet offers to store your transactional message templates on its platform. You can use these templates in your transactional API call to remove the need to repeat the content of a transactional message at each Send API call.

You can either create the templates through our online drag and drop tool Passport or through the /template resource.

You can learn more about storing your templates through API here.

You can also follow our Step by Step guide to create your first Passport template with templating language.

In the templates, you will be able to use simple personalisation ([[data:property_name]] or [[var:variable_name]]) or advanced templating language ({{data:property_name}}, {{var:variable_name}}, conditional statements and loop statements)

In this sample, Mj-TemplateID will be the Id provided by Passport at the end of your designing process or the Id returned by the /template resource.

Adding Email Headers

package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to one recipient with a Reply-To address.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.HEADERS, new JSONObject()
                .put("Reply-To", "copilot@mailjet.com"));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
    "FromEmail":"pilot@mailjet.com",
    "FromName":"Mailjet Pilot",
    "Subject":"Your email flight plan!",
    "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    "Recipients":[{"Email":"passenger@mailjet.com"}],
    "Headers":  {"Reply-To":"copilot@mailjet.com"}
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [
        [
            'Email' => "passenger@mailjet.com"
        ]
    ],
    'Headers' => [
        'Reply-To' => "copilot@mailjet.com"
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: 'pilot@mailjet.com',
  from_name: 'Mailjet Pilot',
  subject: 'Your email flight plan!',
  text_part: 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  html_part: '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
  headers: {'Reply-To' => 'copilot@mailjet.com'},
  recipients:[{'Email' => 'passenger@mailjet.com'}])
# This calls sends an email to one recipient with a Reply-To address.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Headers" : {"Reply-To":"copilot@mailjet.com"}
    }'
/**
 *
 * This calls sends an email to one recipient with a Reply-To address.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Headers": {"Reply-To":"copilot@mailjet.com"}
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(error => {
        console.log(error.statusCode)
    })
/*
This calls sends an email to one recipient with a Reply-To address.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
      Headers: map[string]string {
        "ReplyTo": "copilot@mailjet.com",
      },
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

In every message, you can specify your own Email headers using the Headers property. For example, it is possible to specify a Reply-To email address.

Tagging Email Messages

Mailjet provides 2 properties to tag messages with your own custom information.

These custom pieces of information are returned back in the events you registered to via our Event API and in the messages processed via our Parse API.

Sending an email with a custom ID

package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends a message to one recipient with a CustomID.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.MJCUSTOMID, "PassengerEticket1234");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
    "FromEmail":"pilot@mailjet.com",
    "FromName":"Mailjet Pilot",
    "Subject":"Your email flight plan!",
    "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    "Recipients":[{"Email":"passenger@mailjet.com"}],
    "Mj-CustomID":"PassengerEticket1234"
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [['Email' => "passenger@mailjet.com"]],
    'Mj-CustomID' => "PassengerEticket1234"
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: 'pilot@mailjet.com',
  from_name: 'Mailjet Pilot',
  subject: 'Your email flight plan!',
  text_part: 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  html_part: '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
  recipients:[{'Email' => 'passenger@mailjet.com'}],
  'Mj-CustomID' => 'PassengerEticket1234')
# This calls sends a message to one recipient with a CustomID.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Mj-CustomID":"PassengerEticket1234"
    }'
/**
 *
 * This calls sends a message to one recipient with a CustomID.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Mj-CustomID":"PassengerEticket1234"
    })
request
    .then(result => {
        console.log(result.body)
    })
  .catch(error => {
    console.log(error.statusCode)
    })
/*
This calls sends a message to one recipient with a CustomID.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
      MjCustomID: "PassengerEticket1234",
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

Sometimes you need to use your own ID in addition to ours to be able to trace back the message in our system easily. For this purpose we let you insert your own ID in the message. To achieve this, just pass the ID you want to use in the Mj-CustomID property.

<?php
/*
View : API Key Statistical campaign/message data.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'CustomID' => 'PassengerEticket1234'
];
$response = $mj->get(Resources::$Messagesentstatistics, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : API Key Statistical campaign/message data.
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/messagesentstatistics?CustomID=PassengerEticket1234 
/**
 *
 * View : API Key Statistical campaign/message data.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("messagesentstatistics")
    .request({
        "CustomID":"PassengerEticket1234"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : API Key Statistical campaign/message data.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Messagesentstatistics.all(custom_id: "PassengerEticket1234")
"""
View : API Key Statistical campaign/message data.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'CustomID': 'PassengerEticket1234'
}
result = mailjet.messagesentstatistics.get(filters=filters)
print result.status_code
print result.json()
/*
View : API Key Statistical campaign/message data.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Messagesentstatistics
    _, _, err := mailjetClient.List("messagesentstatistics", &data, Filter("CustomID", "PassengerEticket1234"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.Messagesentstatistics;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * View : API Key Statistical campaign/message data.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Messagesentstatistics.resource)
                  .filter(Messagesentstatistics.CUSTOMID, "PassengerEticket1234");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

From then, your CustomID is linked to our own Message ID. You can also retrieve the message later by providing it to the /messagesentstatistics resource CustomID filter.

Sending an email with a payload

package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends a message to one recipient with an EventPayload.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.MJEVENTPAYLOAD, "Eticket,1234,row,15,seat,B");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
    "FromEmail":"pilot@mailjet.com",
    "FromName":"Mailjet Pilot",
    "Subject":"Your email flight plan!",
    "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    "Recipients":[{"Email":"passenger@mailjet.com"}],
    "Mj-EventPayLoad":"Eticket,1234,row,15,seat,B"
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
<?php
/*
This calls sends a message to one recipient with an EventPayload.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [['Email' => "passenger@mailjet.com"]],
    'Mj-EventPayLoad' => "Eticket,1234,row,15,seat,B"
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: 'pilot@mailjet.com',
  from_name: 'Mailjet Pilot',
  subject: 'Your email flight plan!',
  text_part: 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  html_part: '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
  recipients:[{'Email' => 'passenger@mailjet.com'}],
  'Mj-EventPayLoad' => 'Eticket,1234,row,15,seat,B')
# This calls sends a message to one recipient with an EventPayload.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Mj-EventPayLoad":"Eticket,1234,row,15,seat,B"
    }'
/**
 *
 * This calls sends a message to one recipient with an EventPayload.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Mj-EventPayLoad":"Eticket,1234,row,15,seat,B"
    })
request
  .then(result => {
        console.log(result.body)
    })
  .catch(error => {
    console.log(error.statusCode)
    })
/*
This calls sends a message to one recipient with an EventPayload.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
      MjEventPayLoad: "Eticket,1234,row,15,seat,B",
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

Sometimes, you need more than just an ID to represent the context to what a specific message is attached to. For this purpose, we let you insert a payload in the message which can be of any format (XML, JSON, CSV, etc). To take advantage of this, just pass the payload you want in the Mj-EventPayLoad property.

Grouping into a campaign

"""
This calls sends an email to one recipient within a campaign blocking multiple email to same recipient
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
  'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
  'Recipients': [{ Email": "passenger@mailjet.com" }],
  'Mj-campaign': 'SendAPI_campaign',
  'Mj-deduplicatecampaign': '1'
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
package MyClass;
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to one recipient within a campaign blocking multiple email to same recipient
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
                        .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.MJCAMPAIGN, "SendAPI_campaign")
                        .property(Email.MJDEDUPLICATECAMPAIGN, "1");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'Text-part' => "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    'Html-part' => "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
    'Recipients' => [
        [
            'Email' => "passenger@mailjet.com"
        ]
    ],
    'Mj-campaign' => "SendAPI_campaign",
    'Mj-deduplicatecampaign' => 1
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends an email to the given recipient.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
        from_email: "pilot@mailjet.com",
        from_name: "Mailjet Pilot",
        subject: "Your email flight plan!",
        text_part: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        recipients: [{'Email'=> 'passenger@mailjet.com'}],
        'Mj-campaign' => 'SendAPI_campaign',
        'Mj-duplicatecampaign' => 1)
# This calls sends an email to one recipient within a campaign blocking multiple email to same recipient
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[
                {
                        "Email": "passenger@mailjet.com"
                }
        ],
        "Mj-campaign":"SendAPI_campaign",
        "Mj-deduplicatecampaign":1
    }'
/**
 *
 * This calls sends an email to one recipient within a campaign blocking multiple email to same recipient
 *
 */
var mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
var request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
        "Recipients":[{"Email":"passenger@mailjet.com"}],
        "Mj-campaign":"SendAPI_campaign",
        "Mj-deduplicatecampaign":1
    });
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })
/*
This calls sends an email to one recipient within a campaign blocking multiple email to same recipient
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
      HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
      MjCampaign: "SendAPI_campaign",
      MjDeduplicateCampaign: 1,
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

Messages sent through Send API can be regrouped into campaigns to simulate the behavior of a regular Marketing Campaign. This is useful when your transactional needs are advanced (statistics…).

Use the Property Mj-campaign to specify the name of the campaign the message will be classified in. If the campaign doesn’t already exist it will be automatically created in Mailjet system.

By default, Mailjet lets you send multiple emails with the same campaign to the same contact. To block this feature, use Mj-deduplicatecampaign with the value 1 to stop contacts from being emailed several times in the same campaign.

Send API json properties

Property Name Description
FromEmail Must be a valid, activated and registered sender for this account
May include the name part: john@example.com or <john@example.com> or "John Doe" <john@example.com>
MANDATORY - MAX FROM: 1
FromName Must be a valid, activated and registered sender for this account
May include the name part: john@example.com or <john@example.com> or "John Doe" <john@example.com>
Sender This can be set only on given API Keys. Contact the support team if you want us to enable this setting on your account.
Must be a valid active sender for this account.
Perform a simple GET on resource /sender to view a list of allowed senders for your account, or within the Mailjet Account Settings under Sender Addresses
MAX SENDER: 1
Recipients List of recipients, Must include at least a property Email in each element
Sample: [{"Email":"passenger@mailjet.com","Name":"passenger"}]
MANDATORY
To May include the name part: john@example.com or <john@example.com> or "John Doe" <john@example.com>
If a recipient is specified twice (in the to, cc, or bcc), it is counted only once.
Can be a magic list @lists.mailjet.com. See the Address contactslist property.
MAX RECIPIENTS: 50
Cc, Bcc May include the name part: john@example.com or <john@example.com> or "John Doe" <john@example.com>
If one recipient is specified twice, count as one only (including to, cc, bcc)
MAX RECIPIENTS: 50
Cc and Bcc can’t be used in conjunction with Recipients property
Subject Maximum length is 255 chars
MAX SUBJECTS: 1
Text-part Provides the Text part of the message
Mandatory if the HTML param is not specified
MANDATORY IF NO HTML - MAX PARTS: 1
Html-part Provides the HTML part of the message
Mandatory if the text param is not specified
MANDATORY IF NO TEXT - MAX PARTS: 1
Mj-TemplateID The Template ID or Name to use as this email content. Overrides the HTML/Text parts if any.
Equivalent to using the X-MJ-TemplateID header through SMTP.
MANDATORY IF NO HTML/TEXT - MAX TEMPLATEID: 1
Mj-TemplateLanguage Activate the template language processing. By default the template language processing is deactivated. Use True to activate.
Equivalent to using the X-MJ-TemplateLanguage header through SMTP.
More information
MJ-TemplateErrorReporting Email Address where a carbon copy with error message is sent to.
Equivalent to using the X-MJ-TemplateErrorReporting header through SMTP.
More information
MJ-TemplateErrorDeliver Define if the message is delivered if an error is discovered in the templating language. By default the delivery is deactivated. Use deliver to let the message be delivered to the recipient, 0 to stop it.
Equivalent to using the X-MJ-TemplateErrorDeliver header through SMTP.
More information
Attachments Attach files automatically to this Email
Sum of all attachments, including inline may not exceed 15 MB total
Sample: [{“Content-type”: “MIME TYPE”, “Filename”: “FILENAME.EXT”, “content”:“BASE64 ENCODED CONTENT”}]
Inline_attachments Attach a file for inline use via cid:FILENAME.EXT
Sum of all attachements, including inline may not exceed 15 MB total
Sample: [{“Content-type”: “MIME TYPE”, “Filename”: “FILENAME.EXT”, “content”:“BASE64 ENCODED CONTENT”}]
Mj-prio Manage message processing priority inside your account (API key) scheduling queue.
Default is 2 as in the SMTP submission.
Equivalent of using X-Mailjet-Prio header through SMTP
More information
Mj-campaign Groups multiple messages in one campaign
Equivalent of using X-Mailjet-Campaign header through SMTP.
More information
Mj-deduplicatecampaign Block/unblock messages to be sent multiple times inside one campaign to the same contact.
- 0: unblocked (default behavior)
- 1: blocked
Equivalent of using X-Mailjet-DeduplicateCampaign header through SMTP.
Can only be used if mj-campaign is specified.
More information
Mj-trackopen Force or disable open tracking on this message, can overriding account preferences.
Can only be used with a HTML part.
- 0: take the values defined on the account. The ones shown here
- 1: disable the tracking
- 2: enable the tracking
A X-Mailjet-TrackOpen SMTP header is also available to modify the tracking behaviour.
More information on custom SMTP headers
Mj-trackclick Force or disable click tracking on this message, can overriding account preferences.
Can only be specified if the HTML part is provided.
- 0: take the values defined on the account. The ones shown here
- 1: disable the tracking
- 2: enable the tracking
A X-Mailjet-TrackClick SMTP header is also available to modify the tracking behaviour.
More information on custom SMTP headers
Mj-CustomID Attach a custom ID to the message
Equivalent to using the X-MJ-CustomID header through SMTP.
More information
Mj-EventPayLoad Attach a payload to the message
Equivalent to using the X-MJ-EventPayload header through SMTP.
More information
Headers Add lines to the email’s headers
List of headers as "property":"value" pairs
Notice: overriding values of header properties (ie: subject)
Sample: {"X-My-Header":"my own value","X-My-Header-2":"my own value 2"}
Vars Global variables used for personalisation
Equivalent of using X-MJ-Vars header through SMTP.
Messages List of messages
Used for bulk emailing.
More information

Send API errors

Error Code Message Reason
400 Invalid characters detected A non UTF-8 character was detected
400 “Headers” is not JSON object type The Headers property should follow the format {“X-My-Header”:“my own value”,“X-My-Header-2”:“my own value 2”}
400 Header [Property name] is not string type
400 Missing “To” or “Recipients” property Send API must be called with either “To” or “Recipient” properties
400 Too many recipients in To
Too many recipients in Cc
Too many recipients in Bcc
To, Cc and Bcc can’t exceed 50 Email addresses

Transactional templating

Overview

Leveraging the Mailjet templating language for transactional, designing and building dynamic email, ones that can highly adapt to your recipients profiles, has never been easier. Using a syntax close to the one used by the most popular templating language, such as Jinja2 or Twig, it’s already familiar to you

Go beyond simple personalisation tags by adding logic into your email to include/remove sections of the delivered message.

Additionally, Template API allows for the storage of your templates on the Mailjet system. If you wish, no need to provide the content of your message at each call to the Send API, just use your predefined template.

Finally, Template API can leverage templates created with Passport, our free responsive email template builder - https://www.mailjet.com/feature/passport/

Reference

Basic syntax

Delimitators

The delimitators are :

Operators

Arithmetic Operators :

Comparison Operators :

Logical operators :

Variables

Four sources of variables are on offer in the templating languages. They can be used for simple insertion with the {{ ... }} or with operators, functions and control structures.

Vars and Custom Vars

package MyClass;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.errors.MailjetClient;
import com.mailjet.client.errors.MailjetRequest;
import com.mailjet.client.errors.MailjetResponse;
import com.mailjet.client.resource.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends an email to one recipient.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
            .property(Email.TEXTPART, "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}")
            .property(Email.HTMLPART, "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}")
                        .property(Email.MJTEMPLATELANGUAGE, true)
            .put(Email.VARS, new JSONObject().put("Day", "Monday"))
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")
                    .put("Vars", new JSONObject().put("Day", "Tuesday"))))
                .put(new JSONObject()
                    .put("Email", "passenger2@mailjet.com"))
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'MJ-TemplateLanguage' => true,
    'Text-part' => 'Dear passenger, welcome to Mailjet! On this {{var:day:"monday"}}, may the delivery force be with you! {{var:personalmessage:""}}'
    'Html-part' => '<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:"monday"}}, may the delivery force be with you! {{var:personalmessage:""}}',
    'Recipients' => [
      ['Email' => 'passenger2@mailjet.com', 'Name' => 'Passenger 2'],
      ['Email' => 'passenger@mailjet.com', 'Name' => 'passenger 1',
        'Vars' => ['day' => 'Tuesday', 'Personalmessage' => 'Happy Birthday!']]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends an email to the given recipient with vars and custom vars.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateLanguage":true,
        "Text-part":"Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
        "Vars":{
                "day": "Monday"
        },
        "Recipients":[
                {
                        "Email": "passenger1@mailjet.com",
                        "Name": "passenger 1",
                        "Vars": {
                                "day": "Tuesday",
                                "personalmessage": "Happy birthday!"
                        }
                },
                {
                        "Email": "passenger2@mailjet.com",
                        "Name": "passenger 2"
                }
        ]
    }'
/**
 *
 * This calls sends an email to the given recipient with vars and custom vars.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateLanguage":"true",
        "Text-part":"Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
        "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
        "Vars":{
                "day": "Monday"
        },
        "Recipients":[
                {
                        "Email": "passenger1@mailjet.com",
                        "Name": "passenger 1",
                        "Vars": {
                                "day": "Tuesday",
                                "personalmessage": "Happy birthday!"
                        }
                },
                {
                        "Email": "passenger2@mailjet.com",
                        "Name": "passenger 2"
                }
        ]
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })
# This calls sends an email to the given recipient with vars and custom vars.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: "pilot@mailjet.com",
  from_name: "Mailjet Pilot",
  subject: "Your email flight plan!",
  "Mj-TemplateLanguage": true,
  text_part: "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
  html_part: "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
  vars: {'day' => 'Monday'},
  recipients: [
    {'Email' => 'passenger1@mailjet.com', 'Name' => 'passenger 1',
      'Vars' => {'day' => 'Tuesday', 'personalmessage' => 'Happy birthday!'}},
    {'Email' => 'passenger2@mailjet.com', 'Name' => 'passenger 2'}]
)
"""
This calls sends an email to the given recipient with vars and custom vars.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'MJ-TemplateLanguage': 'true',
  'Text-part': 'Dear passenger, welcome to Mailjet! On this {{var:day:"monday"}}, may the delivery force be with you! {{var:personalmessage:""}}',
  'Html-part': '<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:"monday"}}, may the delivery force be with you! {{var:personalmessage:""}}',
  'Vars': {
                "day": "Monday"
        },
  'Recipients': [
                {
                        "Email": "passenger1@mailjet.com",
                        "Name": "passenger 1",
                        "Vars": {
                                "day": "Tuesday",
                                "personalmessage": "Happy birthday!"
                        }
                },
                {
                        "Email": "passenger2@mailjet.com",
                        "Name": "passenger 2"
                }
        ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
/*
This calls sends an email to the given recipient with vars and custom vars.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
type  MyVarsStruct  struct {
  Day  string
}
type MyRecipientsVarsStruct struct {
  Day               string
  Personalmessage   string
}
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      MJTemplateLanguage: "true",
    TextPart: "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
    HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
      Vars: MyVarsStruct {
        Day: "Monday",
      },
      Recipients: []Recipient {
        Recipient {
          Email: "passenger1@mailjet.com",
          Name: "passenger 1",
          Vars: MyRecipientsVarsStruct {
            Day: "Tuesday",
            Personalmessage: "Happy birthday!",
          },
        },
        Recipient {
          Email: "passenger2@mailjet.com",
          Name: "passenger 2",
        },
      },
    },
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

You can use the Send API vars and custom vars to push contact specific information to be inserted in the template. This information will not be persistent in Mailjet system and will only be used for the current Send API call. To have persistent properties for a contact, please refer to the next section about ContactData.

You can then use the syntax {{var:namevar:defaultvalue}} to print the value of the property in your template.

ContactData

In your templates, you can use your contact properties. See the personalisation guide to learn how to setup and add your own contact properties.

You can then use the syntax {{data:namedata:defaultvalue}} to print the value in your template.

Predefined variables

The predefined variables are useful to access information related to the sender, the recipient and the template. They also allow you to access URLs related to your message.

Segmentation

<html><body>
{% if segment:nameSegment %}
    <h1>Segment nameSegment is true for the recipient</h1>
{% endif %}
</body></html>

Html result

<html><body>
</body></html>

The segmentation formulas, you create with /contactfilter as described in the Newsletter Segmentation section, can be used in the template. It helps to easily mutualise your newsletter logic and Send API template logic.

You can use either the Name or ID of the /contactfilter in the syntax {{segment:nameORid}} to print the value in your template.

The segmentation variables are also available in condition statement but can’t be used and combined with logical operators (AND, OR, NOT, etc).

Functions

Behavior of the contact :

String modification :

Mathematical function :

Encoding/ Formating :

Conditional Statements

<html><body>
{% if data:age > 45 %}
<ul>
    <li>{{data:age}}</li>
</ul>
{% endif %}
</body></html>

Html result

<html><body>
<ul>
    <li>46</li>
</ul>
</body></html>

or

<html><body>
</body></html>

Multiple branches if statement:

{% if data:age >= 21 %}
    You can code, drink and vote!
{% elseif data:age >= 18 %}
    You can't drink but hey, you still can code and vote!
{% else %}
    A few more years to wait !!!
{% endif %}

if,else,elseif and endif allow you to insert conditional display of information in your template.

The if statements can be nested inside one another.

The conditional statement allows the usage of a default value for your variables. This can be helpful if you are not always passing all the variables in your Send API call.

You can specify a default value with the usual format var:name:default_value.

The behavior of the conditional statement will be as follow:

Var “test” defined
and with true value
Var “test” defined
and with false value
Var “test” not defined
{% if var:test %}
YES
{% else %}
NO
{% endif %}
YES NO !TEMPLATE ERROR!
{% if var:test:true %}
YES
{% else %}
NO
{% endif %}
YES NO YES
{% if var:test:false %}
YES
{% else %}
NO
{% endif %}
YES NO NO
{{var:test:“N/A”}} true false N/A
{{var:test}} true false !TEMPLATE ERROR!

Set function

Printing value

Hello {% set yo-yo = "Benjamin" %} {{ yo-yo }} !
Hello Benjamin!

You can change the value of the variable anytime.

Hello {% set yo-yo = "Benjamin" %} {{ yo-yo }}, how is {% set yo-yo = "Jane" %} {{ yo-yo }} ?
Hello Benjamin, how is Jane ?

In conditional statement

Hello {% set yo-yo = 1 %}{% if yo-yo >= 1 %} Benjamin {% endif %} !
Hello Benjamin!

You can use the set function to assign value to a variable, directly in the template. You can then print the value or use it in conditional statements.

You can set values as string, integer, float, boolean, variable or contact data.

Loop Statements

JSON payload

{
...
"Vars":{"x":[1, true, "Pilot"]}
...
}

or

{
...
"Vars":{"x":{"test1":1, "test2":true,"test3":"Pilot"}}
...
}

Template

<html><body>
<ul>
{% for value in var:x %}
    <li>{{value}}</li>
{% endfor %}
</ul>
</body></html>

Html result

<html><body>
<ul>
    <li>1</li>
    <li>true</li>
    <li>Pilot</li>
</ul>
</body></html>

for in and endfor allows to insert an iteration on a JSON object or array in your template.

The syntax is:

{% for variable-name in json-source %}
html or/and nested statement
{% endfor %}

On each iteration, the value of the current element from json-source is assigned to variable-name. variable-name can be used for display ( ie {{ variable-name }} ) or inside a nested statement.

Multidimensional array

{
...
"Vars":{ "rows" :[
        {   
            "title":"title1", 
            "bodies":["1","2","3","4"]
        },
        {   
            "title":"title2", 
            "bodies":["5","6"]
        }] 
    }
...
} 

Template

Hello 
    {% for row in var:rows %}loop1:{{ row.title }}
        {% for body in row.bodies %}loop2:{{ body }} {% endfor %}
    {% endfor %}

Html result

Hello loop1:title1 loop2:1 loop2:2 loop2:3 loop2:4 loop1:title2 loop2:5 loop2:6

Multiple array

{
...
"Vars":{ 
    "array1":["1", "2"] , 
    "array2":["3", "4"]
    }
...
} 

Template

Hello 
{% for x3 in var:array1 %} loop1:{{ x3 }}
    {% for x4 in var:array2 %} loop2:{{ x4 }}{% endfor %}
{% endfor %}

Html result

Hello  loop1:1 loop2:3 loop2:4 loop1:2 loop2:3 loop2:4

The for statements can be nested inside one another. It allows to intersect multiple arrays or objects and manage multidimensional array.

Mailjet templating language support multidimensional json structure:

{
...
"Vars":{ 
    "x":{"test": 2, "test2": { "test3": "Hello" } }
    }
...
} 

Template

{{ var:x.test }} {{ var:x.test2.test3 }}

Html result

2 Hello

Storing a template

Instead of providing the template code in each Send API call, you can also store it using the /template API resource and re-use it at will in Send API. These templates can be edited directly in Passport, our WYSIWYG template editor.

Creating the template

<?php
/*
Create : 
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Name' => "First Template"
];
$response = $mj->post(Resources::$Template, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : 
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/template \
    -H 'Content-Type: application/json' \
    -d '{
        "Name":"First Template"
    }'
/**
 *
 * Create : 
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("template")
    .request({
        "Name":"First Template"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : 
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Template.create(name: "First Template")
"""
Create : 
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Name': 'First Template'
}
result = mailjet.template.create(data=data)
print result.status_code
print result.json()
/*
Create : 
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Template
    mr := &Request{
      Resource: "template",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Template {
      Name: "First Template",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * Create : 
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Template.resource)
                        .property(Template.NAME, "First Template");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

API response:

{
    "Count": 1,
    "Data": [
        {
            "Author": "",
            "Categories": "",
            "Copyright": "",
            "Description": "",
            "EditMode": "",
            "ID": "",
            "IsStarred": "false",
            "Name": "First Template",
            "OwnerId": "5",
            "OwnerType": "",
            "Presets": "",
            "Previews": "",
            "Purposes": ""
        }
    ],
    "Total": 1
}

The /template resource allows to store your template on the Mailjet system.

To create a template, POST on the /template resource specifying a name.

You can them reuse the template at will for your messages by referencing the ID returned when created.

Adding a content

<?php
/*
Create : Template content
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Html-part' => "<html><body><p>Hello {{var:name}}</p></body></html>",
    'Text-part' => "Hello {{var:name}}"
];
$response = $mj->post(Resources::$TemplateDetailcontent, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : Template content
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/template/$ID_TEMPLATE/detailcontent \
    -H 'Content-Type: application/json' \
    -d '{
        "Html-part":"<html><body><p>Hello {{var:name}}</p></body></html>",
        "Text-part":"Hello {{var:name}}"
    }'
/**
 *
 * Create : Template content
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("template")
    .id($ID_TEMPLATE)
    .action("detailcontent")
    .request({
        "Html-part":"<html><body><p>Hello {{var:name}}</p></body></html>",
        "Text-part":"Hello {{var:name}}"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : Template content
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Template_detailcontent.create(id: $ID_TEMPLATE, , html_part: "<html><body><p>Hello {{var:name}}</p></body></html>",text_part: "Hello {{var:name}}")
"""
Create : Template content
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$ID_TEMPLATE'
data = {
  'Html-part': '<html><body><p>Hello {{var:name}}</p></body></html>',
  'Text-part': 'Hello {{var:name}}'
}
result = mailjet.template_detailcontent.create(id=id, data=data)
print result.status_code
print result.json()
/*
Create : Template content
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.TemplateDetailcontent
    mr := &Request{
      Resource: "template",
      ID: RESOURCE_ID,
      Action: "detailcontent",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.TemplateDetailcontent {
    HtmlPart: "<html><body><p>Hello {{var:name}}</p></body></html>",
    TextPart: "Hello {{var:name}}",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.TemplateDetailcontent;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : Template content
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(TemplateDetailcontent.resource, ID)
                        .property(TemplateDetailcontent.HTMLPART, "<html><body><p>Hello {{var:name}}</p></body></html>")
                        .property(TemplateDetailcontent.TEXTPART, "Hello {{var:name}}");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

Now that you have created a template, you can add the content, which can be Text or Html (Text-part or Html-part). To do so, you can perform a PUT or POST request on the /template/$ID/detailcontent resource. With a POST, if you only give a value to Html-part or Text-part, the other one will be set to empty. While with a PUT, if you only give a value to Html-part or Text-part, the other one keeps its previous value.

Leveraging Template Headers

The /template/$ID/detailcontent resource allow to store a headers property. You can store in this property a JSON object containing default value for some standard SMTP header or Send API properties.

When using a template in Send API, the processing of the message will take as default the value from the headers property. It will allow you to call Send API without repeating in each API call the same information. If you specify one of those information in your Send API call, you will overwrite the default values of the template.

JSON Sample of headers

{
"From":"\"Mailjet pilot\" <pilot@mailjet.com>",
"Subject":"Welcome",
"Reply-to":"copilot@mailjet.com"
}
Template headers property Send API property Description
From FromName and FromEmail Sender name and email address
john@example.com or <john@example.com> or "John Doe" <john@example.com>
Subject Subject Message subject (support template language)
Reply-To Reply-To property of Headers object Email address that should be used to reply to the message

Templates generated with Passport for transactional will also support the default values listed above.

Use the Template in Send API

The templates and templating languages can be used in multiple ways with Send API:

Send a stored template

package MyClass;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.errors.MailjetClient;
import com.mailjet.client.errors.MailjetRequest;
import com.mailjet.client.errors.MailjetResponse;
import com.mailjet.client.resource.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends a message based on a template.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.MJTEMPLATEID, 1)
                        .property(Email.MJTEMPLATELANGUAGE, true)
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.RECIPIENTS, new JSONArray()
                .put(new JSONObject()
                    .put("Email", "passenger@mailjet.com")))
                        .property(Email.MJEVENTPAYLOAD, "Eticket,1234,row,15,seat,B");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
/*
This calls sends a message based on a template.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'MJ-TemplateID' => 1,
    'MJ-TemplateLanguage' => true,
    'Recipients' => [['Email' => "passenger@mailjet.com"]]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends a message based on a template.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateID":"1",
        "MJ-TemplateLanguage":true,
        "Recipients":[
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
    }'
/**
 *
 * This calls sends a message based on a template.
 *
 */
var mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
var request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateID":"1",
        "MJ-TemplateLanguage":"true",
        "Recipients":[
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
    });
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })
# This calls sends a message based on a template.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: "pilot@mailjet.com",
  from_name: "Mailjet Pilot",
  subject: "Your email flight plan!",
  "Mj-TemplateID": "1",
  "Mj-TemplateLanguage": true,
  recipients: [{ 'Email'=> 'passenger@mailjet.com'}]
)
"""
This calls sends a message based on a template.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'MJ-TemplateID': '1',
  'MJ-TemplateLanguage': 'true',
  'Recipients': [
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
/*
This calls sends a message based on a template.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      MJTemplateID: 1,
      MJTemplateLanguage: "true",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
    },
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}

Use the Mj-TemplateID property in your Send API payload to specify the ID of the the template you created.

You must set the Mj-TemplateLanguage property in the payload at true to have the templating language interpreted.

Send a message containing template language

You can pass in the payload of the call to Send API, the usual Text-Part and Html-Part containing the templating language.

Refer to the Send API guide for more information.

Using Passport Templates

<?php
/*
View : Find your personal templates
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'OwnerType' => 'user',
  'Limit' => '100'
];
$response = $mj->get(Resources::$Template, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : Find your personal templates
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/template?OwnerType=user\&Limit=100 
/**
 *
 * View : Find your personal templates
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("template")
    .request({
        "OwnerType":"user",
        "Limit":"100"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# View : Find your personal templates
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Template.all(owner_type: "user",limit: "100")
"""
View : Find your personal templates
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'OwnerType': 'user',
  'Limit': '100'
}
result = mailjet.template.get(filters=filters)
print result.status_code
print result.json()
/*
View : Find your personal templates
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Template
    _, _, err := mailjetClient.List("template", &data, Filter("OwnerType", "user"), Filter("Limit", "100"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * View : Find your personal templates
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Template.resource)
                  .filter(Template.OWNERTYPE, "user")
                  .filter(Template.LIMIT, "100");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
<?php
/*
View : Find your templates, created in Passport
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$filters = [
  'EditMode' => 'tool',
  'Limit' => '100',
  'OwnerType' => 'user'
];
$response = $mj->get(Resources::$Template, ['filters' => $filters]);
$response->success() && var_dump($response->getData());
?>
# View : Find your templates, created in Passport
curl -s \
    -X GET \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/template?EditMode=tool\&Limit=100\&OwnerType=user 
/**
 *
 * View : Find your templates, created in Passport
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .get("template")
    .request({
        "EditMode":"tool",
        "Limit":"100",
        "OwnerType":"user"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
"""
View : Find your templates, created in Passport
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
filters = {
  'EditMode': 'tool',
  'Limit': '100',
  'OwnerType': 'user'
}
result = mailjet.template.get(filters=filters)
print result.status_code
print result.json()
# View : Find your templates, created in Passport
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Template.all(edit_mode: "tool",limit: "100",owner_type: "user")
/*
View : Find your templates, created in Passport
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Template
    _, _, err := mailjetClient.List("template", &data, Filter("EditMode", "tool"), Filter("Limit", "100"), Filter("OwnerType", "user"))
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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 {
    /**
     * View : Find your templates, created in Passport
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Template.resource)
                  .filter(Template.EDITMODE, "tool")
                  .filter(Template.LIMIT, "100")
                  .filter(Template.OWNERTYPE, "user");
      response = client.get(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

When using Passport, you have the option to save your work as a template. Next step will be to preview the template and see how it will look like on different devices - mobile phone, tablet and desktop. You can send a test as well to see how the variables will be printed. On the last step, you will see code sample which can be directly used in your system, after specifying the variables.

You can find your templates with a GET on the /template resource then you can use them using the same Send API call as templates created with the API.

Templates error management

<?php
/*
This calls sends a message to a recipient and an template error email.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'FromEmail' => "pilot@mailjet.com",
    'FromName' => "Mailjet Pilot",
    'Subject' => "Your email flight plan!",
    'MJ-TemplateID' => "1",
    'MJ-TemplateLanguage' => true,
    'MJ-TemplateErrorReporting' => "air-traffic-control@mailjet.com",
    'MJ-TemplateErrorDeliver' => "deliver",
    'Recipients' => [
        [
            'Email' => "passenger@mailjet.com"
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends a message to a recipient and an template error email.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/send \
    -H 'Content-Type: application/json' \
    -d '{
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateID":"1",
        "MJ-TemplateLanguage":true,
        "MJ-TemplateErrorReporting":"air-traffic-control@mailjet.com",
        "MJ-TemplateErrorDeliver":"deliver",
        "Recipients":[
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
    }'
/**
 *
 * This calls sends a message to a recipient and an template error email.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send")
    .request({
        "FromEmail":"pilot@mailjet.com",
        "FromName":"Mailjet Pilot",
        "Subject":"Your email flight plan!",
        "MJ-TemplateID":"1",
        "Mj-TemplateLanguage":"true",
        "MJ-TemplateErrorReporting":"air-traffic-control@mailjet.com",
        "MJ-TemplateErrorDeliver":"deliver",
        "Recipients":[
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
    })
request
  .then(result => {
    console.log(result.body)
    })
  .catch(error => {
    console.log(error.statusCode)
    })
# This calls sends a message to a recipient and an template error email.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Send.create(
  from_email: "pilot@mailjet.com",
  from_name: "Mailjet Pilot",
  subject: "Your email flight plan!",
  "Mj-TemplateID": "1",
  "Mj-TemplateLanguage": true,
  "Mj-TemplateErrorReporting": "air-traffic-control@mailjet.com",
  "Mj-TemplateErrorDeliver": "deliver",
  recipients: [{ 'Email'=> 'passenger@mailjet.com'}]
)
"""
This calls sends a message to a recipient and an template error email.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'FromEmail': 'pilot@mailjet.com',
  'FromName': 'Mailjet Pilot',
  'Subject': 'Your email flight plan!',
  'MJ-TemplateID': '1',
  'MJ-TemplateLanguage': 'true',
  'MJ-TemplateErrorReporting': 'air-traffic-control@mailjet.com',
  'MJ-TemplateErrorDeliver': 'deliver',
  'Recipients': [
                {
                        "Email": "passenger@mailjet.com"
                }
        ]
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
/*
This calls sends a message to a recipient and an template error email.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    email := &InfoSendMail {
      FromEmail: "pilot@mailjet.com",
      FromName: "Mailjet Pilot",
      Subject: "Your email flight plan!",
      MJTemplateID: 1,
      MJTemplateLanguage: "true",
      MJTemplateErrorReporting: "air-traffic-control@mailjet.com",
      MJTemplateErrorDeliver: "deliver",
      Recipients: []Recipient {
        Recipient {
          Email: "passenger@mailjet.com",
        },
      },
    },
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}
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.Email;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This calls sends a message to a recipient and an template error email.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Email.resource)
                        .property(Email.FROMEMAIL, "pilot@mailjet.com")
                        .property(Email.FROMNAME, "Mailjet Pilot")
                        .property(Email.SUBJECT, "Your email flight plan!")
                        .property(Email.MJTEMPLATEID, "1")
                        .property(Email.MJTEMPLATELANGUAGE, true)
                        .property(Email.MJTEMPLATEERRORREPORTING, "air-traffic-control@mailjet.com")
                        .property(Email.MJTEMPLATEERRORDELIVER, "deliver")
                        .property(Email.RECIPIENTS, new JSONArray()
                                                                .put(new JSONObject()
                                                                    .put("Email", "passenger@mailjet.com")));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

Send API offers two payload properties to allow error management:

By default, the delivery of a message in error to the recipient is turned off.

If an error occurs when the template error reporting is enabled, a message from templating-language-error@mailjet.com with subject Error while evaluating Mailjet Templating language for message "original subject" will be delivered to the given error reporting address. It will contain the error message in the body and an attachement, containing the source of the original message (base64 encoded).

Common templating errors:

Step by step guide

This guide will show you how to quickly be up and running with your first transactional template. This guide leverage Mailjet’s responsive mail builder (Passport) which helps you design your emails easily.

At the end of this guide you will have a flexible e-commerce template, which will cover different types of actions - order confirmation (including list of purchased products), out of stock notice, refund request.

OK, let’s go!

In this section, we can actually start designing our own template. You can use templating language as a text, directly added in the template, or you can add it using the button “Template language” which is under the Advanced mode of the builder. You drag and drop the block on the preferred position in the template.

insert-templ-lang.png

In order to add templating language inside the block, you double click and enter the code on the left hand side of the builder.

You can personalize the name for the recipient using the contact data.

Dear {{data:firstname:”customer”}}

Of course, we would like our message to vary, depending on the the purpose of the message. We can achieve this by leveraging the conditional statements.

{% if var:step == "confirmorder" %}
    Confirmation of purchase: {{ var:productname:"" }} 

{% elseif var:step == "unavailable" %} 
    Sorry, {{ var:productname:""}} is out of stock :( If you would like a refund, 
    please<a href = "http://mailjet.com/">contact us</a>. 

{% elseif var:step == "refund" %}
    Refund of your purchase {{ var:productname:"" }} has been issued. The amount of 
    {{var:totalprice}} will be returned to your credit card within 10 business days. 

{% endif %}

/images/inside_if.png

But your clients can order N products, how to handle this? Well, let’s use loop structure for that! You can iterate on all the purchased products in order to display them in the template using smart loops.

{% if var:step == "refund" or var:step == "confirmorder" %}
{% for purchase in var:product %}
<ul>PRODUCT TYPE:</ul><li>{{purchase.name}}</li>
<ul>PRODUCT DESCRIPTION:</ul>{{purchase.description}}
{% endfor %}
- Make table with 4 columns in our responsive template builder with column names - Name, Number, Price, Total price. You will print the values nested in the product variable in the 
respective column.
{% for purchase in var:product %}
{{purchase.name}}
{{purchase.number}}
{{purchase.price}}
{{purchase.totalprice}}
{% endfor %}
{% endif %}

/images/productlist.png

When confirming order, we need to show the customer additional details about the order. We can add another table and print inside the information about the order, stored in the variable order.

{% if var:step == "confirmorder" %}
{{var:totalprice:"Default value"}}
{{var:order_date:"Default value"}}
{{var:order_id:"Default value"}}
{% endif %}

/images/orderdetails.png

And here is what our final resuts will look like!

Confirm order:


# API call to send order confirmation
"Vars":
{
"products":[
        {"name":"T-shirt",
        "number":2,
        "price":"$20.00",
        "totalprice":"$40.00",
        "link":"https://s-media-cache-ak0.pinimg.com/736x/25/cf/c1/25cfc1d2d5239d2c37eebdd354d9a285.jpg",
        "description":"<li>Funny T-shirt for coders<\/li> <li>100% cotton<\/li> <li>Machine washable</li>"
        },
        {
        "name":"T-shirt",
        "number":1,
        "price":"$20.00",
        "totalprice":"$20.00",
        "link":"http://rlv.zcache.com/keep_calm_and_code_on_t_shirt_programming_nerd-r7592d3683abe4438863f9192f03bd467_804gy_512.jpg",
        "description":" <li>  Standard fit</li> <li> Fits true to size</li> <li> 5.4 oz. 100% cotton</li> <li>   1x1 rib knit collar and shoulder-to-shoulder taping</li> <li>  Double-needle hem</li>   <li> Imported</li> <li>Machine wash cold</li>"
        }
            ],
"vat":"$12.00",
"totalprice":"$72.00",
"firstname":"Mr. Awesome",
"step":"confirmorder",
"order_date":"10-01-2016",
"order_id":"423482",
"productname":"T-shirt"
}

/images/full.png

Out of stock:

# API call for out of stock item

"Vars":
{
"products":[
        {"name":"T-shirt",
        "number":2,
        "price":"$20.00",
        "totalprice":"$40.00",
        "link":"https://s-media-cache-ak0.pinimg.com/736x/25/cf/c1/25cfc1d2d5239d2c37eebdd354d9a285.jpg",
        "description":"<li>Funny T-shirt for coders<\/li> <li>100% cotton<\/li> <li>Machine washable</li>"
        },
        {
        "name":"T-shirt",
        "number":1,
        "price":"$20.00",
        "totalprice":"$20.00",
        "link":"http://rlv.zcache.com/keep_calm_and_code_on_t_shirt_programming_nerd-r7592d3683abe4438863f9192f03bd467_804gy_512.jpg",
        "description":" <li>  Standard fit</li> <li> Fits true to size</li> <li> 5.4 oz. 100% cotton</li> <li>   1x1 rib knit collar and shoulder-to-shoulder taping</li> <li>  Double-needle hem</li>   <li> Imported</li> <li>Machine wash cold</li>"
        }
            ],
"vat":"$12.00",
"totalprice":"$72.00",
"firstname":"Mr. Awesome",
"step":"unavailable",
"order_date":"10-01-2016",
"order_id":"423482",
"productname":"T-shirt"
}

/images/unavailable.png

Refund:


# API call to send refund request

"Vars":
{
"products":[
        {"name":"T-shirt",
        "number":2,
        "price":"$20.00",
        "totalprice":"$40.00",
        "link":"https://s-media-cache-ak0.pinimg.com/736x/25/cf/c1/25cfc1d2d5239d2c37eebdd354d9a285.jpg",
        "description":"<li>Funny T-shirt for coders<\/li> <li>100% cotton<\/li> <li>Machine washable</li>"
        },
        {
        "name":"T-shirt",
        "number":1,
        "price":"$20.00",
        "totalprice":"$20.00",
        "link":"http://rlv.zcache.com/keep_calm_and_code_on_t_shirt_programming_nerd-r7592d3683abe4438863f9192f03bd467_804gy_512.jpg",
        "description":" <li>  Standard fit</li> <li> Fits true to size</li> <li> 5.4 oz. 100% cotton</li> <li>   1x1 rib knit collar and shoulder-to-shoulder taping</li> <li>  Double-needle hem</li>   <li> Imported</li> <li>Machine wash cold</li>"
        }
            ],
"vat":"$12.00",
"totalprice":"$72.00",
"firstname":"Mr. Awesome",
"step":"refund",
"order_date":"10-01-2016",
"order_id":"423482",
"productname":"T-shirt"
}

/images/refund.png

Github Demos

You can find some use case samples on Github

Send marketing campaigns

To send your first newsletter, you need to have at least one active sender address in the Sender domains & addresses section.

You will need to create contacts and organize them into lists. To do so, you have two options : use the interface or the API.

Create a contact list

<?php
/*
Create : only need a Name
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Name' => "myList"
];
$response = $mj->post(Resources::$Contactslist, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : only need a Name
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contactslist \
    -H 'Content-Type: application/json' \
    -d '{
        "Name":"myList"
    }'
/**
 *
 * Create : only need a Name
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("contactslist")
    .request({
        "Name":"myList"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : only need a Name
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contactslist.create(name: "myList")
/*
Create : only need a Name
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contactslist
    mr := &Request{
      Resource: "contactslist",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Contactslist {
      Name: "myList",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
"""
Create : only need a Name
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Name': 'myList'
}
result = mailjet.contactslist.create(data=data)
print result.status_code
print result.json()
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.Contactslist;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : only need a Name
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contactslist.resource)
                        .property(Contactslist.NAME, "myList");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

API response:

{
    "Count": 1,
    "Data": [
        {
            "Address": "",
            "CreatedAt": "",
            "ID": "",
            "IsDeleted": "false",
            "Name": "myList",
            "SubscriberCount": ""
        }
    ],
    "Total": 1
}

You can create your contacts list by performing a simple POST request on the /contactslist resource with only one mandatory field : its name.

The Name will be a unique identifier for your list.

Manage contacts

Create a contact

<?php
/*
Create : Manage the details of a Contact.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Email' => "Mister@mailjet.com"
];
$response = $mj->post(Resources::$Contact, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : Manage the details of a Contact.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact \
    -H 'Content-Type: application/json' \
    -d '{
        "Email":"Mister@mailjet.com"
    }'
/**
 *
 * Create : Manage the details of a Contact.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("contact")
    .request({
        "Email":"Mister@mailjet.com"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : Manage the details of a Contact.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact.create(email: "Mister@mailjet.com")
"""
Create : Manage the details of a Contact.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Email': 'Mister@mailjet.com'
}
result = mailjet.contact.create(data=data)
print result.status_code
print result.json()
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 {
    /**
     * Create : Manage the details of a Contact.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contact.resource)
                        .property(Contact.EMAIL, "Mister@mailjet.com");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}
/*
Create : Manage the details of a Contact.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contact
    mr := &Request{
      Resource: "contact",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Contact {
      Email: "Mister@mailjet.com",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}

API response:

{
    "Count": 1,
    "Data": [
        {
            "CreatedAt": "",
            "DeliveredCount": "",
            "Email": "Mister@mailjet.com",
            "ExclusionFromCampaignsUpdatedAt": "",
            "ID": "",
            "IsExcludedFromCampaigns": "false",
            "IsOptInPending": "false",
            "IsSpamComplaining": "false",
            "LastActivityAt": "",
            "LastUpdateAt": "",
            "Name": "MisterMailjet",
            "UnsubscribedAt": "",
            "UnsubscribedBy": ""
        }
    ],
    "Total": 1
}

To create some contacts which will be the recipients, you need to specify an email address with POST on the /contact resource.

The email address will be a unique identifier of your contact in the Mailjet System.

Personalisation : add contact properties

The /contact resource allows you to create contacts using their email addresses and names. If you want to add more granular details about your contacts, Mailjet provides the capability to add custom data to contacts.

The addition of custom data starts with the definition of the extra information to store with the contacts (It could be for example the country the contacts live in, how old the contacts are, their current income, the value of their purchases on your site…) and how this data will be stored (string, number, boolean…).

Defining custom Contact data

<?php
/*
Create : Definition of available extra data items for contacts.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Datatype' => "str",
    'Name' => "Age",
    'NameSpace' => "static"
];
$response = $mj->post(Resources::$Contactmetadata, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : Definition of available extra data items for contacts.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contactmetadata \
    -H 'Content-Type: application/json' \
    -d '{
        "Datatype":"str",
        "Name":"Age",
        "NameSpace":"static"
    }'
/**
 *
 * Create : Definition of available extra data items for contacts.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("contactmetadata")
    .request({
        "Datatype":"str",
        "Name":"Age",
        "NameSpace":"static"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : Definition of available extra data items for contacts.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contactmetadata.create(datatype: "str",name: "Age",name_space: "static")
"""
Create : Definition of available extra data items for contacts.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Datatype': 'str',
  'Name': 'Age',
  'NameSpace': 'static'
}
result = mailjet.contactmetadata.create(data=data)
print result.status_code
print result.json()
/*
Create : Definition of available extra data items for contacts.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contactmetadata
    mr := &Request{
      Resource: "contactmetadata",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Contactmetadata {
      Datatype: "str",
      Name: "Age",
      NameSpace: "static",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.Contactmetadata;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : Definition of available extra data items for contacts.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contactmetadata.resource)
                        .property(Contactmetadata.DATATYPE, "str")
                        .property(Contactmetadata.NAME, "Age")
                        .property(Contactmetadata.NAMESPACE, "static");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

API response:

{
    "Count": 1,
    "Data": [
        {
            "Datatype": "str",
            "ID": "",
            "Name": "Age",
            "NameSpace": "static"
        }
    ],
    "Total": 1
}

To define custom contact data, perform a POST on /contactmetadata with the following properties:

For example, to store the age of each contacts, a static int “Age” property can be added to the metadata.

A static data stores only one value per DataType. It could store for example a firstname, a lastname, a country, a language …
A historic data stores a timestamped history of the value of this data. It could be used for example to store the value of each purchases over the history of the contact.

These 2 Namespaces have their own resources for viewing, creating and editing: /contactdata and /contacthistorydata

The contact datas will be available for personalisation of your message content and for segmentation of your lists.

Adding custom static Contact data

<?php
/*
Modify : Modify the static custom contact data
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Data' => [
        [
            'Name' => "Age",
            'value' => 30
        ],
        [
            'Name' => "Country",
            'value' => "US"
        ]
    ]
];
$response = $mj->put(Resources::$Contactdata, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
/**
 *
 * Modify : Modify the static custom contact data
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .put("contactdata")
    .id($CONTACT_ID)
    .request({
        "Data":[
                {
                        "Name": "Age",
                        "value": 30
                },
                {
                        "Name": "Country",
                        "value": "US"
                }
        ]
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Modify : Modify the static custom contact data
curl -s \
    -X PUT \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contactdata/$CONTACT_ID \
    -H 'Content-Type: application/json' \
    -d '{
        "Data":[
                {
                        "Name": "Age",
                        "value": 30
                },
                {
                        "Name": "Country",
                        "value": "US"
                }
        ]
    }'
# Modify : Modify the static custom contact data
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
target = Mailjet::Contactdata.find($CONTACT_ID)
target.update_attributes(data: [{ 'Name'=> 'Age', 'value'=> 30}, { 'Name'=> 'Country', 'value'=> 'US'}])
"""
Modify : Modify the static custom contact data
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$CONTACT_ID'
data = {
  'Data': [
                {
                        "Name": "Age",
                        "value": 30
                },
                {
                        "Name": "Country",
                        "value": "US"
                }
        ]
}
result = mailjet.contactdata.update(id=id, data=data)
print result.status_code
print result.json()
/*
Modify : Modify the static custom contact data
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    mr := &Request{
      Resource: "contactdata",
      ID: RESOURCE_ID,
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Contactdata {
      Data: []MailjetDat {
        MailjetDat {
          Name: "Age",
          Value: 30,
        },
        MailjetDat {
          Name: "Country",
          Value: "US",
        },
      },
    },
    }
    err := mailjetClient.Put(fmr)
    if err != nil {
      fmt.Println(err)
    }
}
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, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      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());
    }
}

By Performing a PUT (acting like a PATCH, your other static datas will not be lost) on /contactdata, you can add values for several metadata at once.

Adding custom historic Contact data

# Create : This resource can be used to add historical data to contact.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contacthistorydata \
    -H 'Content-Type: application/json' \
    -d '{
        "ContactID":"$CONTACT_ID",
        "Data":"10",
        "Name":"Purchase"
    }'
<?php
/*
Create : This resource can be used to add historical data to contact.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'ContactID' => "$CONTACT_ID",
    'Data' => 10,
    'Name' => "Purchase"
];
$response = $mj->post(Resources::$Contacthistorydata, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
/**
 *
 * Create : This resource can be used to add historical data to contact.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("contacthistorydata")
    .request({
        "ContactID":"$CONTACT_ID",
        "Data":"10",
        "Name":"Purchase"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : This resource can be used to add historical data to contact.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contacthistorydata.create(contact_id: "$CONTACT_ID",data: "10",name: "Purchase")
"""
Create : This resource can be used to add historical data to contact.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'ContactID': '$CONTACT_ID',
  'Data': '10',
  'Name': 'Purchase'
}
result = mailjet.contacthistorydata.create(data=data)
print result.status_code
print result.json()
/*
Create : This resource can be used to add historical data to contact.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Contacthistorydata
    mr := &Request{
      Resource: "contacthistorydata",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Contacthistorydata {
      ContactID: "$CONTACT_ID",
      Data: 10,
      Name: "Purchase",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.Contacthistorydata;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : This resource can be used to add historical data to contact.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Contacthistorydata.resource)
                        .property(Contacthistorydata.CONTACTID, "$CONTACT_ID")
                        .property(Contacthistorydata.DATA, "10")
                        .property(Contacthistorydata.NAME, "Purchase");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

By Performing a POST on /contacthistorydata, you can add a new value for a historic metadata.

This historic metadata will be available for segmentation with dedicated functions like Avg,Min,Max

Creating contacts with Contact data

<?php
/*
Create : Manage the details of a Contact.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Contacts' => [
        [
            'Email' => "jimsmith@example.com",
            'Name' => "Jim",
            'Properties' => [
                'Property1' => "value",
                'Property2' => "value2"
            ]
        ],
        [
            'Email' => "janetdoe@example.com",
            'Name' => "Janet",
            'Properties' => [
                'Property1' => "value",
                'Property2' => "value2"
            ]
        ]
    ]
];
$response = $mj->post(Resources::$ContactManagemanycontacts, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : Manage the details of a Contact.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact/managemanycontacts \
    -H 'Content-Type: application/json' \
    -d '{
        "Contacts":[
                {
                        "Email": "jimsmith@example.com",
                        "Name": "Jim",
                        "Properties": {
                                "Property1": "value",
                                "Property2": "value2"
                        }
                },
                {
                        "Email": "janetdoe@example.com",
                        "Name": "Janet",
                        "Properties": {
                                "Property1": "value",
                                "Property2": "value2"
                        }
                }
        ]
    }'
/**
 *
 * Create : Manage the details of a Contact.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("contact")
    .action("managemanycontacts")
    .request({
        "Contacts":[
                {
                        "Email": "jimsmith@example.com",
                        "Name": "Jim",
                        "Properties": {
                                "Property1": "value",
                                "Property2": "value2"
                        }
                },
                {
                        "Email": "janetdoe@example.com",
                        "Name": "Janet",
                        "Properties": {
                                "Property1": "value",
                                "Property2": "value2"
                        }
                }
        ]
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : Manage the details of a Contact.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact_managemanycontacts.create(contacts: [{ 'Email'=> 'jimsmith@example.com', 'Name'=> 'Jim', 'Properties'=> { 'Property1'=> 'value', 'Property2'=> 'value2' }}, { 'Email'=> 'janetdoe@example.com', 'Name'=> 'Janet', 'Properties'=> { 'Property1'=> 'value', 'Property2'=> 'value2' }}])
"""
Create : Manage the details of a Contact.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Contacts': [
                {
                        "Email": "jimsmith@example.com",
                        "Name": "Jim",
                        "Properties": {
                                "Property1": "value",
                                "Property2": "value2"
                        }
                },
                {
                        "Email": "janetdoe@example.com",
                        "Name": "Janet",
                        "Properties": {
                                "Property1": "value",
                                "Property2": "value2"
                        }
                }
        ]
}
result = mailjet.contact_managemanycontacts.create(data=data)
print result.status_code
print result.json()
/*
Create : Manage the details of a Contact.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.ContactManagemanycontacts
    mr := &Request{
      Resource: "contact",
      Action: "managemanycontacts",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.ContactManagemanycontacts {
      Contacts: []MailjetContact {
        MailjetContact {
          Email: "jimsmith@example.com",
          Name: "Jim",
          Properties: MyPropertiesStruct {
            Property1: "value",
            Property2: "value2",
          },
        },
        MailjetContact {
          Email: "janetdoe@example.com",
          Name: "Janet",
          Properties: MyPropertiesStruct {
            Property1: "value",
            Property2: "value2",
          },
        },
      },
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.ContactManagemanycontacts;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : Manage the details of a Contact.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(ContactManagemanycontacts.resource)
                        .property(ContactManagemanycontacts.CONTACTS, new JSONArray()
                                                                .put(new JSONObject()
                                                                    .put("Email", "jimsmith@example.com")
                                                                    .put("Name", "Jim")
                                                                    .put("Properties", new JSONObject()
                                                                        .put("Property1", "value")
                                                                        .put("Property2", "value2")))
                                                                .put(new JSONObject()
                                                                    .put("Email", "janetdoe@example.com")
                                                                    .put("Name", "Janet")
                                                                    .put("Properties", new JSONObject()
                                                                        .put("Property1", "value")
                                                                        .put("Property2", "value2"))));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

Mailjet offers the /contact/managemanycontacts resource to create or update multiple contacts and their properties at once.

More information

Subscribe to a list

<?php
/*
Create : Manage a contact subscription to a list
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'ContactsLists' => [
        [
            'ListID' => "$ListID_1",
            'Action' => "addnoforce"
        ],
        [
            'ListID' => "$ListID_2",
            'Action' => "addforce"
        ]
    ]
];
$response = $mj->post(Resources::$ContactManagecontactslists, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : Manage a contact subscription to a list
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contact/$ID/managecontactslists \
    -H 'Content-Type: application/json' \
    -d '{
        "ContactsLists":[
                {
                        "ListID": "$ListID_1",
                        "Action": "addnoforce"
                },
                {
                        "ListID": "$ListID_2",
                        "Action": "addforce"
                }
        ]
    }'
/**
 *
 * Create : Manage a contact subscription to a list
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("contact")
    .id($ID)
    .action("managecontactslists")
    .request({
        "ContactsLists":[
                {
                        "ListID": "$ListID_1",
                        "Action": "addnoforce"
                },
                {
                        "ListID": "$ListID_2",
                        "Action": "addforce"
                }
        ]
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : Manage a contact subscription to a list
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contact_managecontactslists.create(id: $ID, contacts_lists: [{ 'ListID'=> '$ListID_1', 'Action'=> 'addnoforce'}, { 'ListID'=> '$ListID_2', 'Action'=> 'addforce'}])
"""
Create : Manage a contact subscription to a list
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$ID'
data = {
  'ContactsLists': [
                {
                        "ListID": "$ListID_1",
                        "Action": "addnoforce"
                },
                {
                        "ListID": "$ListID_2",
                        "Action": "addforce"
                }
        ]
}
result = mailjet.contact_managecontactslists.create(id=id, data=data)
print result.status_code
print result.json()
/*
Create : Manage a contact subscription to a list
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.ContactManagecontactslists
    mr := &Request{
      Resource: "contact",
      ID: RESOURCE_ID,
      Action: "managecontactslists",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.ContactManagecontactslists {
      ContactsLists: []MailjetContactsList {
        MailjetContactsList {
          ListID: "$ListID_1",
          Action: "addnoforce",
        },
        MailjetContactsList {
          ListID: "$ListID_2",
          Action: "addforce",
        },
      },
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      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());
    }
}

Last step: you have to add this contact to the contactslist previously created.

POST on the /contact/$ID/managecontactslists with $ID being the Mailjet contact id or the email address of the contact. You can specify one or more list to add this contact to. The action specified with the ListID can be addforce (force the subscription of the contact even if he unsubscribed to the list before) or addnoforce (do not resubscribe the contact to the list if unsubscribed before)

managecontactslist offer more possibilities of list management for a contact. More information

Create contact and subscribe at once

# Add a contact to the list
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/contactslist/$LIST_ID/managecontact \
    -H 'Content-Type: application/json' \
    -d '{
        "Email":"mrsmith@mailjet.com",
        "Name":"MrSmith",
        "Action":"addnoforce",
        "Properties":{
                "property1": "value",
                "propertyN": "valueN"
        }
    }'
<?php
/*
Add a contact to the list
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Email' => "mrsmith@mailjet.com",
    'Name' => "MrSmith",
    'Action' => "addnoforce",
    'Properties' => [
        'property1' => "value",
        'propertyN' => "valueN"
    ]
];
$response = $mj->post(Resources::$ContactslistManagecontact, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
/**
 *
 * Add a contact to the list
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("contactslist")
    .id($LIST_ID)
    .action("managecontact")
    .request({
        "Email":"mrsmith@mailjet.com",
        "Name":"MrSmith",
        "Action":"addnoforce",
        "Properties":{
                "property1": "value",
                "propertyN": "valueN"
        }
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Add a contact to the list
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Contactslist_managecontact.create(id: $LIST_ID, , , , email: "mrsmith@mailjet.com",name: "MrSmith",action: "addnoforce",properties: { 'property1'=> 'value', 'propertyN'=> 'valueN'})
"""
Add a contact to the list
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$LIST_ID'
data = {
  'Email': 'mrsmith@mailjet.com',
  'Name': 'MrSmith',
  'Action': 'addnoforce',
  'Properties': {
                "property1": "value",
                "propertyN": "valueN"
        }
}
result = mailjet.contactslist_managecontact.create(id=id, data=data)
print result.status_code
print result.json()
/*
Add a contact to the list
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
type  MyPropertiesStruct  struct {
  Property1  string
  PropertyN  string
}
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.ContactslistManagecontact
    mr := &Request{
      Resource: "contactslist",
      ID: RESOURCE_ID,
      Action: "managecontact",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.ContactslistManagecontact {
      Email: "mrsmith@mailjet.com",
      Name: "MrSmith",
      Action: "addnoforce",
      Properties: MyPropertiesStruct {
        Property1: "value",
        PropertyN: "valueN",
      },
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.ContactslistManagecontact;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Add a contact to the list
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(ContactslistManagecontact.resource, ID)
                        .property(ContactslistManagecontact.EMAIL, "mrsmith@mailjet.com")
                        .property(ContactslistManagecontact.NAME, "MrSmith")
                        .property(ContactslistManagecontact.ACTION, "addnoforce")
                        .property(ContactslistManagecontact.PROPERTIES, new JSONObject()
                                                                .put("property1", "value")
                                                                .put("propertyN", "valueN"));
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

API response:

{
    "Count": 1,
    "Data": [
        {
            "ContactID": "10",
            "Email": "mrsmith@mailjet.com",
            "Action": "addnoforce",
            "Name": "MrSmith",
            "Properties": {
                "property1": "value",
                "propertyN": "valueN"
            }
        }
    ],
    "Total": 1
}

The /contactslist/$ID/managecontact allows to create and add a contact to a list in one call.

The properties specified in this call can only be static Contact data. The Contact

‘Action’ is mandatory and can be one of the following values:

Actions
addforce string
adds the contact and resets the unsub status to false
addnoforce string
adds the contact and does not change the subscription status of the contact
remove string
removes the contact from the list
unsub string
unsubscribes a contact from the list

The response will include the ID of the contact that was created or updated.

Error response:

{
    "ErrorInfo": {
        "Properties": [
            {
                "property1": "Property not defined"
            },
            {
                "propertyN": "Property type does not match definition"
            }
        ]
    },
    "ErrorMessage": "Object properties invalid",
    "StatusCode": 400
}

In case of error, /contactslist/$ID/managecontact will return JSON payload containing a ErrorInfo and ErrorMessage.

Add Contacts in bulks

Managing and uploading multiple contacts ( /contact/managemanycontacts )

This resource allows to add contacts in bulk in a json format. Optionally, these contacts can be added to existing lists. More information

Managing multiple Contacts subscriptions to a List ( /contactslist/$ID/managemanycontacts )

This resource allows to add contacts directly to a list. This resource will create new contacts if the contacts are not already in the Mailjet system. More information

Managing Contacts through CSV upload

This process allows to upload csv containing large quantities of contacts. More information

Prepare a campaign

Create a campaign draft

<?php
/*
Create : CampaignDraft data
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Locale' => "en_US",
    'Sender' => "MisterMailjet",
    'SenderEmail' => "Mister@mailjet.com",
    'Subject' => "Greetings from Mailjet",
    'ContactsListID' => "$ID_CONTACTSLIST",
    'Title' => "Friday newsletter"
];
$response = $mj->post(Resources::$Campaigndraft, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : CampaignDraft data
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/campaigndraft \
    -H 'Content-Type: application/json' \
    -d '{
        "Locale":"en_US",
        "Sender":"MisterMailjet",
        "SenderEmail":"Mister@mailjet.com",
        "Subject":"Greetings from Mailjet",
        "ContactsListID":"$ID_CONTACTSLIST",
        "Title":"Friday newsletter"
    }'
/**
 *
 * Create : CampaignDraft data
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("campaigndraft")
    .request({
        "Locale":"en_US",
        "Sender":"MisterMailjet",
        "SenderEmail":"Mister@mailjet.com",
        "Subject":"Greetings from Mailjet",
        "ContactsListID":"$ID_CONTACTSLIST",
        "Title":"Friday newsletter"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : CampaignDraft data
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Campaigndraft.create(locale: "en_US",sender: "MisterMailjet",sender_email: "Mister@mailjet.com",subject: "Greetings from Mailjet",contacts_list_id: "$ID_CONTACTSLIST",title: "Friday newsletter")
"""
Create : CampaignDraft data
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
data = {
  'Locale': 'en_US',
  'Sender': 'MisterMailjet',
  'SenderEmail': 'Mister@mailjet.com',
  'Subject': 'Greetings from Mailjet',
  'ContactsListID': '$ID_CONTACTSLIST',
  'Title': 'Friday newsletter'
}
result = mailjet.campaigndraft.create(data=data)
print result.status_code
print result.json()
/*
Create : CampaignDraft data
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.Campaigndraft
    mr := &Request{
      Resource: "campaigndraft",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.Campaigndraft {
      Locale: "en_US",
      Sender: "MisterMailjet",
      SenderEmail: "Mister@mailjet.com",
      Subject: "Greetings from Mailjet",
      ContactsListID: "$ID_CONTACTSLIST",
      Title: "Friday newsletter",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.Campaigndraft;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Create : CampaignDraft data
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(Campaigndraft.resource)
                        .property(Campaigndraft.LOCALE, "en_US")
                        .property(Campaigndraft.SENDER, "MisterMailjet")
                        .property(Campaigndraft.SENDEREMAIL, "Mister@mailjet.com")
                        .property(Campaigndraft.SUBJECT, "Greetings from Mailjet")
                        .property(Campaigndraft.CONTACTSLISTID, "$ID_CONTACTSLIST")
                        .property(Campaigndraft.TITLE, "Friday newsletter");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

API response:

{
    "Count": 1,
    "Data": [
        {
            "AXFractionName": "",
            "AXTesting": "",
            "CampaignID": "",
            "ContactsListID": "$ID_CONTACTSLIST",
            "CreatedAt": "",
            "Current": "",
            "DeliveredAt": "",
            "EditMode": "",
            "ID": "",
            "IsStarred": "false",
            "IsTextPartIncluded": "false",
            "Locale": "en_US",
            "ModifiedAt": "",
            "Preset": "",
            "ReplyEmail": "",
            "SegmentationID": "",
            "Sender": "MisterMailjet",
            "SenderEmail": "Mister@mailjet.com",
            "SenderName": "",
            "Status": "",
            "Subject": "Greetings from Mailjet",
            "Template": "",
            "Title": "Friday newsletter",
            "Url": "",
            "Used": "false"
        }
    ],
    "Total": 1
}

To create a campaign draft, perform a POST on the /campaigndraft resource. Required fields are a Locale, Sender, SenderEmail, Subject and ContactsListID.

Reminder: the SenderEmail needs to be active. Visit the Sender domains & addresses section to check.

Add a body to a campaign draft

<?php
/*
Modify : CampaignDraft content data.
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Html-part' => "Hello <strong>world</strong>!",
    'Text-part' => "Hello world!"
];
$response = $mj->post(Resources::$CampaigndraftDetailcontent, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Modify : CampaignDraft content data.
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/campaigndraft/$ID/detailcontent \
    -H 'Content-Type: application/json' \
    -d '{
        "Html-part":"Hello <strong>world</strong>!",
        "Text-part":"Hello world!"
    }'
/**
 *
 * Modify : CampaignDraft content data.
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("campaigndraft")
    .id($ID)
    .action("detailcontent")
    .request({
        "Html-part":"Hello <strong>world</strong>!",
        "Text-part":"Hello world!"
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Modify : CampaignDraft content data.
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Campaigndraft_detailcontent.create(id: $ID, , html_part: "Hello <strong>world</strong>!",text_part: "Hello world!")
"""
Modify : CampaignDraft content data.
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$ID'
data = {
  'Html-part': 'Hello <strong>world</strong>!',
  'Text-part': 'Hello world!'
}
result = mailjet.campaigndraft_detailcontent.create(id=id, data=data)
print result.status_code
print result.json()
/*
Modify : CampaignDraft content data.
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.CampaigndraftDetailcontent
    mr := &Request{
      Resource: "campaigndraft",
      ID: RESOURCE_ID,
      Action: "detailcontent",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.CampaigndraftDetailcontent {
      HtmlPart: "Hello <strong>world</strong>!",
      TextPart: "Hello world!",
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err != nil {
      fmt.Println(err)
    }
    fmt.Printf("Data array: %+v\n", data)
}
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.CampaigndraftDetailcontent;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * Modify : CampaignDraft content data.
     */
    public static void main(String[] args) throws MailjetException, MailjetSocketTimeoutException {
      MailjetClient client;
      MailjetRequest request;
      MailjetResponse response;
      client = new MailjetClient(System.getenv("MJ_APIKEY_PUBLIC"), System.getenv("MJ_APIKEY_PRIVATE"));
      request = new MailjetRequest(CampaigndraftDetailcontent.resource, ID)
                        .property(CampaigndraftDetailcontent.HTMLPART, "Hello <strong>world</strong>!")
                        .property(CampaigndraftDetailcontent.TEXTPART, "Hello world!");
      response = client.post(request);
      System.out.println(response.getStatus());
      System.out.println(response.getData());
    }
}

API response :

{
    "Count": 1,
    "Data": [
        {
            "Html-part": "Hello <strong>world</strong>!",
            "Text-part": "Hello world!"
        }
    ],
    "Total": 1
}

Now that we have a campaign draft, we can add the most important property: its content, which can be Text or Html (Text-part or Html-part). To do so, you can perform a PUT or POST request on the /campaigndraft/$ID/detailcontent resource. With a POST, if you only give a value to Html-part or Text-part, the other one will be set to empty. While with a PUT, if you only give a value to Html-part or Text-part, the other one keeps its previous value.

Send a campaign

Test a campaign draft

<?php
/*
Create : CampaignDraft test
*/
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
$body = [
    'Recipients' => [
        [
            'Email' => "mailjet@example.org",
            'Name' => "Mailjet"
        ]
    ]
];
$response = $mj->post(Resources::$CampaigndraftTest, ['id' => $id, 'body' => $body]);
$response->success() && var_dump($response->getData());
?>
# Create : CampaignDraft test
curl -s \
    -X POST \
    --user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
    https://api.mailjet.com/v3/REST/campaigndraft/$ID/test \
    -H 'Content-Type: application/json' \
    -d '{
        "Recipients":[
                {
                        "Email": "mailjet@example.org",
                        "Name": "Mailjet"
                }
        ]
    }'
/**
 *
 * Create : CampaignDraft test
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("campaigndraft")
    .id($ID)
    .action("test")
    .request({
        "Recipients":[
                {
                        "Email": "mailjet@example.org",
                        "Name": "Mailjet"
                }
        ]
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })
# Create : CampaignDraft test
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']
  config.default_from = 'your default sending address'
end
variable = Mailjet::Campaigndraft_test.create(id: $ID, recipients: [{ 'Email'=> 'mailjet@example.org', 'Name'=> 'Mailjet'}])
"""
Create : CampaignDraft test
"""
from mailjet_rest import Client
import os
api_key = os.environ['MJ_APIKEY_PUBLIC']
api_secret = os.environ['MJ_APIKEY_PRIVATE']
mailjet = Client(auth=(api_key, api_secret))
id = '$ID'
data = {
  'Recipients': [
                {
                        "Email": "mailjet@example.org",
                        "Name": "Mailjet"
                }
        ]
}
result = mailjet.campaigndraft_test.create(id=id, data=data)
print result.status_code
print result.json()
/*
Create : CampaignDraft test
*/
package main
import (
    "fmt"
    . "github.com/mailjet/mailjet-apiv3-go"
    "github.com/mailjet/mailjet-apiv3-go/resources"
    "os"
)
func main () {
    mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
    var data []resources.CampaigndraftTest
    mr := &Request{
      Resource: "campaigndraft",
      ID: RESOURCE_ID,
      Action: "test",
    }
    fmr := &FullRequest{
      Info: mr,
      Payload: &resources.CampaigndraftTest {
      Recipients: []MailjetRecipient {
        MailjetRecipient {
          Email: "mailjet@example.org",
          Name: "Mailjet",
        },
      },
    },
    }
    err := mailjetClient.Post(fmr, &data)
    if err