Reference

This document describes the logic of the Mailjet's template language and the syntax, variables, functions and statements available for the creation of a dynamic template.

Delimitators

The template language elements need to be wrapped between the following delimitators:

  • {{ ... }} for expressions that you would like to print in the template output
  • {% ... %} for statements (conditions and loops)

Operators

Arithmetic Operators :

  • +
  • -
  • *
  • / : float division
  • div : integer division , Format: ( X div Y )
  • mod : remainder of division, Format: ( X mod Y )

Comparison Operators :

  • > : strict superior
  • < : strict inferior
  • >= : superior
  • <= : inferior
  • =, ==, === : equals
  • !=, <> : not equals

Logical operators :

  • and
  • or
  • xor
  • not

Variables

Four sources of variables (or namespaces) are on offer in the template language. They can be used for simple insertion with {{ ... }} or with operators, functions and control structures.

  • Vars (var) : non-persistent information, sent with the message
  • Contact properties - ContactData (data) : information related to the contact, already stored in Mailjet system
  • Predefined static variables (mj) : allowing you to easily access specific information related to the contact, sender, template and others
  • Segmentation (segmentation) : leveraging the existing segmentation formulas you created for marketing purposes.

Vars and Custom Vars

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

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

# 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.1/send \
	-H 'Content-Type: application/json' \
	-d '{
		"Messages":[
			{
				"From": {
					"Email": "pilot@mailjet.com",
					"Name": "Mailjet Pilot"
				},
				"To": [
					{
					"Email": "passenger1@mailjet.com",
					"Name": "passenger 1"
					}
				],
				"TextPart": "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
				"HTMLPart": "

Dear passenger, welcome to Mailjet!


On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}", "TemplateLanguage": true, "Subject": "Your email flight plan!", "Variables": { "day": "Tuesday", "personalmessage": "Happy birthday!" } } ] }'
<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
$mj = new \Mailjet\Client(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'),true,['version' => 'v3.1']);
$body = [
    'Messages' => [
        [
            'From' => [
                'Email' => "pilot@mailjet.com",
                'Name' => "Mailjet Pilot"
            ],
            'To' => [
                [
                    'Email' => "passenger1@mailjet.com",
                    'Name' => "passenger 1"
                ]
            ],
            'TextPart' => "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
            'HTMLPart' => "

Dear passenger, welcome to Mailjet!


On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}", 'TemplateLanguage' => true, 'Subject' => "Your email flight plan!", 'Variables' => [ '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.
 *
 */
const mailjet = require ('node-mailjet')
	.connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
	.post("send", {'version': 'v3.1'})
	.request({
		"Messages":[
			{
				"From": {
					"Email": "pilot@mailjet.com",
					"Name": "Mailjet Pilot"
				},
				"To": [
					{
					"Email": "passenger1@mailjet.com",
					"Name": "passenger 1"
					}
				],
				"TextPart": "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
				"HTMLPart": "

Dear passenger, welcome to Mailjet!


On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}", "TemplateLanguage": true, "Subject": "Your email flight plan!", "Variables": { "day": "Tuesday", "personalmessage": "Happy birthday!" } } ] }) 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.
require 'mailjet'
Mailjet.configure do |config|
  config.api_key = ENV['MJ_APIKEY_PUBLIC']
  config.secret_key = ENV['MJ_APIKEY_PRIVATE']  
  config.api_version = "v3.1"
end
variable = Mailjet::Send.create(messages: [{
    'From'=> {
        'Email'=> 'pilot@mailjet.com',
        'Name'=> 'Mailjet Pilot'
    },
    'To'=> [
        {
            'Email'=> 'passenger1@mailjet.com',
            'Name'=> 'passenger 1'
        }
    ],
    'TextPart'=> 'Dear passenger, welcome to Mailjet! On this {{var:day:\'monday\'}}, may the delivery force be with you! {{var:personalmessage:\'\'}}',
    'HTMLPart'=> '

Dear passenger, welcome to Mailjet!


On this {{var:day:\'monday\'}}, may the delivery force be with you! {{var:personalmessage:\'\'}}', 'TemplateLanguage'=> true, 'Subject'=> 'Your email flight plan!', 'Variables'=> { 'day'=> 'Tuesday', 'personalmessage'=> 'Happy birthday!' } }] ) p variable.attributes['Messages']
"""
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), version='v3.1')
data = {
  'Messages': [
	{
		"From": {
			"Email": "pilot@mailjet.com",
			"Name": "Mailjet Pilot"
		},
		"To": [
			{
			"Email": "passenger1@mailjet.com",
			"Name": "passenger 1"
			}
		],
		"TextPart": "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
		"HTMLPart": "

Dear passenger, welcome to Mailjet!


On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}", "TemplateLanguage": True, "Subject": "Your email flight plan!", "Variables": { "day": "Tuesday", "personalmessage": "Happy birthday!" } } ] } result = mailjet.send.create(data=data) print result.status_code print result.json()
package com.my.project;
import com.mailjet.client.errors.MailjetException;
import com.mailjet.client.errors.MailjetSocketTimeoutException;
import com.mailjet.client.MailjetClient;
import com.mailjet.client.MailjetRequest;
import com.mailjet.client.MailjetResponse;
import com.mailjet.client.ClientOptions;
import com.mailjet.client.resource.Emailv31;
import org.json.JSONArray;
import org.json.JSONObject;
public class MyClass {
    /**
     * This call sends a message to the given recipient with vars and custom vars.
     */
    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"), new ClientOptions("v3.1"));
      request = new MailjetRequest(Emailv31.resource)
			.property(Emailv31.MESSAGES, new JSONArray()
                .put(new JSONObject()
                    .put(Emailv31.Message.FROM, new JSONObject()
                        .put("Email", "pilot@mailjet.com")
                        .put("Name", "Mailjet Pilot"))
                    .put(Emailv31.Message.TO, new JSONArray()
                        .put(new JSONObject()
                            .put("Email", "passenger1@mailjet.com")
                            .put("Name", "passenger 1")))
                    .put(Emailv31.Message.TEXTPART, "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}")
                    .put(Emailv31.Message.HTMLPART, "

Dear passenger, welcome to Mailjet!


On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}") .put(Emailv31.Message.TEMPLATELANGUAGE, true) .put(Emailv31.Message.SUBJECT, "Your email flight plan!") .put(Emailv31.Message.VARIABLES, new JSONObject() .put("day", "Tuesday") .put("personalmessage", "Happy birthday!")))); response = client.post(request); System.out.println(response.getStatus()); System.out.println(response.getData()); } }
/*
This calls sends an email to the given recipient with vars and custom vars.
*/
package main
import (
	"fmt"
	"log"
	"os"
	mailjet "github.com/mailjet/mailjet-apiv3-go"
)
func main () {
	mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"))
	messagesInfo := []mailjet.InfoMessagesV31 {
      mailjet.InfoMessagesV31{
        From: &mailjet.RecipientV31{
          Email: "pilot@mailjet.com",
          Name: "Mailjet Pilot",
        },
        To: &mailjet.RecipientsV31{
          mailjet.RecipientV31 {
            Email: "passenger1@mailjet.com",
            Name: "passenger 1",
          },
        },
      TextPart: "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}",
      HTMLPart: "

Dear passenger, welcome to Mailjet!


On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}", TemplateLanguage: true, Subject: "Your email flight plan!", Variables: map[string]interface{}{ "day": "Tuesday","personalmessage": "Happy birthday!"}, }, }, messages := mailjet.MessagesV31{Info: messagesInfo } res, err := m.SendMailV31(&messages) if err != nil { log.Fatal(err) } fmt.Printf("Data: %+v\n", res) }
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using Newtonsoft.Json.Linq;
namespace Mailjet.ConsoleApplication
{
   class Program
   {
      /// 
      /// This call sends a message to the given recipient with vars and custom vars.
      /// 
      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"))
         {
            Version = ApiVersion.V3_1,
         };
         MailjetRequest request = new MailjetRequest
         {
            Resource = Send.Resource,
         }
            .Property(Send.Messages, new JArray {
                new JObject {
                 {"From", new JObject {
                  {"Email", "pilot@mailjet.com"},
                  {"Name", "Mailjet Pilot"}
                  }},
                 {"To", new JArray {
                  new JObject {
                   {"Email", "passenger1@mailjet.com"},
                   {"Name", "passenger 1"}
                   }
                  }},
                 {"TextPart", "Dear passenger, welcome to Mailjet! On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}"},
                 {"HTMLPart", "

Dear passenger, welcome to Mailjet!


On this {{var:day:\"monday\"}}, may the delivery force be with you! {{var:personalmessage:\"\"}}"}, {"TemplateLanguage", true}, {"Subject", "Your email flight plan!"}, {"Variables", new JObject { {"day", "Tuesday"}, {"personalmessage", "Happy birthday!"} }} } }); 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(response.GetData()); Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage())); } } } }

Note

In order to have the template language interpreted, you must provide Mj-TemplateLanguage property in the payload to the Send API and set it to true.

Mailjet templating language support multidimensional json structure in the vars and custom vars:

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

Template

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

Html result

2 Hello

Contact properties

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

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

Predefined static variables

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

mj:contact

mj:contact represents the recipient of the current message (related to /contact resource of Mailjet API and recipient defined in the Send API call).

  • mj:contact.ID : Mailjet Contact ID
  • mj:contact.email : Email address (local_part@domain)
  • mj:contact.local_part
  • mj:contact.domain
  • mj:contact.name : Name of the contact

mj:sender

mj:sender represents the sender of the current message (related to /sender resource of Mailjet API and recipient defined in the Send API call).

  • mj:sender.ID : Mailjet Sender ID
  • mj:sender.email : Email address (local_part@domain)
  • mj:sender.local_part
  • mj:sender.domain
  • mj:sender.name : Name of the sender

mj:template

mj:template represents the template used to generate this message (related to /template resource of Mailjet API).

  • mj:template.ID
  • mj:template.name
  • mj:template.copyright

More

  • mj:unsub_link: the unsubscription link in english (EN)
  • mj:unsub_link_$lang: the unsubscription link in the specified language (ISO-639-1 formatted)
  • mj:share_twitter: the Twitter link to share the online version of the newsletter
  • mj:share_google: the Google+ link to share the online version of the newsletter
  • mj:share_facebook: the Facebook link to share the online version of the newsletter
  • mj:share_linkedin: the LinkedIn link to share the online version of the newsletter

Segmentation

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

<html><body>
{% if segment:nameSegment %}
    <h1>Recipient {{mj:contact.email}} matches segment nameSegment</h1>
{% endif %}
</body></html>

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

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

Functions

Behavior of the contact

  • HasOpenedSince(number_of_days) : return true if the contact has opened a message in the last number of days
  • HasClickedSince(number_of_days) : return true if the contact has clicked on a link in a message in the last number of days

String modification

  • Upper(string) : Uppercase the string
  • Lower(string) : Lowercase the string
  • Capitalize(string) : Capitalize the first letter of the string

Mathematical functions

  • Round(value, precision) : round a value at precision decimals
  • Int(value) : Return the integer part of a number

Formatting functions

FormatNumberLocale(format, number, locale) : allows you to specify the format of a float

  • Format : a string parameter which accepts the following symbols:

    0 (zero) : represents a forced digit. This means that whether or not the digit is relevant to the value, it will be displayed

    # (hash) : represents an optional digit

    , (comma) : represents the thousands separator in the number being displayed

    . (dot) : represents the location of the decimal point in the number being displayed

  • Number : represents the numerical value you would like to format.

  • Locale : a string parameter which defines the decimal point and the thousands separator.

Possible use cases:
FormatNumber("#,###.00", 1000, "fr_FR"): 1 000,00 
FormatNumber ("0.##", 0.666666, "en_GB"): 0.67

FormatNumber(format,number) : replicates the behavior of FormatNumberLocale, but with default locale set to “en_US”, defining the decimal point as the . chararcter and the thousand separator as the , character.

Possible use cases:
FormatNumber("#,###.00", 1000): 1,000.00
FormatNumber(".00", 0.99) => .99

Encoding/ Formating

  • UrlEncode(string) : Encode a string for use in a URL
  • Escape(html) : Encode html to be displayed as code in the message

Conditional Statements

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

The if statements can be nested inside one another.

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

Html result

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

or

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

Multiple branches of if statement:

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

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

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

The behavior of the conditional statement will be as follow:

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

Set function

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

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

Printing value

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

You can change the value of the variable anytime.

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

In conditional statement

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

Loop Statements

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

The syntax is:

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

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

JSON payload

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

or

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

Template

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

Html result

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

Multidimensional array

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

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

Template

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

Html result

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

Multiple array

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

Template

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

Html result

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