# Email renderers

An email renderer plugin is a [plugin](https://developer.mediarithmics.io/advanced-usages/plugins) that can be associated to an email template, allowing you to customize the rendering of the template.

{% hint style="success" %}
If you don't know what a plugin is, you can find [complete documentation in the specific section.](https://developer.mediarithmics.io/advanced-usages/plugins)
{% endhint %}

{% hint style="info" %}
If you're looking to make a connection with your email router, you should look at the [Email router](https://developer.mediarithmics.io/advanced-usages/automations/email-routers) plugin type.
{% endhint %}

## Endpoints to implement

Email renderers need to implement only one endpoint.

## Send email contents to the renderer

<mark style="color:green;">`POST`</mark> `myworker/v1/email_contents`

This endpoint is called just before the email is sent. The email renderer replies to the request with the email content. There is no particular requirement on the latency, however, the best practice is to maintain a rendering latency below 200 ms.

#### Request Body

| Name                      | Type   | Description                                                                                 |
| ------------------------- | ------ | ------------------------------------------------------------------------------------------- |
| email\_tracking\_url      | string | The URL of the pixel tracking for view event to be inserted in the email content.           |
| click\_urls               | array  | The URLs to prepend the click through URL of the email content, see below.                  |
| user\_data\_bag           | object | Customizable object.                                                                        |
| user\_identifiers         | object | The available user identifiers for the user.                                                |
| campaign\_technical\_anme | string | The campaign technical name.                                                                |
| campaign\_id              | string | The ID of the campaign.                                                                     |
| creative\_id              | string | The ID of the email template.                                                               |
| context                   | string | The call context. One of `LIVE`, `STAGE` or `PREVIEW`.                                      |
| call\_id                  | string | The email call ID.                                                                          |
| email\_renderer\_id       | string | The ID of the email renderer plugin instance. **Used to retrieve the instance properties.** |

{% tabs %}
{% tab title="200 The reply contains a PluginEmailMeta, a PluginEmailContent and a PluginEmailData objects." %}

```javascript
{
    "meta": {
        "from_name": "string",
        "to_email": "string",
        "to_name": "string",
        "reply_to": "string",
        "subject_line": "string"
    },
    "content": {
        "html": "string",
        "text": "string"
    },
    "data": {}
}
```

{% endtab %}
{% endtabs %}

See [Plugin Instances ](https://developer.mediarithmics.io/plugins#instances)to learn why you should use the `email_renderer_id` parameter to retrieve the instance properties.

{% hint style="warning" %}
About `click_urls`: when constructing the final URL, it's essential that you properly URL encode the click URLs. For example, if you have `List("http://url1/?redirect=", "`[`http://url2/?redirect=`](http://url2/?redirect=)`")` and a destination URL equal to `http://dest/`, the result must be equal to `http://url1/?redirect=http%3A%2F%2Furl2%2F%3Fredirect%3Dhttp%253A%252F%252Fdest%252F` which is `http://url1/?redirect=url_encode(http://url2/?redirect=url_encode(http://dest/))`
{% endhint %}

### PluginEmailMeta

| Field         | Type   | Description                                                         |
| ------------- | ------ | ------------------------------------------------------------------- |
| from\_name    | String |                                                                     |
| to\_email     | String |                                                                     |
| to\_name      | String |                                                                     |
| reply\_to     | String |                                                                     |
| subject\_line | String | The subject line, overriding the email campaign subject if defined. |

### PluginEmailContent

| Field | Type              | Description                    |
| ----- | ----------------- | ------------------------------ |
| html  | String (optional) | The html content of the email. |
| text  | String (optional) | The text content of the email. |

### PluginEmailData

This object is customizable.

## Available outbound services

The code of the email renderer can call the following API endpoints to retrieve[ its instance context](https://developer.mediarithmics.io/plugins#instances).

## Retrieve the instance properties

<mark style="color:blue;">`GET`</mark> `https://api.mediarithmics.com/v1/creatives/:id/renderer_properties`

Get the properties associated with the email renderer plugin instance.

#### Path Parameters

| Name | Type   | Description                                                                                           |
| ---- | ------ | ----------------------------------------------------------------------------------------------------- |
| id   | string | ID of the email renderer plugin instance, typically the`email_renderer_id` from the incoming request. |

{% tabs %}
{% tab title="200 " %}

```javascript
{
  "status": "ok",
  "data": [
    {
      "technical_name": "provider",
      "value": { "value": "mediarithmics" },
      "property_type": "STRING",
      "origin": "PLUGIN_STATIC",
      "writable": false,
      "deletable": false
    },
    {
      "technical_name": "name",
      "value": { "value": "Email renderer example" },
      "property_type": "STRING",
      "origin": "PLUGIN_STATIC",
      "writable": false,
      "deletable": false
    }
  ]
}
```

{% endtab %}
{% endtabs %}

## Creating an email router plugin

See the [plugins](https://developer.mediarithmics.io/advanced-usages/plugins) documentation to see [how plugins are created and deployed](https://developer.mediarithmics.io/advanced-usages/plugins).

{% hint style="success" %}
An email renderer plugin has the `EMAIL_TEMPLATE_RENDERER` plugin type. Its group id should be `{domain.organisation.email-renderer}` (for example `com.mediarithmics.email-renderer`).

Its artifact id should be the name of the email renderer plugin, i.e. `example-email-renderer`.
{% endhint %}

Use our [Plugin SDK](https://developer.mediarithmics.io/resources/tools-and-libraries/plugin-sdk) to create your email renderer plugin in Node.js: the required routes are already defined and you only have to override specific functions.

{% hint style="info" %}
You can find a sample email renderer plugin [in the examples folder of the plugin SDK](https://github.com/MEDIARITHMICS/plugins-nodejs-sdk/tree/master/examples/activity-analyzer).
{% endhint %}

We can provide you with a *Hello World* project using our SDK. Please contact your support to obtain access to it.

The project structure and files work as [with every other plugin](https://developer.mediarithmics.io/advanced-usages/plugins/creation).

### Interfaces to implement

Your should extend `EmailRendererPlugin` class and implement the `onEmailContents` function from the plugin SDK.

The `onEmailContents` function is called just before the email is sent. It is responsible for providing the email content to the router.

{% hint style="warning" %}
Don't forget to catch your errors. You should log / respond with the appropriate message to facilitate debugging.
{% endhint %}

```javascript
import {core} from '@mediarithmics/plugins-nodejs-sdk';
import {EmailRenderRequest} from '@mediarithmics/plugins-nodejs-sdk/src/mediarithmics/api/plugin/emailtemplaterenderer/EmailRendererRequestInterface';
import {EmailRendererPluginResponse} from '@mediarithmics/plugins-nodejs-sdk/src/mediarithmics/api/plugin/emailtemplaterenderer/EmailRendererPluginResponse';
import {EmailRendererBaseInstanceContext} from '@mediarithmics/plugins-nodejs-sdk/lib/mediarithmics';

export interface ExampleEmailRendererConfigurationFileProperties {
  apiToken: string;
}

export class ExampleEmailRenderer extends core.EmailRendererPlugin {
  constructor(enableThrottling = false) {
    super(enableThrottling);
  }

  protected async onEmailContents(
      request: EmailRenderRequest,
      instanceContext: EmailRendererBaseInstanceContext
  ): Promise<EmailRendererPluginResponse> {

    // do stuff

    return {
      meta: {}, // use this to set email addresses, subject, ...
      content: {}, // use this to set content
      data: {} // with this you can provide additional data to the email router
    };
  }
}
```

## Debugging

### Plugin logs and metrics

You can monitor email router plugins[ as you do with all plugins](https://developer.mediarithmics.io/advanced-usages/plugins/monitoring).

## Creating a new email template associated to the renderer

## Create an email template

<mark style="color:green;">`POST`</mark> `https://api.mediarithmics.com/v1/email_templates`

#### Request Body

| Name                   | Type   | Description                        |
| ---------------------- | ------ | ---------------------------------- |
| type                   | string | "EMAIL\_TEMPLATE"                  |
| renderer\_group\_id    | string |                                    |
| renderer\_artifact\_id | string |                                    |
| organisation\_id       | string | The ID of the organisation         |
| name                   | string | The name of the template.          |
| editor\_group\_id      | string | "com.mediarithmics.template.email" |
| editor\_artifact\_id   | string | "default\_editor"                  |

{% tabs %}
{% tab title="200 " %}

```
{
    "status": "ok",
    "data": {
        "type": "EMAIL_TEMPLATE",
        "id": "123",
        "organisation_id": "123",
        "name": "Test email with renderer",
        "technical_name": null,
        "archived": false,
        "editor_version_id": "1020",
        "editor_version_value": "1.0.0",
        "editor_group_id": "com.mediarithmics.template.email",
        "editor_artifact_id": "default-editor",
        "editor_plugin_id": "1015",
        "renderer_version_id": "123",
        "renderer_version_value": "1.0.0",
        "renderer_group_id": "com.test-organisation.email-renderer",
        "renderer_artifact_id": "test-organisation-example-email-renderer",
        "renderer_plugin_id": "123",
        "creation_date": 1618003512488,
        "subtype": null
    }
}
```

{% endtab %}
{% endtabs %}
