# 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](https://www.mailblastr.com/docs/api/templates-create). A template may contain up to **50** variables.

**Variable fields**

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `key` | string | Yes | The variable name referenced in the body. We recommend uppercase (e.g. `PRODUCT_NAME`). |
| `type` | string | Yes | Either `string` or `number`. |
| `fallback_value` | string | number | No | Used when you do not supply a value at send time. Must match `type`. If omitted, a value is required on every send. |

**Node.js**

```js
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 });
```

**Ruby**

```ruby
require "mailblastr"

Mailblastr.api_key = "mb_xxxxxxxxx"

Mailblastr::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
    }
  ]
})
```

**PHP**

```php
$mailblastr = Mailblastr::client('mb_xxxxxxxxx');

$mailblastr->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
    ]
  ]
]);
```

**Python**

```python
import mailblastr

mailblastr.api_key = "mb_xxxxxxxxx"

mailblastr.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
    }
  ]
})
```

**Go**

```go
package main

import (
    "fmt"
    "io"
    "net/http"
    "strings"
)

func main() {
    req, _ := http.NewRequest("POST", "https://api.mailblastr.com/templates", strings.NewReader(`{
  "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 }
  ]
}`))
    req.Header.Set("Authorization", "Bearer mb_xxxxxxxxx")
    req.Header.Set("Content-Type", "application/json")
    res, _ := http.DefaultClient.Do(req)
    defer res.Body.Close()
    out, _ := io.ReadAll(res.Body)
    fmt.Println(string(out))
}
```

**Rust**

```rust
use reqwest::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let res = Client::new()
        .post("https://api.mailblastr.com/templates")
        .header("Authorization", "Bearer mb_xxxxxxxxx")
        .header("Content-Type", "application/json")
        .body(r#"{
  "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 }
  ]
}"#)
        .send()
        .await?;
    println!("{}", res.text().await?);
    Ok(())
}
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.mailblastr.com/templates"))
    .header("Authorization", "Bearer mb_xxxxxxxxx")
    .header("Content-Type", "application/json")
    .method("POST", HttpRequest.BodyPublishers.ofString("""
{
  "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 }
  ]
}
"""))
    .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
```

**.NET**

```csharp
using System.Net.Http;
using System.Text;

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.mailblastr.com/templates");
request.Headers.Add("Authorization", "Bearer mb_xxxxxxxxx");
request.Content = new StringContent(@"{
  ""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 }
  ]
}", Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
Console.WriteLine(await response.Content.ReadAsStringAsync());
```

**cURL**

```bash
curl -X POST 'https://api.mailblastr.com/templates' \
  -H 'Authorization: Bearer mb_xxxxxxxxx' \
  -H 'Content-Type: application/json' \
  -d '{
  "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 }
  ]
}'
```

**CLI**

```bash
mailblastr 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}]'
```

> **Warning:** These names are reserved and cannot be used as a variable `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](https://www.mailblastr.com/docs/api/emails-send) and [POST /emails/batch](https://www.mailblastr.com/docs/api/emails-batch) accept a template.

**Node.js**

```js
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 });
```

**Ruby**

```ruby
require "mailblastr"

Mailblastr.api_key = "mb_xxxxxxxxx"

Mailblastr::Emails.send({
  "from": "Acme <hello@yourdomain.com>",
  "to": [
    "delivered@example.com"
  ],
  "subject": "Your order",
  "template": {
    "id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    "variables": {
      "PRODUCT": "Laptop"
    }
  }
})
```

**PHP**

```php
$mailblastr = Mailblastr::client('mb_xxxxxxxxx');

$mailblastr->emails->send([
  'from' => "Acme <hello@yourdomain.com>",
  'to' => [
    "delivered@example.com"
  ],
  'subject' => "Your order",
  'template' => [
    'id' => "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    'variables' => [
      'PRODUCT' => "Laptop"
    ]
  ]
]);
```

**Python**

```python
import mailblastr

mailblastr.api_key = "mb_xxxxxxxxx"

mailblastr.Emails.send({
  "from": "Acme <hello@yourdomain.com>",
  "to": [
    "delivered@example.com"
  ],
  "subject": "Your order",
  "template": {
    "id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    "variables": {
      "PRODUCT": "Laptop"
    }
  }
})
```

**Go**

```go
import "github.com/shekhu10/mailblastr-sdks/mailblastr-go"

client := mailblastr.NewClient("mb_xxxxxxxxx")

params := &mailblastr.SendEmailRequest{
    From:    "Acme <hello@yourdomain.com>",
    To:      []string{"delivered@example.com"},
    Subject: "hello world",
    Html:    "<p>it works!</p>",
}
sent, err := client.Emails.Send(params)
```

**Rust**

```rust
use mailblastr::{Mailblastr, CreateEmailBaseOptions};

let mb = Mailblastr::new("mb_xxxxxxxxx");

let email = CreateEmailBaseOptions::new(
    "Acme <hello@yourdomain.com>",
    ["delivered@example.com"],
    "hello world",
).with_html("<p>it works!</p>");
let _sent = mb.emails.send(email).await?;
```

**Java**

```java
import com.mailblastr.*;

Mailblastr mailblastr = new Mailblastr("mb_xxxxxxxxx");

SendEmailRequest request = SendEmailRequest.builder()
    .from("Acme <hello@yourdomain.com>")
    .to("delivered@example.com")
    .subject("hello world")
    .html("<p>it works!</p>")
    .build();
mailblastr.emails().send(request);
```

**.NET**

```csharp
using Mailblastr;

IMailblastr mailblastr = MailblastrClient.Create("mb_xxxxxxxxx");

var resp = await mailblastr.EmailSendAsync(new EmailMessage
{
    From = "Acme <hello@yourdomain.com>",
    To = "delivered@example.com",
    Subject = "hello world",
    HtmlBody = "<p>it works!</p>",
});
```

**cURL**

```bash
curl -X POST 'https://api.mailblastr.com/emails' \
  -H 'Authorization: Bearer mb_xxxxxxxxx' \
  -H 'Content-Type: application/json' \
  -d '{
  "from": "Acme <hello@yourdomain.com>",
  "to": ["delivered@example.com"],
  "subject": "Your order",
  "template": {
    "id": "f3b9756c-f4f4-44da-bc00-9f7903c8a83f",
    "variables": { "PRODUCT": "Laptop" }
  }
}'
```

> **Warning:** When you send a `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.

> **Note:** Only a **published** template can be used to send. See [Version history](https://www.mailblastr.com/docs/templates/version-history) for the draft → publish workflow.
