# Email routers

An email router plugin is a [plugin](https://developer.mediarithmics.io/advanced-usages/plugins) that can be associated to a send email node in an automation, allowing you to manage the connection with an external email router.

{% 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 customizing your emails, you should look at the [email renderer](https://developer.mediarithmics.io/advanced-usages/automations/email-renderers) plugin type.
{% endhint %}

## Endpoints to implement

Email routers need to implement two endpoints.

## Send an email to the router

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

This endpoint is called any time a user goes through a send email node in an automation.

#### Request Body

| Name              | Type   | Description                                                                               |
| ----------------- | ------ | ----------------------------------------------------------------------------------------- |
| data              | object | PluginEmailData. See Email renderer.                                                      |
| content           | object | PluginEmailContent. See Email renderer.                                                   |
| meta              | object | PluginEmailMeta. See Email renderer.                                                      |
| user\_identifiers | object | The available user identifiers for the user.                                              |
| datamart\_id      | string | The ID of the datamart.                                                                   |
| blast\_id         | string | The ID of the campaign blast.                                                             |
| campaign\_id      | string | The ID of the campaign.                                                                   |
| creative\_id      | string | The ID of the email template.                                                             |
| context           | string | The email call context. One of `LIVE`, `STAGE` or `PREVIEW`.                              |
| call\_id          | string | The email call ID.                                                                        |
| email\_router\_id | string | The ID of the email router plugin instance. **Used to retrieve the instance properties.** |

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

```javascript
{
    "result": true
}
```

{% endtab %}

{% tab title="500 " %}

```javascript
{
  "error": "..."
}
```

{% endtab %}
{% endtabs %}

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

## Check email channel

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

The endpoint is called before sending an email to do preliminary checks. In particular, to check if it is possible to send an email with the provided identifiers.

#### Request Body

| Name              | Type   | Description                                                                               |
| ----------------- | ------ | ----------------------------------------------------------------------------------------- |
| user\_identifiers | object | The available user identifiers for the user.                                              |
| email\_router\_id | string | The ID of the email router plugin instance. **Used to retrieve the instance properties.** |

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

```
{
    "result": true
}
```

{% endtab %}

{% tab title="500 " %}

```
{
    "error": "..."
}
```

{% endtab %}
{% endtabs %}

## Available outbound services

The code of the email router can call the following API endpoint 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/email_routers/:id/properties`

Get the properties associated with the email router plugin instance.

#### Path Parameters

| Name | Type   | Description                                                                                       |
| ---- | ------ | ------------------------------------------------------------------------------------------------- |
| id   | string | ID of the email router plugin instance, typically the`email_router_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": true,
      "deletable": false
    },
    {
      "technical_name": "name",
      "value": { "value": "Email router 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 router plugin has the `EMAIL_ROUTER` plugin type. Its group id should be `{domain.organisation.email-router}` (for example `com.mediarithmics.email-router`).

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

Use our [Plugin SDK](https://developer.mediarithmics.io/resources/tools-and-libraries/plugin-sdk) to create your email router 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 router 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 in order to have 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 `EmailRouterPlugin` class and implement the `onEmailRouting` and `onEmailCheck` functions from the plugin SDK.

The `onEmailRouting` function is called every time a user runs through a send email node in an automation. It is responsible for sending the email.

{% 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';

export class MyEmailRouterPlugin extends core.EmailRouterPlugin {
  constructor() {
    super();
  }

  protected async onEmailRouting(
    request: core.EmailRoutingRequest,
    instanceContext: core.EmailRouterBaseInstanceContext
  ): Promise<core.EmailRoutingPluginResponse> {
    const identifier = request.user_identifiers.find(identifier => {
      return (
        identifier.type === 'USER_EMAIL' &&
        !!(identifier as core.UserEmailIdentifierInfo).email
      );
    }) as core.UserEmailIdentifierInfo;

    if (!identifier) {
      throw Error('No clear email identifiers were provided');
    }

    const payload = this.buildMyEmailRouterPayload(
      request.creative_id,
      identifier.hash
    );

    await this.sendToMyEmailRouter(payload); 
    return { result: true };
  }

  protected async onEmailCheck(
    request: core.CheckEmailsRequest,
    instanceContext: core.EmailRouterBaseInstanceContext
  ): Promise<core.CheckEmailsPluginResponse> {
    // If your router does not have a route to check its status, you can use this
    return Promise.resolve({result: true});
  }
}
```

## 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).
