NAV
cURL PHP NODE RUBY PYTHON GO JAVA C#

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

<?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());
    }
}
# 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 
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : List of 150 contacts
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
         }
         .Filter(Contact.Limit, "150");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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()
/*
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)
}
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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : List of contact with Offset, delivers 10 contacts, starting with the 25000th contact
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
         }
         .Filter(Contact.Offset, "25000");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : List of contacts with Limit and Offset, retrieves a list of 150 contacts starting with the 25000th contact
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
         }
         .Filter(Contact.Limit, "150")
         .Filter(Contact.Offset, "25000");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}
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
"""
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()
/*
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)
}
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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : List of contact ordered by email in an ascending order
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
         }
         .Filter(Contact.Sort, "email");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
    class Program
    {
        /// <summary>
        /// View : List of contact ordered by email in an ascending order
        /// </summary>
        static void Main(string[] args)
        {
            RunAsync().Wait();
        }
        static async Task RunAsync()
        {
            MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
            MailjetRequest request = new MailjetRequest
            {
                Resource = Contact.Resource,
            }
                  .Filter(Contact.Sort, "email DESC");
            MailjetResponse response = await client.GetAsync(request);
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
                Console.WriteLine(response.GetData());
            }
            else
            {
                Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
                Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
                Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
            }
        }
    }
}

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : Contacts in ContactsList
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
         }
         .Filter(Contact.Contactslist, "$ContactsListID");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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()
/*
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)
}
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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : Contact from email address
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
            ResourceId = ResourceId.Numeric(ID)
         }
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : event-driven callback URLs, also called webhooks, used by the Mailjet platform when a specific action is triggered
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Eventcallbackurl.Resource,
            ResourceId = ResourceId.Numeric(ID)
         }
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : View Campaign/message/click statistics grouped by ContactsList with Like filter on Name.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Liststatistics.Resource,
         }
         .Filter(Liststatistics.Namelike, "$Name");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
    class Program
    {
        /// <summary>
        /// View : Total number of contact
        /// </summary>
        static void Main(string[] args)
        {
            RunAsync().Wait();
        }
        static async Task RunAsync()
        {
            MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
            MailjetRequest request = new MailjetRequest
            {
                Resource = Contact.Resource,
            }
            .Filter(Contact.CountOnly, "1");
            MailjetResponse response = await client.GetAsync(request);
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
                Console.WriteLine(response.GetData());
            }
            else
            {
                Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
                Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
                Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
            }
        }
    }
}

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.

Prerequisites

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// 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.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Sender.Resource,
         }
            .Property(Sender.Email, "anothersender@example.com");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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.

Send API v3.1 (beta)

Mailjet is offering a public beta version of the new Send API. This news version is a brand new Send API with new functionalities, better error reporting and higher overall performance and scalability.

If you are a current user of Send API in version 3, we listed the changes you will need to take into account.

Read this blogpost to learn more on how we designed this new version and where our Transactional Suite is going to.

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)
    })
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to one recipient.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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 separated 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 receive a common message showing every other recipients and carbon copies recipients. The recipients listed in Recipients will each receive an separate 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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to two recipients in To and one recipient in CC.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.To, "Name <passenger@mailjet.com>, Name2 <passenger2@mailjet.com>")
            .Property(Send.Cc, "Name3 <passenger@mailjet.com>");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    })
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to 2 recipients.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger1@mailjet.com"},
                 {"Name", "passenger 1"}
                 },
                new JObject {
                 {"Email", "passenger2@mailjet.com"},
                 {"Name", "passenger 2"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    })
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to the given recipient.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                })
            .Property(Send.Attachments, new JArray {
                new JObject {
                 {"Content-type", "text/plain"},
                 {"Filename", "test.txt"},
                 {"content", "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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":"R0lGODlhEAAQAOYAAP////748v39/Pvq1vr6+lJSVeqlK/zqyv7+/unKjJ+emv78+fb29pucnfrlwvTCi9ra2vTCa6urrWdoaurr6/Pz8uHh4vn49PO7QqGfmumaN+2uS1ZWWfr27uyuLnBxd/z8+0pLTvHAWvjar/zr2Z6cl+jal+2kKmhqcEJETvHQbPb07lBRVPv6+cjJycXFxn1+f//+/f337nF0efO/Mf306NfW0fjHSJOTk/TKlfTp0Prlx/XNj83HuPfEL+/v8PbJgueXJOzp4MG8qUNES9fQqN3d3vTJa/vq1f317P769f/8+gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS4wLWMwNjAgNjEuMTM0Nzc3LCAyMDEwLzAyLzEyLTE3OjMyOjAwICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MjY5ODYxMzYzMkJCMTFFMDkzQkFFMkFENzVGN0JGRkYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MjY5ODYxMzczMkJCMTFFMDkzQkFFMkFENzVGN0JGRkYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDoyNjk4NjEzNDMyQkIxMUUwOTNCQUUyQUQ3NUY3QkZGRiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDoyNjk4NjEzNTMyQkIxMUUwOTNCQUUyQUQ3NUY3QkZGRiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PgH//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJCAcGBQQDAgEAACH5BAEAAAAALAAAAAAQABAAAAdUgACCg4SFhoeIiYRGLhaKhA0TMDgSLxAUiEIZHAUsIUQpKAo9Og6FNh8zJUNFJioYQIgJRzc+NBEkiAcnBh4iO4o8QRsjj0gaOY+CDwPKzs/Q0YSBADs="}]
    }'
/**
 *
 * 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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to the given recipient.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to <img src=\"cid:logo.gif\">Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                })
            .Property(Send.InlineAttachments, new JArray {
                new JObject {
                 {"Content-type", "image/gif"},
                 {"Filename", "logo.gif"},
                 {"content", "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"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to the given recipient.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.Messages, new JArray {
                new JObject {
                 {"FromEmail", "pilot@mailjet.com"},
                 {"FromName", "Mailjet Pilot"},
                 {"Recipients", new JArray {
                  new JObject {
                   {"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!"}
                 },
                new JObject {
                 {"FromEmail", "pilot@mailjet.com"},
                 {"FromName", "Mailjet Pilot"},
                 {"Recipients", new JArray {
                  new JObject {
                   {"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!"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to 2 given recipient with global personalisation.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you!")
            .Property(Send.Vars, new JObject {
                {"day", "Monday"}
                })
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger1@mailjet.com"},
                 {"Name", "passenger 1"}
                 },
                new JObject {
                 {"Email", "passenger2@mailjet.com"},
                 {"Name", "passenger 2"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to 2 recipients with global and contact personalisation.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this [[var:day]], may the delivery force be with you! [[var:personalmessage]]")
            .Property(Send.Vars, new JObject {
                {"day", "Monday"}
                })
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger1@mailjet.com"},
                 {"Name", "passenger 1"},
                 {"Vars", new JObject {
                  {"day", "Tuesday"},
                  {"personalmessage", "Happy birthday!"}
                  }}
                 },
                new JObject {
                 {"Email", "passenger2@mailjet.com"},
                 {"Name", "passenger 2"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to the given recipient.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear [[data:firstname:\"passenger\"]], welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear [[data:firstname:\"passenger\"]], welcome to Mailjet!</h3><br /> May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger1@mailjet.com"},
                 {"Name", "passenger 1"}
                 },
                new JObject {
                 {"Email", "passenger2@mailjet.com"},
                 {"Name", "passenger 2"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends a message based on a template.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.MjTemplateID, "1")
            .Property(Send.MjTemplateLanguage, "True")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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.

Using Template Language

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to the given recipient with vars and custom vars.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br /> On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}")
            .Property(Send.Vars, new JObject {
                {"day", "Monday"}
                })
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger1@mailjet.com"},
                 {"Name", "passenger 1"},
                 {"Vars", new JObject {
                  {"day", "Tuesday"},
                  {"personalmessage", "Happy birthday!"}
                  }}
                 },
                new JObject {
                 {"Email", "passenger2@mailjet.com"},
                 {"Name", "passenger 2"}
                 }
                })
            .Property(Send.MjTemplateLanguage, "True");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

Mailjet Send API allow to leverage template language in your transactional messages.

The Mailjet Template Language include fonctionality for :

Find our dedicated guide here.

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to one recipient with a Reply-To address
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                })
            .Property(Send.Headers, new JObject {
                {"Reply-To", "copilot@mailjet.com"}
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends a message to one recipient with a CustomID
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                })
            .Property(Send.MjCustomID, "PassengerEticket1234");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : API Key Statistical campaign/message data.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Messagesentstatistics.Resource,
         }
         .Filter(Messagesentstatistics.Customid, "PassengerEticket1234");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends a message to one recipient with an EventPayload.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                })
            .Property(Send.MjEventPayload, "Eticket,1234,row,15,seat,B");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to one recipient within a campaign blocking multiple email to same recipient
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                })
            .Property(Send.Mjcampaign, "SendAPI_campaign")
            .Property(Send.Mjdeduplicatecampaign, "1");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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.

Real-time Monitoring

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-MonitoringCategory': 'Category1'
}
result = mailjet.send.create(data=data)
print result.status_code
print result.json()
/*
This calls sends an email to one recipient with Real-time Monitoring.
*/
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",
        },
      },
      MjMonitoringCategory: "Category1"
    }
    res, err := mailjetClient.SendMail(email)
    if err != nil {
            fmt.Println(err)
    } else {
            fmt.Println("Success")
            fmt.Println(res)
    }
}
<?php
/*
This calls sends an email to one recipient with Real-time Monitoring.
*/
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-MonitoringCategory' => "Category1"
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$response->success() && var_dump($response->getData());
?>
# This calls sends an email to one recipient with Real-time Monitoring.
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-MonitoringCategory': "Category1")
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 Real-time Monitoring.
     */
    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.MJMONITORINGCATEGORY, "Category1")
                        .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 with Real-time Monitoring.
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-MonitoringCategory": "Category1"
    }'
/**
 *
 * This calls sends an email to one recipient with Real-time Monitoring.
 *
 */
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-MonitoringCategory": "Category1"
    })
request
    .then(result => {
        console.log(result.body)
    })
    .catch(err => {
        console.log(err.statusCode)
    })
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends an email to one recipient with Real-time Monitoring.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.TextPart, "Dear passenger, welcome to Mailjet! May the delivery force be with you!")
            .Property(Send.HtmlPart, "<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!")
            .Property(Send.MjMonitoringCategory, "Category1")
        .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

Real-time Monitoring enables you to have a constant supervision on your transactional messages by creating custom alerts on categories of Messages.

You can create as many alerts as you want under one of our four types of monitoring alerts, allowing you to fully control your sending:

Mailjet’s Real-time monitoring will inform you by email, Slack or even SMS based on alert

After creating your categories and alerts in our user interface, you can leverage the Mj-MonitoringCategory property to specify which category the message you are sending is related to.

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
Mj-MonitoringCategory Category for Real-time Monitoring to which the message will be attached
Equivalent of using X-MJ-MonitoringCategory header through SMTP.
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

Template API

Overview

Template API allows for the storage and access to your templates on the Mailjet system.

Template API will give you access to all templates : Marketing , Transactional , Automation and snippets

By using templates, you will find no need to provide the content of your message at each call to the Send API, just use your predefined template.

Template API can leverage templates created with Passport, our free responsive email template builder.

Storing a template

Store your templates on your Mailjet account by using the /template API resource. These templates can also 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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// Create : 
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Template.Resource,
         }
            .Property(Template.Name, "First Template");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// Create : Template content
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = TemplateDetailcontent.Resource,
            ResourceId = ResourceId.Numeric(ID)
         }
            .Property(TemplateDetailcontent.Htmlpart, "<html><body><p>Hello {{var:name}}</p></body></html>")
            .Property(TemplateDetailcontent.Textpart, "Hello {{var:name}}");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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)
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// This calls sends a message based on a template.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.FromEmail, "pilot@mailjet.com")
            .Property(Send.FromName, "Mailjet Pilot")
            .Property(Send.Subject, "Your email flight plan!")
            .Property(Send.MjTemplateID, "1")
            .Property(Send.MjTemplateLanguage, "True")
            .Property(Send.Recipients, new JArray {
                new JObject {
                 {"Email", "passenger@mailjet.com"}
                 }
                });
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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.

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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : Find your personal templates
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Template.Resource,
         }
         .Filter(Template.Ownertype, "user")
         .Filter(Template.Limit, "100");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}
<?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
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
"""
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
*/
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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// View : Find your templates, created in Passport
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Template.Resource,
         }
         .Filter(Template.Editmode, "tool")
         .Filter(Template.Limit, "100")
         .Filter(Template.Ownertype, "user");
         MailjetResponse response = await client.GetAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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.

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
"""
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()
/*
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)
}
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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// Create : only need a Name
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contactslist.Resource,
         }
            .Property(Contactslist.Name, "myList");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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()
/*
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)
}
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());
    }
}
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// <summary>
      /// Create : Manage the details of a Contact.
      /// </summary>
      static void Main(string[] args)
      {
         RunAsync().Wait();
      }
      static async Task RunAsync()
      {
         MailjetClient client = new MailjetClient(Environment.GetEnvironmentVariable("MJ_APIKEY_PUBLIC"), Environment.GetEnvironmentVariable("MJ_APIKEY_PRIVATE"));
         MailjetRequest request = new MailjetRequest
         {
            Resource = Contact.Resource,
         }
            .Property(Contact.Email, "Mister@mailjet.com");
         MailjetResponse response = await client.PostAsync(request);
         if (response.IsSuccessStatusCode)
         {
            Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount()));
            Console.WriteLine(response.GetData());
         }
         else
         {
            Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode));
            Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo()));
            Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage()));
         }
      }
   }
}

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
    .