Knowledge base

How to use variables in emails

MailerSend includes the ability to add simple and advanced personalization to email templates with variables. This enables you to customize and personalize the content to be unique for each recipient, increasing engagement and building stronger customer relationships. You can add personalization variables to the subject, HTML and text fields.

Simple personalization

With simple personalization, you can add basic data (such as name or email) to email templates using variables in the {$var} format when sending via the Email endpoint. Simple personalization variables start with a {$ followed by the variable name and end with a }. For example, {$name}.

Rules for naming variables

When naming your simple personalization variables, you must follow these rules to avoid errors when sending:

  • Variables must start with a dollar sign: '$'

  • They must be surrounded by curly brackets: '{ }'

  • They may contain alphanumeric characters and underscores: `_` but not hyphens: '-'

  • Variables must not start with a number or underscore

How to use simple personalization

You can add personalization variables to your subject line, HTML and text fields. Let's look at an example of a template with empty variables.

Email template example with simple personalization variables.

We can see that the template includes 6 variables that will need the corresponding data added when creating a POST request. These are order_date, order_number, delivery_date, delivery_method, delivery_address and support_email. Here's how that POST request would look when including all of the variables:

{
    "from": {
        "email": "your@email.com"
    },
    "to": [
        {
            "email": "recipient@email.com"
        }
    ],
    "variables": [{
        "email": "recipient@email.com",
        "substitutions": [
            {
                "var": "order_date",
                "value": "10/05/23"
            },
            {
                "var": "order_number",
                "value": "#12345"
            },
            {
                "var": "delivery_date",
                "value": "14/05/23"
            },
            {
                "var": "support_email",
                "value": "support@domain.com"
            },
            {
                "var": "delivery_method",
                "value": "FedEx"
            },
            {
                "var": "delivery_address",
                "value": "1123 Old River Rd, 29047 Elloree, South Carolina"
            }
        ]
    }],
    "template_id": "23zxk54voxgjy6v7"
}

And the result would be:

Example of an email template with variables accounting for the corresponding data.

Important notes about simple personalization

  • When using simple personalization, a value must be entered for variables. Sending blank values will result in an error, like the one below.

{
  "message": "The given data was invalid.",
  "errors": {
    "variables.0.substitutions.0.value": [
      "The variables.0.substitutions.0.value field is required."
    ]
  }
}
  • You can only pass values of a string data type. You'll need to convert your variables' values to a string before you're able to pass those in your API call. If you pass non-string values, you'll get an error like this.

{
  "message": "The given data was invalid.",
  "errors": {
    "variables.0.substitutions.0.value": [
      "The variables.0.substitutions.0.value must be a string."
    ]
  }
}

If you want to pass non-string data types such as integers or boolean values, it's recommended that you use advanced personalization.

Advanced personalization

Much like simple personalization, advanced personalization allows you to use variables to generate dynamic content when sending emails. Advanced personalization, however, uses a limited version of Twig v3.x as the template language.

This gives you the added flexibility of using filtersconditional statements, and iterating over arrays with for loops, making advanced personalization a more powerful and flexible version of simple personalization. Especially if you're dealing with a variety of dynamic data.

Rules for naming variables

The notation for advanced personalization variables is slightly different from simple personalization variables. Advanced personalization variables start with double curly brackets {{ followed by the variable name, then ending with double curly brackets }}. For example, {{var}}.

As with simple personalization, there are a number of rules you must follow to avoid errors when sending:

  • Variables must be surrounded by double curly brackets: `{{ }}`

  • They may contain alphanumeric characters and underscores: '_' but not hyphens: '-'

  • Variables must not start with a number or underscore

  • They are case sensitive, meaning that `{{VAR}}` is different from `{{var}}`

How to use advanced personalization

You can add advanced personalization variables to the subject, HTML and text fields. Here's an example of an email template using advanced personalization variables:

Example of an email template using advanced personalization variables.

We can see that in this template, there are 3 variables that data needs to be added for in the body of our API call. These are name, support_email and account_name. Here's how that POST request would look when including all of the variables:

{
	"to": [
		{
			"email": "info@mailersend.com"
		}
	],
	"template_id": "z3m5jgrjm04dpyo6",
	"personalization": [
		{
			"email": "info@mailersend.com",
			"data": {
				"name": "John Doe",
				"support_email": "hello@examplecompany.com",
				"account_name": "Example Company"

			}
		}
	]
}

And this would be the resulting email:

Example of an email using advanced personalization.

How to use filters

You can use Twig filters to modify variables with the following rules:

  • Filters are separated from the variable by a pipe symbol: '|'

  • They may have optional arguments in parentheses

  • Multiple filters can be chained, meaning that the output of one filter is applied to the next

As an example, let's take a look at Twig's default filter. The default filter returns the default value you have assigned if the variable value is undefined or empty.

This can be used to set a fallback value for variables that have been left undefined. For example, if the "name" variable is left empty, the default filter can be used so that an email template reads "Hi there" instead of "Hi {{name}}". In this instance, the variable would look like this: {{name|default('there')}}.

An example of email using an advanced personalization variable with the default filter.

When using the default filter in this way, the name variable can be left empty or omitted entirely from the body of the API call, and the default value or fallback will be shown.

An example of an email using the default filter value.
Note: As of now MailerSend supports the following Twig filters: 'default', 'escape', 'length', 'lower', 'upper' and 'keys'.

How to use dynamic tables

Dynamic tables allow you to add rows of data dynamically to a table via an API call. This is especially useful in transactional emails that contain billing information or invoices or other types of emails where the end result of the table can vary depending on the selections of the customer.

As an example, let's take a look at an order confirmation email template that uses a dynamic table.

Example of an order confirmation emails that uses a dynamic template.

We've set the dynamic table's array key as 'products' which means we'll have an array of objects (products) in the table. Each row will represent a separate object (product) under the 'products' array. Here's how the POST request for the API call would look:

{
	"to": [
		{
			"email": "info@mailersend.com"
		}
	],
	"template_id": "k68zxl2563lj9057",
	"personalization": [
		{
			"email": "info@mailersend.com",
			"data": {
				"order_number": 1234567890,
				"account_name": "Example Company",
				"support_email": "hello@examplecompany.com",
				"products": [
					{
						"name": "Nike Airforce Ones",
						"quantity": 2,
						"size": 43,
						"color": "Beetroot"
					},
					{
						"name": "Vans Retro",
						"quantity": 1,
						"size": 44,
						"color": "Black"
					},
					{
						"name": "Yeezys",
						"quantity": 3,
						"size": 45,
						"color": "Chrome"
					}
				]
			}
		}
	]
}

And here is how the resulting email would look:

An email example showing a dynamic table as a result of the previous API call.

How to use conditional statements

A conditional statement is a command that tells a computer or system what action to take based on the conditions you set. A common way to do this is with If/Else statements. If the condition is true, do this. Else, if the condition is false, do another thing instead.

Rules for using conditional statements

  • Conditional statements (i.e. if/elseif/else) must appear inside the following block: `{% %}

  • A conditional block always starts with the `if` keyword followed by the statement that is being tested and ends with the `endif` keyword

  • Conditional statements are only available in the HTML and text fields

Here's an example of a simple if statement:

{% if online == false %}

    <p>Our website is in maintenance mode. Please, come back later.</p>

{% endif %}

Now let's look at how you could use conditional statements in our order confirmation email example to make decision-making logic easier within templates.

In the below example, we've added a conditional statement that will change the delivery messaging in the template depending on whether the customer is/isn't within a delivery range.

Note: To keep things simple, we're using a boolean data type for our 'within_range' variable which can either equate to 'true' or 'false'. You can use other data types such as 'string' or 'integer' too.
Example of an email template using a conditional statement.

And this is how the POST request body of our API call would look, taking into account the 'within_range' variable.

{
	"to": [
		{
			"email": "info@mailersend.com"
		}
	],
	"template_id": "k68zxl2563lj9057",
	"personalization": [
		{
			"email": "info@mailersend.com",
			"data": {
				"order_number": 1234567890,
				"account_name": "Example Company",
				"support_email": "hello@examplecompany.com",
				"within_range": false,
				"products": [
					{
						"name": "Nike Airforce Ones",
						"quantity": 2,
						"size": 43,
						"color": "Beetroot"
					},
					{
						"name": "Vans Retro",
						"quantity": 1,
						"size": 44,
						"color": "Black"
					},
					{
						"name": "Yeezys",
						"quantity": 3,
						"size": 45,
						"color": "Chrome"
					}
				]
			}
		}
	]
}

The 'within_range' variable is set to false so the resulting email will contain the else part of our messaging.

An example of conditional statements at work.

If we set the 'within-range' variable to true, the resulting email would be as follows:

An example of an email template with conditional statements.
Check out Twig's documentation to learn more about conditional statements.

How to use for loops

You can use for loops to loop over each item in a collection of data in a sequence: for example, looping over arrays to display a list of items in your email.

Rules for using for loops

  • Loops must appear inside the following block: `{% %}

  • A loops block always starts with the `for` keyword and ends with the `endfor` keyword

  • For loops are only available in the HTML and text fields

For example, to display a list of titles provided in an array called `books`, you can add the following code to a code block in your template:

<ul>
    {% for title in books %}
        <li>{{title}}</li>
    {% endfor %}
</ul>

Here's how you would add this to a template to include the for loop in a code block.

Example of a for loop in an email template.

Now all you need to do is include your books array within the personalization object of your request body. Here's how that would look.

{
	"to": [
		{
			"email": "info@mailersend.com"
		}
	],
	"template_id": "k68zxl25velj9057",
	"personalization": [
		{
			"email": "info@mailersend.com",
			"data": {
				"books": [
					"The Institute",
					"Killers of the Flower Moon",
					"Cosmos",
					"100 Years of Solitude"
				]
			}
		}
	]
}

And this is how it would appear in the email:

Example of an email using a for loop to display a list of books.
You can do a lot more with for loops, especially if you combine them with filters. Check out Twig's documentation to learn more.

Need more info?

For other questions, feel free to talk with us via live chat or at support@mailersend.com.

Stop War! Help Ukraine! See what you can do