Working with variables
Define custom variables with types and fallback values on a template, then supply their values when you send.
Custom template variables let you reuse one template across many sends and fill in the per-recipient details at send time. You declare each variable on the template — with a key, a type, and an optional fallback_value — and reference it in the body. When you send, MailBlastr substitutes the values you supply (falling back to the declared default where you do not).
Declaring variables
Reference a variable in the html (or text) body with triple braces, e.g. {{{PRODUCT}}}, and declare it in the variables array when you create the template. A template may contain up to 50 variables.
keystringrequiredThe variable name referenced in the body. We recommend uppercase (e.g. PRODUCT_NAME).
typestringrequiredEither string or number.
fallback_valuestring | numberoptionalUsed when you do not supply a value at send time. Must match type. If omitted, a value is required on every send.
import { MailBlastr } from 'mailblastr';
const mb = new MailBlastr('mb_xxxxxxxxx');
const { data, error } = await mb.templates.create({
"name": "order-confirmation",
"html": "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
"variables": [
{ "key": "PRODUCT", "type": "string", "fallback_value": "item" },
{ "key": "PRICE", "type": "number", "fallback_value": 25 }
]
});
console.log({ data, error });key: FIRST_NAME, LAST_NAME, EMAIL, UNSUBSCRIBE_URL, contact, and this.Fallback values
A fallback value is used whenever you do not pass a value for that variable at send time. If a variable has no fallback, you must supply a value on every send or the request is rejected — so set fallbacks for any variable that is not always present.
Sending with variables
To send with a template, reference the published template by id and pass a variables object. Both POST /emails and POST /emails/batch accept a template.
import { MailBlastr } from 'mailblastr';
const mb = new MailBlastr('mb_xxxxxxxxx');
const { data, error } = await mb.emails.send({
"from": "Acme <hello@yourdomain.com>",
"to": ["delivered@example.com"],
"subject": "Your order",
"template": {
"id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
"variables": { "PRODUCT": "Laptop" }
}
});
console.log({ data, error });template, you cannot also pass html or text in the same request — doing so returns a validation_error. The request’s from, subject, and reply_to override the template’s defaults; if the template sets no default for one of those, you must provide it in the request.