> ## Documentation Index
> Fetch the complete documentation index at: https://docs.emailr.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Using Templates

> Learn how to use templates to send emails.

Templates are stored on Emailr and can be referenced when you send transactional emails. With Templates, define the structure and layout of a message and optionally include custom variables which will be replaced with the actual values when sending the email.

Send only the Template `id` and `variables` (instead of sending the HTML), and Emailr will render your final email and send it out.

<CodeGroup>
  ```ts Node.js {8-14} theme={null} theme={null}
  import { Emailr } from 'emailr';

  const emailr = new Emailr('em_xxxxxxxxx');

  await emailr.emails.send({
    from: 'Acme <onboarding@emailr.dev>',
    to: 'delivered@emailr.dev',
    template: {
      id: 'order-confirmation',
      variables: {
        PRODUCT: 'Vintage Macintosh',
        PRICE: 499,
      },
    },
  });
  ```

  ```php PHP {7-12} theme={null} theme={null}
  $emailr = Emailr::client('em_xxxxxxxxx');

  $emailr->emails->send([
    'from' => 'Acme <onboarding@emailr.dev>',
    'to' => ['delivered@emailr.dev'],
    'subject' => 'hello world',
    'template'=> [
      'id' => 'f3b9756c-f4f4-44da-bc00-9f7903c8a83f',
      'variables' => [
        'PRODUCT' => 'Vintage Macintosh',
        'PRICE' => 499,
      ]
    ]
  ]);
  ```

  ```python Python {8-14} theme={null} theme={null}
  import emailr

  emailr.api_key = "em_xxxxxxxxx"

  emailr.Emails.send({
    "from": "Acme <onboarding@emailr.dev>",
    "to": "delivered@emailr.dev",
    "template": {
      "id": "order-confirmation",
      "variables": {
        "PRODUCT": "Vintage Macintosh",
        "PRICE": 499
      }
    }
  })
  ```

  ```ruby Ruby {8-14} theme={null} theme={null}
  require "emailr"

  Emailr.api_key = "em_xxxxxxxxx"

  Emailr::Emails.send({
    from: "Acme <onboarding@emailr.dev>",
    to: "delivered@emailr.dev",
    template: {
      id: "order-confirmation",
      variables: {
        PRODUCT: "Vintage Macintosh",
        PRICE: 499
      }
    }
  })
  ```

  ```go Go {8-14} theme={null} theme={null}
  import "github.com/emailr/emailr-go/v3"

  client := emailr.NewClient("em_xxxxxxxxx")

  params := &emailr.SendEmailRequest{
    From: "Acme <onboarding@emailr.dev>",
    To: []string{"delivered@emailr.dev"},
    Template: &emailr.EmailTemplate{
      Id: "order-confirmation",
      Variables: map[string]interface{}{
        "PRODUCT": "Vintage Macintosh",
        "PRICE": 499,
      },
    },
  }

  email, err := client.Emails.Send(params)
  ```

  ```rust Rust {7-13} theme={null} theme={null}
  use emailr_rs::{types::SendEmailOptions, Emailr, Result};

  #[tokio::main]
  async fn main() -> Result<()> {
    let emailr = Emailr::new("em_xxxxxxxxx");

    let variables = serde_json::json!({
      "PRODUCT": "Vintage Macintosh",
      "PRICE": 499
    });

    let opts = SendEmailOptions::new("Acme <onboarding@emailr.dev>", vec!["delivered@emailr.dev"])
      .with_template("order-confirmation", variables);

    let _email = emailr.emails.send(opts).await?;

    Ok(())
  }
  ```

  ```java Java {3-5,10-13} theme={null} theme={null}
  Emailr emailr = new Emailr("em_xxxxxxxxx");

  Map<String, Object> variables = new HashMap<>();
  variables.put("PRODUCT", "Vintage Macintosh");
  variables.put("PRICE", 499);

  SendEmailOptions params = SendEmailOptions.builder()
    .from("Acme <onboarding@emailr.dev>")
    .to(Arrays.asList("customer@email.com"))
    .template(Template.builder()
      .id("order-confirmation")
      .variables(variables)
      .build())
    .build();

  SendEmailResponseSuccess data = emailr.emails().send(params);
  ```

  ```csharp .NET {5-9,17-20} theme={null} theme={null}
  using Emailr;

  IEmailr emailr = EmailrClient.Create("em_xxxxxxxxx");

  var variables = new Dictionary<string, object>
  {
    { "PRODUCT", "Vintage Macintosh" },
    { "PRICE", 499 }
  };

  var resp = await emailr.EmailSendAsync(
    new EmailMessage()
    {
      From = "Acme <onboarding@emailr.dev>",
      To = new[] { "delivered@emailr.dev" },
      Template = new EmailMessageTemplate()
      {
        TemplateId = new Guid( "b6d24b8e-af0b-4c3c-be0c-359bbd97381e" ),
        Variables = variables
      }
    }
  );

  Console.WriteLine($"Email Id={resp.Content}");
  ```

  ```bash cURL {7-13} theme={null} theme={null}
  curl -X POST 'https://api.emailr.dev/emails' \
    -H 'Authorization: Bearer em_xxxxxxxxx' \
    -H 'Content-Type: application/json' \
    -d $'{
      "from": "Acme <onboarding@emailr.dev>",
      "to": "delivered@emailr.dev",
      "template": {
        "id": "order-confirmation",
        "variables": {
          "PRODUCT": "Vintage Macintosh",
          "PRICE": 499
        }
      }
  }'
  ```
</CodeGroup>

Use Templates for transactional emails like:

* Login/Auth
* Onboarding
* Ecommerce
* Notifications
* Automations

## Add a Template

You can add a Template:

* [In the dashboard](#add-a-template-in-the-dashboard)
* [From an existing email](#add-a-template-from-an-existing-email)
* [Using the API](#create-a-template-by-using-the-api)

### Add a Template in the dashboard

The [Templates dashboard](https://app.emailr.dev/dashboard/templates) shows all existing templates. Click **Create template** to start a new Template.

<img alt="Screenshot placeholder" src="https://mintcdn.com/emailrdev/tSm2WeCvU8-lHmTx/images/placeholder.svg?fit=max&auto=format&n=tSm2WeCvU8-lHmTx&q=85&s=93891ced94bad8f8c38f90b5be99f73c" width="800" height="450" data-path="images/placeholder.svg" />

### Add a Template from an existing email

You can create a Template from an existing Broadcast. Locate your desired Broadcast in the [Broadcast dashboard](https://app.emailr.dev/dashboard/broadcasts), click the more options button <span className="inline-block align-middle"><Icon icon="ellipsis" iconType="solid" /></span>, and choose **Clone as template**.

<img alt="Screenshot placeholder" src="https://mintcdn.com/emailrdev/tSm2WeCvU8-lHmTx/images/placeholder.svg?fit=max&auto=format&n=tSm2WeCvU8-lHmTx&q=85&s=93891ced94bad8f8c38f90b5be99f73c" width="800" height="450" data-path="images/placeholder.svg" />

You can also import an HTML or [React Email](https://react.email) file to create a Template from your existing code. Create a new Template, then paste or drag in your HTML or React Email content.

### Create a Template by using the API

You can also programmatically create a Template by using the API. The payload can optionally include variables to be used in the Template.

<CodeGroup>
  ```ts Node.js theme={null} theme={null}
  import { Emailr } from 'emailr';

  const emailr = new Emailr('em_xxxxxxxxx');

  await emailr.templates.create({
    name: 'order-confirmation',
    from: 'Emailr Store <store@emailr.dev>',
    subject: 'Thanks for your order!',
    html: '<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>',
    variables: [
      {
        key: 'PRODUCT',
        type: 'string',
        fallbackValue: 'item',
      },
      {
        key: 'PRICE',
        type: 'number',
        fallbackValue: 20,
      },
    ],
  });
  ```

  ```php PHP theme={null} theme={null}
  $emailr = Emailr::client('em_xxxxxxxxx');

  $emailr->templates->create([
    'name' => 'order-confirmation',
    'from' => 'Emailr Store <store@emailr.dev>',
    'subject' => 'Thanks for your order!',
    'html' => '<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>',
    'variables' => [
      [
        'key' => 'PRODUCT',
        'type' => 'string',
        'fallback_value' => 'item'
      ],
      [
        'key' => 'PRICE',
        'type' => 'number',
        'fallback_value' => 49.99
      ]
    ]
  ]);
  ```

  ```py Python theme={null} theme={null}
  import emailr

  emailr.api_key = "em_xxxxxxxxx"

  params: emailr.Templates.CreateParams = {
      "name": "order-confirmation",
      "from": "Emailr Store <store@emailr.dev>",
      "subject": "Thanks for your order!",
      "html": "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
      "variables": [
          {
              "key": "PRODUCT",
              "type": "string",
              "fallback_value": "item",
          },
          {
              "key": "PRICE",
              "type": "number",
              "fallback_value": 20,
          },
      ],
  }

  emailr.Templates.create(params)
  ```

  ```ruby Ruby theme={null} theme={null}
  require "emailr"

  Emailr.api_key = "em_xxxxxxxxx"

  Emailr::Templates.create(
    name: "order-confirmation",
    from: "Emailr Store <store@emailr.dev>",
    subject: "Thanks for your order!",
    html: "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
    variables: [
      {
        key: "PRODUCT",
        type: "string",
        fallback_value: "item"
      },
      {
        key: "PRICE",
        type: "number",
        fallback_value: 20
      }
    ]
  )
  ```

  ```go Go theme={null} theme={null}
  import "github.com/emailr/emailr-go/v3"

  client := emailr.NewClient("em_xxxxxxxxx")

  template, err := client.Templates.Create(&emailr.CreateTemplateRequest{
  	Name:    "order-confirmation",
  	From:    "Emailr Store <store@emailr.dev>",
  	Subject: "Thanks for your order!",
  	Html:    "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
  	Variables: []*emailr.TemplateVariable{
  		{
  			Key:           "PRODUCT",
  			Type:          emailr.VariableTypeString,
  			FallbackValue: "item",
  		},
  		{
  			Key:           "PRICE",
  			Type:          emailr.VariableTypeNumber,
  			FallbackValue: 20,
  		},
  	},
  })
  ```

  ```rust Rust theme={null} theme={null}
  use emailr_rs::{
    types::{CreateTemplateOptions, Variable, VariableType},
    Emailr, Result,
  };

  #[tokio::main]
  async fn main() -> Result<()> {
    let emailr = Emailr::new("em_xxxxxxxxx");

    let name = "order-confirmation";
    let from = "Emailr Store <store@emailr.dev>";
    let subject = "Thanks for your order!";
    let html = "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>";

    let variables = [
      Variable::new("PRODUCT", VariableType::String).with_fallback("item"),
      Variable::new("PRICE", VariableType::Number).with_fallback(20)
    ];

    let opts = CreateTemplateOptions::new(name, from, subject)
      .with_html(html)
      .with_variables(&variables);

    let template = emailr.templates.create(opts).await?;

    let _published = emailr.templates.publish(&template.id).await?;

    Ok(())
  }
  ```

  ```java Java theme={null} theme={null}
  import com.emailr.*;

  public class Main {
      public static void main(String[] args) {
          Emailr emailr = new Emailr("em_xxxxxxxxx");

          CreateTemplateOptions params = CreateTemplateOptions.builder()
                  .name("order-confirmation")
                  .from("Emailr Store <store@emailr.dev>")
                  .subject("Thanks for your order!")
                  .html("<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>")
                  .addVariable(new Variable("PRODUCT", VariableType.STRING, "item"))
                  .addVariable(new Variable("PRICE", VariableType.NUMBER, 20))
                  .build();

          CreateTemplateResponseSuccess data = emailr.templates().create(params);
      }
  }
  ```

  ```csharp .NET theme={null} theme={null}
  using Emailr;

  IEmailr emailr = EmailrClient.Create("em_xxxxxxxxx");

  var variables = new List<TemplateVariable>
  {
    new TemplateVariable() {
      Key = "PRODUCT",
      Type = TemplateVariableType.String,
      Default = "item",
    },
    new TemplateVariable() {
      Key = "PRICE",
      Type = TemplateVariableType.Number,
      Default = 20,
    },
  };

  var resp = await emailr.TemplateCreateAsync(
    new TemplateData()
    {
      Name = "order-confirmation",
      From = "Emailr Store <store@emailr.dev>",
      Subject = "Thanks for your order!",
      HtmlBody = "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
      Variables = variables,
    }
  );

  Console.WriteLine($"Template Id={resp.Content}");
  ```

  ```bash cURL theme={null} theme={null}
  curl -X POST 'https://api.emailr.dev/templates' \
       -H 'Authorization: Bearer em_xxxxxxxxx' \
       -H 'Content-Type: application/json' \
       -d $'{
    "name": "order-confirmation",
    "from": "Emailr Store <store@emailr.dev>",
    "subject": "Thanks for your order!",
    "html": "<p>Name: {{{PRODUCT}}}</p><p>Total: {{{PRICE}}}</p>",
    "variables": [
      {
        "key": "PRODUCT",
        "type": "string",
        "fallback_value": "item"
      },
      {
        "key": "PRICE",
        "type": "number",
        "fallback_value": 20
      }
    ]
  }'
  ```
</CodeGroup>

View the [API reference](/docs/api/templates/create-template) for more details.

## Add Variables

Each Template may contain up to 20 variables.

To add a custom variable, select **Variable** in the commands palette or type `{{` in the editor. Define the `name`, `type`, and `fallback_value` (optional).

<img alt="Screenshot placeholder" src="https://mintcdn.com/emailrdev/tSm2WeCvU8-lHmTx/images/placeholder.svg?fit=max&auto=format&n=tSm2WeCvU8-lHmTx&q=85&s=93891ced94bad8f8c38f90b5be99f73c" width="800" height="450" data-path="images/placeholder.svg" />

You can also define custom variables [via the API](/docs/guides/dashboard/templates/template-variables).

<Info>
  The following variable names are reserved and cannot be used: `FIRST_NAME`,
  `LAST_NAME`, `EMAIL`, `EMAILR_UNSUBSCRIBE_URL`, `contact`,`this`.
</Info>

[Learn more about working with variables](/docs/guides/dashboard/templates/template-variables).

## Send Test Emails

You can send test emails to your inbox to preview your Template before sending it to your audience. Provide variable values to test the rendered Template in your inbox.

<img alt="Video placeholder" src="https://mintcdn.com/emailrdev/tSm2WeCvU8-lHmTx/images/placeholder.svg?fit=max&auto=format&n=tSm2WeCvU8-lHmTx&q=85&s=93891ced94bad8f8c38f90b5be99f73c" width="800" height="450" data-path="images/placeholder.svg" />

## Publish a Template

By default, Templates are in a **draft** state. To use a Template to send emails, you must first **publish** it via the dashboard or [via the API](/docs/api/templates/publish-template).

<img alt="Screenshot placeholder" src="https://mintcdn.com/emailrdev/tSm2WeCvU8-lHmTx/images/placeholder.svg?fit=max&auto=format&n=tSm2WeCvU8-lHmTx&q=85&s=93891ced94bad8f8c38f90b5be99f73c" width="800" height="450" data-path="images/placeholder.svg" />

For a more streamlined flow, create and publish a template in a single step.

```ts Node.js theme={null} theme={null}
await emailr.templates.create({ ... }).publish();
```

Once a Template is published, you can continue to edit it without impacting existing emails sent using the Template. As you work, your changes are saved as a draft, although you can also manually save drafts by pressing <kbd>Cmd</kbd> + <kbd>S</kbd> (Mac) or <kbd>Ctrl</kbd> + <kbd>S</kbd> (Windows).

Only after publishing again will the changes be reflected in emails using the Template.

[Learn more about Template version history](/docs/guides/dashboard/templates/version-history).

## Send Emails with Templates

When sending a transactional email, you can reference your Template and include your variables in the call. The Template variables will be replaced with the actual values.

<CodeGroup>
  ```ts Node.js {8-14} theme={null} theme={null}
  import { Emailr } from 'emailr';

  const emailr = new Emailr('em_xxxxxxxxx');

  await emailr.emails.send({
    from: 'Acme <onboarding@emailr.dev>',
    to: 'delivered@emailr.dev',
    template: {
      id: 'order-confirmation',
      variables: {
        PRODUCT: 'Vintage Macintosh',
        PRICE: 499,
      },
    },
  });
  ```

  ```php PHP {7-12} theme={null} theme={null}
  $emailr = Emailr::client('em_xxxxxxxxx');

  $emailr->emails->send([
    'from' => 'Acme <onboarding@emailr.dev>',
    'to' => ['delivered@emailr.dev'],
    'subject' => 'hello world',
    'template'=> [
      'id' => 'f3b9756c-f4f4-44da-bc00-9f7903c8a83f',
      'variables' => [
        'PRODUCT' => 'Vintage Macintosh',
        'PRICE' => 499,
      ]
    ]
  ]);
  ```

  ```python Python {8-14} theme={null} theme={null}
  import emailr

  emailr.api_key = "em_xxxxxxxxx"

  emailr.Emails.send({
    "from": "Acme <onboarding@emailr.dev>",
    "to": "delivered@emailr.dev",
    "template": {
      "id": "order-confirmation",
      "variables": {
        "PRODUCT": "Vintage Macintosh",
        "PRICE": 499
      }
    }
  })
  ```

  ```ruby Ruby {8-14} theme={null} theme={null}
  require "emailr"

  Emailr.api_key = "em_xxxxxxxxx"

  Emailr::Emails.send({
    from: "Acme <onboarding@emailr.dev>",
    to: "delivered@emailr.dev",
    template: {
      id: "order-confirmation",
      variables: {
        PRODUCT: "Vintage Macintosh",
        PRICE: 499
      }
    }
  })
  ```

  ```go Go {8-14} theme={null} theme={null}
  import "github.com/emailr/emailr-go/v3"

  client := emailr.NewClient("em_xxxxxxxxx")

  params := &emailr.SendEmailRequest{
    From: "Acme <onboarding@emailr.dev>",
    To: []string{"delivered@emailr.dev"},
    Template: &emailr.EmailTemplate{
      Id: "order-confirmation",
      Variables: map[string]interface{}{
        "PRODUCT": "Vintage Macintosh",
        "PRICE": 499,
      },
    },
  }

  email, err := client.Emails.Send(params)
  ```

  ```rust Rust {7-13} theme={null} theme={null}
  use emailr_rs::{types::SendEmailOptions, Emailr, Result};

  #[tokio::main]
  async fn main() -> Result<()> {
    let emailr = Emailr::new("em_xxxxxxxxx");

    let variables = serde_json::json!({
      "PRODUCT": "Vintage Macintosh",
      "PRICE": 499
    });

    let opts = SendEmailOptions::new("Acme <onboarding@emailr.dev>", vec!["delivered@emailr.dev"])
      .with_template("order-confirmation", variables);

    let _email = emailr.emails.send(opts).await?;

    Ok(())
  }
  ```

  ```java Java {3-5,10-13} theme={null} theme={null}
  Emailr emailr = new Emailr("em_xxxxxxxxx");

  Map<String, Object> variables = new HashMap<>();
  variables.put("PRODUCT", "Vintage Macintosh");
  variables.put("PRICE", 499);

  SendEmailOptions params = SendEmailOptions.builder()
    .from("Acme <onboarding@emailr.dev>")
    .to(Arrays.asList("customer@email.com"))
    .template(Template.builder()
      .id("order-confirmation")
      .variables(variables)
      .build())
    .build();

  SendEmailResponseSuccess data = emailr.emails().send(params);
  ```

  ```csharp .NET {5-9,17-20} theme={null} theme={null}
  using Emailr;

  IEmailr emailr = EmailrClient.Create("em_xxxxxxxxx");

  var variables = new Dictionary<string, object>
  {
    { "PRODUCT", "Vintage Macintosh" },
    { "PRICE", 499 }
  };

  var resp = await emailr.EmailSendAsync(
    new EmailMessage()
    {
      From = "Acme <onboarding@emailr.dev>",
      To = new[] { "delivered@emailr.dev" },
      Template = new EmailMessageTemplate()
      {
        TemplateId = new Guid( "b6d24b8e-af0b-4c3c-be0c-359bbd97381e" ),
        Variables = variables,
      }
    }
  );

  Console.WriteLine($"Email Id={resp.Content}");
  ```

  ```bash cURL {7-13} theme={null} theme={null}
  curl -X POST 'https://api.emailr.dev/emails' \
    -H 'Authorization: Bearer em_xxxxxxxxx' \
    -H 'Content-Type: application/json' \
    -d $'{
      "from": "Acme <onboarding@emailr.dev>",
      "to": "delivered@emailr.dev",
      "template": {
        "id": "order-confirmation",
        "variables": {
          "PRODUCT": "Vintage Macintosh",
          "PRICE": 499
        }
      }
  }'
  ```
</CodeGroup>

Learn more about [sending emails](/docs/api/emails/send-email) or sending [batch emails](/docs/api/emails/send-email) with Templates via the API.

## Duplicate a Template

You can also duplicate an existing Template in the dashboard or [via the API](/docs/api/templates/create-template).

<img alt="Screenshot placeholder" src="https://mintcdn.com/emailrdev/tSm2WeCvU8-lHmTx/images/placeholder.svg?fit=max&auto=format&n=tSm2WeCvU8-lHmTx&q=85&s=93891ced94bad8f8c38f90b5be99f73c" width="800" height="450" data-path="images/placeholder.svg" />

<Info>
  <p>
    You can create a Template from an existing Broadcast. Locate your desired
    Broadcast in the [Broadcast dashboard](https://app.emailr.dev/dashboard/broadcasts), click
    the more options button{' '}

    <span className="inline-block align-middle">
      <Icon icon="ellipsis" iconType="solid" />
    </span>

    , and choose **Clone as template**.
  </p>
</Info>

## Delete a Template

You can delete a Template via the dashboard by clicking on the **Delete** button or [via the API](/docs/api/templates/delete-template).

<img alt="Screenshot placeholder" src="https://mintcdn.com/emailrdev/tSm2WeCvU8-lHmTx/images/placeholder.svg?fit=max&auto=format&n=tSm2WeCvU8-lHmTx&q=85&s=93891ced94bad8f8c38f90b5be99f73c" width="800" height="450" data-path="images/placeholder.svg" />

## Validation errors

When sending an email using a Template, the Template variables will be replaced with the actual values. If a variable is not provided, the fallback value will be used. If no fallback value is provided, the email will not be sent and a validation error will be returned.

[See the API reference for more details](/docs/api/templates/create-template) or the [errors reference](/docs/api/errors).
