# Developer Documentation

This is the Encharge Developer Documentation.&#x20;

For our user documentation please check the [Knowledge Base](https://help.encharge.io).

## Getting Started

{% content-ref url="/pages/-LpnMQSQWTzISbnDiegb" %}
[Sending data to your Encharge account](/getting-started/connecting-your-app-to-encharge)
{% endcontent-ref %}

{% content-ref url="/pages/-LpD8FU\_r140UAVqWJop" %}
[Getting Help](/getting-started/getting-help)
{% endcontent-ref %}

## Developer Tools

Encharge provides several tools for developers to make magic happen:

{% content-ref url="/pages/-MJ6b-0KYRN1lZ4cXFTM" %}
[Transactional Email API](/transactional-email-api/overview)
{% endcontent-ref %}

{% content-ref url="/pages/-MPp2AvDus2BKkDDr3Cf" %}
[Personalizing Emails with Liquid](/sending-emails/personalized-emails-with-liquid)
{% endcontent-ref %}


# Sending data to your Encharge account

If you have a software product (SaaS) or a mobile app, you can bring in data from your app to Encharge automatically.

Getting your users and their activity from your app to Encharge is a great way to give super powers to your onboarding and retention efforts.&#x20;

There are three ways to get data in Encharge:&#x20;

* [Segment.com integration](/getting-started/connecting-your-app-to-encharge#segment-com-integration)
* [Ingest API](/getting-started/connecting-your-app-to-encharge/ingest-api)
* [JavaScript tracking](/getting-started/connecting-your-app-to-encharge/javascript-event-tracking)

## Segment.com integration

Sending people and events through Segment works best for when your app already integrates with Segment.

To get started with sending your Segment events to Encharge, open [Your Apps](https://app.encharge.io/apps), and click on the Segment logo.

{% content-ref url="/pages/-MPmg-yIqTngrew5jir2" %}
[Segment.com Integration](/getting-started/connecting-your-app-to-encharge/segment.com)
{% endcontent-ref %}

## Ingest API

The Ingest API lets you create/update people and submit events from your app's backend directly to Encharge.

{% content-ref url="/pages/-LpnQK0i7BmHHQGmr2vs" %}
[Ingest API](/getting-started/connecting-your-app-to-encharge/ingest-api)
{% endcontent-ref %}

## JavaScript tracking

Track events that happen on your app's frontend or on your site using the Encharge Javascript tracking.&#x20;

{% content-ref url="/pages/-LpoAyvUhEY1ofQ6FKny" %}
[JavaScript Event Tracking](/getting-started/connecting-your-app-to-encharge/javascript-event-tracking)
{% endcontent-ref %}


# Ingest API

### Description

The Encharge Ingest API lets you create/update people and submit events from your app's backend directly to Encharge. The API exposes a single endpoint.

See this documentation as a [Postman Collection](https://documenter.getpostman.com/view/460427/SVfNwVFU).&#x20;

{% hint style="danger" %}
Don't use this API, if you are building an integration with Encharge to be used by our mutual customers. For example, if your product is a form builder and you'd like to send leads to Encharge, use the [Rest API](/api-documentation#rest-api). The Ingest API is the wrong tool for the job and will result in poor experience for our mutual users.
{% endhint %}

### Authentication

Get your write key for the Ingest API in [Your Account](https://app.encharge.io/account/info).

### Endpoints

Use the below endpoint to create/update people and submit events from your app's backend directly to Encharge. See below for sample events

## /

<mark style="color:green;">`POST`</mark> `https://ingest.encharge.io/v1/`

Create/update person or record events for existing people.

#### Headers

| Name             | Type   | Description                           |
| ---------------- | ------ | ------------------------------------- |
| X-Encharge-Token | string | Write key for your account.           |
| Content-Type     | string | Content-type must be application/json |

#### Request Body

| Name       | Type   | Description                                                                                                                                                                 |
| ---------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name       | string | Name of your event. If you are using this API to create/update people, you can use "identify" as the event name.                                                            |
| user       | object | Properties for the current user. `email` or `userId` is required to uniquely identify this person. Any other fields in properties will be added as custom fields to people. |
| properties | object | Properties for this event.                                                                                                                                                  |
| sourceIp   | string | IP of the end user, if available.                                                                                                                                           |

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

```
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Send date fields formatted as ISO 8601 datetime values. For example, `2020-10-27T07:58:19+00:00` or `2020-10-27T07:58:19Z`.
{% endhint %}

{% hint style="info" %}
Pass the IP of the user (as property `ip` in the `user` object) to automatically populate the user country and timezone. Alternatively, you might set the `sourceIp` as shown above.
{% endhint %}

{% hint style="info" %}
You can pass comma-separated `tags` property in the `user` object to easily add tags to the user. For example: `{"user": { "userId": 123, "tags": "tag1, tag2"}}`
{% endhint %}

### Sample Ingest API calls

Below you can find some samples on how to use the Ingest API. While these are using the curl script, you can import them into Postman to get sample snippets for your preferred language/lib.

#### User registered

A sample call to create the user upon registration. The event has properties describing the user's plan and trial.

```
curl --location --request POST 'https://ingest.encharge.io/v1' \
--header 'content-type: application/json' \
--header 'X-Encharge-Token: your-write-key' \
--data-raw '{
  "name": "Registered user",
  "user": {
  	"email": "jonsnow@thenorthremembers.com",
  	"userId": "1234567890",
  	"firstName": "Jon",
  	"lastName": "Snow"
  },
  "properties": {
	  "plan": "Premium",
    "trial": {
    	"startDate": "2020-03-06T14:24:03.522Z",
    	"length": 14
    }
  }
}'
```

#### Action taken

A sample call about an action that the user performed in your app (created a page). In this case, the user is identified with their `userId` and the event has no `properties`.

```
curl --location --request POST 'https://ingest.encharge.io/v1' \
--header 'content-type: application/json' \
--header 'X-Encharge-Token: your-write-key' \
--data-raw '{
  "name": "Created Page",
  "user": {
  	"userId": "1234567890"
  }
}'
```

#### Form submitted

A sample call to record a form submission by a user. The user email is supplied to identify the user and the `properties` are the form fields.

```
curl --location --request POST 'https://ingest.encharge.io/v1' \
--header 'content-type: application/json' \
--header 'X-Encharge-Token: your-write-key' \
--data-raw '{
  "name": "Form Submitted",
  "user": {
    "email": "michael@michael-scott-paper-company.com"
  },
  "properties": {
	  "Message": "Hello, I'd like to order some paper."
  }
}'
```

{% hint style="info" %}
**CORS issues with the Ingest API**

Pass the write key in the URL instead as a header. For example:

<https://ingest.encharge.io/v1/your-write-key>

Alternatively, you can use the [Javascript Event Tracking](/getting-started/connecting-your-app-to-encharge/javascript-event-tracking) library.
{% endhint %}

### Special Events

Encharge defines the following special events:

#### Alias

Use this event to change the `userId` and/or `email` of a user in your Encharge account.

Please note that you can provide both an email and a User Id.

The event has the following extra properties:

* `type` Should be set to "alias"
* `previousEmail` If changing the email address, the previous email of the user. Optional.
* `user.email` If changing the email address, the new email of the user. Optional.
* `previousUserId` If changing the User Id, the previous User Id. Optional.
* `user.userId` If changing the User Id, the new User Id. Optional.

Sample call:

```
curl --location --request POST 'https://ingest.encharge.io/v1' \
--header 'content-type: application/json' \
--header 'X-Encharge-Token: your-write-key' \
--data-raw '{
  "type": "alias",
  "previousUserId": "abc",
  "previousEmail": "jon@snow.com",
  "user": {
  	"userId": "123",
        "email": "aegon@targaryen.com"
  }
}'
```

#### Group (Create/Update Custom Objects)

Create or Update a Custom Object (including Companies) in Encharge.&#x20;

Additionally, if an Email or a User ID is provided, an Encharge user will be associated with the object. A new user will be created if the email or user ID does not exist in Encharge.

The event has the following extra properties:

* `type` Should be set to "group"
* `objectType` The name of the object to create/update (e.g. `company`). Make sure to create the object schema beforehand, either in the Encharge app or via the API.
* `properties` Dictionary of object fields to associate with the object in Encharge. Any unexisting fields will be ignored.
  * If you want to update an existing object in Encharge, make sure to pass `id` or `externalId` in the properties.
* `user.userId` If you want to associate the object with a user in Encharge, pass the User Id here. Optional.
* `user.email` If you want to associate the object with a user in Encharge, pass the user email here. Optional.

Sample call:

```
curl --location --request POST 'https://ingest.encharge.io/v1' \
--header 'content-type: application/json' \
--header 'X-Encharge-Token: your-write-key' \
--data-raw '{
  "type": "group",
  "objectType": "company",
  "properties": {
    "name": "House Stark",
    "externalId": "abc"
  },
  "user": {
  	"userId": "123",
        "email": "jon@snow.com"
  }
}'
```


# JavaScript Event Tracking

Track events that happen on your app's frontend or on your site using the Encharge Javascript tracking code.&#x20;

The Javascript tracking code will automatically record pageviews.

Make sure you have installed the Encharge JS snippet by following [the instructions](https://app.encharge.io/settings/site-tracking) in the app.

If there is a chance that the Encharge JS snippet will be run after code that calls it, add the following line of code before calling any of its methods:

```
if (!window.EncTracking) window.EncTracking={queue:[],track:function(e){this.queue.push({type:"track",props:e})},identify:function(e){this.queue.push({type:"identify",props:e})}};
```

### Identify

The `identify` method can be used to:

* Uniquely identify the current person.
* Enrich his or her profile with additional traits

We recommend calling `identify` on the following events:

* After a user registers
* After a user logs in
* When a user updates their info (for example changes his plan or updates his address)

```javascript
EncTracking.identify({ 
  email: "emily.doe@gmail.com", 
  userId: "123"
});
```

{% hint style="info" %}
You can pass comma-separated `tags` property to the identify method to easily add tags to the user. For example: `EncTracking.identify({ email: "emily.doe@gmail.com", tags: "tag1, tag2"});`
{% endhint %}

###

### Track

Use `track` method to record actions that users take in your app.

{% hint style="info" %}
Please note that pageviews are tracked automatically, so you don't need to emit events for them.
{% endhint %}

The `track` method uses the same request body as our [Ingest API](/getting-started/connecting-your-app-to-encharge/ingest-api).

For example, to log that one of your users sent a message, you'd use the following:

```javascript
// Make sure this code is placed after the Encharge Tracking JS snippet
window.EncTracking.track(
  {
    // Name of this event (required)
    "name": "Sent Message", 
    // Properties of this event (optional)
    "properties": { 
      "numberOfRecipients": 12
    },
    // Fields for the current user performing the event (required)
    "user": { 
      // `email` or `userId` is required to uniquely identify this person
      "email": "mscott@dundermifflin.com", 
      // Any other fields will be added to this person.
      "name": "Michael Scott", 
    }
  }
);
```

{% hint style="info" %}
The Encharge Javascript tracking code sends these events to the Encharge Ingest API, and is subject to the same terms.
{% endhint %}

{% hint style="success" %}
You can omit calling the `identify` method by sending the user traits in the `user` property of the `track` method (see the example above).
{% endhint %}

###

### Single-page app Pageviews&#x20;

Usually, the Encharge JS snippet tracks pageviews automatically. However, in some single-page apps, you might need to explicitly trigger pageview. You can do so as follows:

```javascript
// Make sure this code is called after the Encharge Tracking JS snippet has loaded
window.EncTracking.client.recordEvent('pageviews', 
  { 
    "page": { 
      "url": "https://google.com", 
      // Page title is optional
      "title": "New Page"
    }
  }
)

```

### Get Anonymous ID

If you need the Anonymous user ID created by Encharge, use the `EncTracking.getId()` method.

###

## Opt-In and Opt-Out

Opt-In and Opt-Out are two separate concepts for the Event Tracking.

### Opt-Out

When Opt-Out is enabled, it means that the Event Tracking script **will not track any events** for the current user, including form submission and any manually triggered event such as `identify` and `track` calls.

If you'd like to not track specific users, call the following snippet before the Encharge tracking has been loaded.&#x20;

```
if (!window.EncTracking) window.EncTracking = {};
window.EncTracking.explicitOptOut = true;
```

### Opt-In

When the user explicitly (or implicitly according to your [Site Tracking](https://app.encharge.io/settings/site-tracking) settings) enables Opt-In, the events that they perform on your site will be tracked. This includes pageviews, form submissions, manual `identify` and `track` calls.

However, if Opt-In is not enabled, the Event Tracking will still record form submissions, and manual `identify` and `track` calls. However, these events will be recorded without placing a cookie or using local storage on the user's computer. Also, the user's IP address will not be passed to the Encharge backend.

You can enable Opt-In by disabling "Wait for opt-in before tracking" when configuring your tracking script in [Site Tracking](https://app.encharge.io/settings/site-tracking). Alternatively, you can use the following code:

<pre><code>if (!window.EncTracking) {
<strong>    window.EncTracking = {};
</strong>    window.EncTracking.hasOptedIn = true;
} else {
    window.EncTracking.optIn();
}
</code></pre>

###

### Using custom consent prompt

If you'd like to use your own consent mechanism, you need to configure your tracking script in [Site Tracking](https://app.encharge.io/settings/site-tracking) like so:

![](/files/-MZrJrJmC3r6_0KaGBi4)

Then, to enable tracking for the current visitor, call the following Javascript code from your cookie consent solution:

```
window.EncTracking.optIn();
```

## Disable some tracking functionality

### Disable form tracking

The Encharge Tracking code automatically captures fields named "email" in any forms on your site. If you don't want to create people from all forms on your site, you can disable ALL form tracking by calling the following snippet before the Encharge tracking has been loaded.&#x20;

```
if (!window.EncTracking) window.EncTracking = {};
window.EncTracking.recordForms = false;
```

###

### Disable pageview tracking

The Encharge Tracking code automatically records pageviews. You can disable all pageviews tracking by calling the following snippet before the Encharge tracking has been loaded.&#x20;

```
if (!window.EncTracking) window.EncTracking = {};
window.EncTracking.recordPageViews = false;
```

###

### Track pageviews on page open

The Encharge Tracking code automatically records pageviews when the user leaves the page. This is done to track time spent on the page. In certain cases, it might be beneficial to track pageviews right after the page has been opened. You can do so by using the following snippet before the Encharge tracking has been loaded:&#x20;

```
if (!window.EncTracking) window.EncTracking = {};
window.EncTracking.recordPageViewsOnExit = false;
```

### Clear cookies

If you'd like to clear all cookies for the current user (e.g. upon log out)use the following call.

```
if (!window.EncTracking) window.EncTracking = {};
window.EncTracking.clearCookies();
```

###


# Segment.com Integration

Connecting your App with Encharge via Segment.com

Sending events and creating people through Segment works best for when your app already integrates with Segment.

To get started with sending your Segment events to Encharge, open [Your Apps](https://app.encharge.io/apps), and click on the Segment logo.

### Creating People in Encharge through Segment events

Encharge ingests all Segment events (identify, track, group, alias) that are passed to the destination you’ve set up in Segment. Encharge tries to assign the event to a person: this happens automatically through the `email` or the `userId` property, or with Segment’s `anonymousId`.&#x20;

If no person is found, a new one is created. New people (if they have an email) are treated as subscribers automatically, i.e. eligible to receive emails.

### Mapping Data from Segment events

Apart from `email`, `userId`, `anonymousId` , any other properties/traits in Segment events are not mapped to people in Encharge by default. However, you often might need additional data from events. To do this, in the [Segment config in Encharge](https://app.encharge.io/apps?auth-app=segment), the second step (Map Fields) allows you to map properties from Segment events to people in Encharge.

Let’s say that you want to be able to set the fields "Trial Start Date" and "Trial End Date" for people in your account. Your Segment event might look like this:&#x20;

```javascript
{ 
  type: "track", 
  userId: "019mr8mf4r", 
  event: "Started trial", 
  properties: { 
    trialStartDate: "2020-12-30T07:47:46.550Z", 
    trialEndDate: "2021-01-30T07:47:46.550Z" 
  } 
}
```

&#x20;Then, your mapping in Encharge would be set up like this:

![Mapping trial data from Segment to Encharge](/files/-MPmhHE8DbDsQgbm9dK5)

&#x20;This will map the `trialStartDate` and `trialEndDate` from any Segment event to “Trial Start” and “Trial End” fields in Encharge.

{% hint style="info" %}
The “Trial Ends” step in Encharge flows works with the “Trial End” field, so if this is set on some people in your account, the step will work out of the box.
{% endhint %}

### Unsubscribe person through Segment events

To unsubscribe a person in Encharge, you need to set the “Unsubscribed” field in Encharge to `true`. Let’s say you send an event like this:&#x20;

```javascript
{ 
  type: "track", 
  userId: "019mr8mf4r", 
  // Event name can be anything, the unsubscribe property below makes it work 
  event: "User canceled", 
  properties: { 
    unsubscribed: true 
  } 
}
```

&#x20;Now, you need to map the unsubscribe property from Segment to Encharge like this:<br>

![Segment property \`unsubscribed\` is mapped to "Unsubscribed" field](/files/-MPmhtxrFqydlYbds1SY)

{% hint style="info" %}
You can review other fields on your account in [Fields Management](https://app.encharge.io/settings/person-fields).
{% endhint %}

### What should my Segment events be named

In Encharge, event names in Segment events are used only when creating an Encharge “segment” based on whether an event has happened for a person. For example, with the “User canceled” event above, you might create a segment of people who have canceled:

![](/files/-MPmigYIt7vlZ7v-bwNE)

{% hint style="success" %}
As a best practice, set up an Event Tracking plan to know what events are going through Segment and what properties they have. Here is a [sample template](https://docs.google.com/spreadsheets/d/1tzTMcRrXjScR2_E00tBMISQ94Z7FxTABPOdgYjjJ-2U/edit?usp=sharing).
{% endhint %}


# Getting Help

Contact support and get help with Encharge

We're here to help! Please email <support@encharge.io> with any technical questions.

### Book a technical call

If you'd like to book a technical help call please reach out to <support@encharge.io> detailing your request. The support team will review your request and forward it to our technical team, so you can arrange a call. Please note that technical support calls are only available to our recurring customers.


# Personalizing Emails with Liquid

Sending personalized emails to your subscribers allows you to add a personal touch to your automated messages.&#x20;

Encharge uses Liquid, a dynamic templating language built by Shopify. Liquid allows you to insert personalization in your emails, display dynamic content, and use data from people in your account in automation flows.&#x20;

### Personalizing with people's data

To dynamically insert data into emails or flow steps, you can use the `person` object. For example, to dynamically insert the subscriber's first name in an email, you can use the following code: `{{ person.firstName }}` .

Personalization also works with custom fields. You can review all the fields in your account in [Fields Management](https://app.encharge.io/settings/person-fields?folder-item=allPersonFields). To personalize with a custom field, use the field's "API Name" from Fields Management, like so `{{person.field-api-name-here}}`.

For example, the API Name for the "Last Name" field is `lastName` and the personalization tag would be `{{person.lastName}}`.

### Accessing the current date

You can insert the current date, formatted as simplified extended [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations) format (e.g. *2020-12-30T19:35:54.019Z* ) with the `{% now %}` Liquid tag.&#x20;

### Advanced Personalization

Encharge supports all Liquid tags and filters as described in the official [Liquid docs](https://shopify.github.io/liquid/).


# Email Deliverability

Encharge has best-in-class deliverability. We take extra care of our email sending infrastructure to ensure the best deliverability for you. Some of the measures we take:

* Our system monitors delivery, bounce, unsubscribe, and spam rates to prevent abuse.
* Cold emails are not allowed on Encharge.
* All of our mail servers are regularly checked to make sure they are not in email sending blacklists.
* All new and trial accounts are manually verified to ensure they are not sending spam, phishing, or cold emails.

### Test emails end up in Spam folder or display a warning&#x20;

When your test emails land in spam, usually it's due to one of the following reasons:

* The sender and the recipient have the same email address. To fix this, send test emails to another email address or set up email authentication (see below).
* The domain you are sending from does not allow unauthorized email. You can fix this by setting up email authentication.

### Set up email authentication

Open [Email Settings](https://app.encharge.io/settings/email) in Encharge and add the domain you are sending from. Then, set the required DNS records in your DNS host. You might need to forward the information to someone on your team to set this up for you.

{% hint style="info" %}
If your domain name is "example.com", DNS hostnames look like `m1._domainkey.example.com`  . Depending on your DNS host, you might need to omit "example.com" from the hostname.&#x20;
{% endhint %}


# API Documentation

## Ingest API

If you are looking to send people and their activity to Encharge, the [Encharge Ingest API](/getting-started/connecting-your-app-to-encharge/ingest-api) is the easiest way to do so.

***Do not use this API if you are building an integration to be used by our mutual users.***

## Javascript API

We also have [Javascript API](/getting-started/connecting-your-app-to-encharge/javascript-event-tracking) if you'd like to track people's activity on your app's frontend or specific actions on your site.

## REST API

For advanced integrations with Encharge, use the Encharge REST API.

***Use the REST API if you are building an integration with Encharge.***

The Encharge API documentation is available formatted by [ReDoc](https://app-encharge-resources.s3.amazonaws.com/redoc.html) (recommended) or [RapiDoc](https://app-encharge-resources.s3.amazonaws.com/rapidoc.html) (experimental).&#x20;

You can also download the raw [OpenAPI 3 definition](https://encharge-app-resources.s3.amazonaws.com/merged.yaml).


# Overview

This supplementary API allows you to send transactional emails via Encharge.

Encharge really shines when it comes to sending automated emails. However, if you need to send transactional emails (e.g. password resets), this API has got your back.

For example, you can use this API to send emails like:

* Password reset email
* Single sign-on email with a magic login link
* Payment receipt email
* and more

## Benefits

Sending HTML over email is a mess. Knowing what email clients support what HTML features can be a full-time job.&#x20;

With Encharge, you can use our Visual Drag-and-Drop editor or our Simple editor to create a standard-compliant email that will look properly in all email clients. Then, you can send the template using this API.

**Further reading:**

* [Explore more benefits](https://docs.encharge.io/transactional-email-api/features) of sending transactional email via Encharge.
* [What are transactional emails?](https://encharge.io/what-are-transactional-emails/)
* [11 Best Practices for Transactional Email Marketing](https://encharge.io/11-best-practices-for-transactional-email-marketing/)

## Getting Started&#x20;

### 0. Create an account and get your API key

If you haven't registered for Encharge yet, [create an account](https://app.encharge.io/register). Then, get your API key from [your Account](https://app.encharge.io/account/info).

### 1. Create an email template

Open the [Emails section](https://app.encharge.io/emails) in Encharge. Click the + icon in the lower-left to create a new email. You can skip this step if you've already created your email template.

### 2. Send a request to the Transactional Email API

An example follows in Node.js. You can use [API documentation in Postman](https://documenter.getpostman.com/view/460427/TVRj5o3E) to generate an example in your preferred language.

```javascript
const axios = require('axios');

// Send a POST request
axios({
  method: 'post',
  url: 'https://api.encharge.io/v1/emails/send?token=yourAPIKey',
  data: {
    "to": "recipient@acme.com",
    // Name of the template you created in step 1.
    "template": "Template Name",
    /**
   * Dictionary of properties to be replaced in the email.
   * For example, passing
   * `{ "loginURL": "https://app.encharge.io/login/3n2l3ad99"}`
   * will replace
   * `{{ loginURL }}` in the email body or subject.
   *
   */
    "templateProperties": {
      "loginURL": "https://app.encharge.io/login/3n2l3ad99"
    }
  }
});

```


# Pricing

Sending transactional email with this API is already included with your Encharge Premium plan 😊.

If you send to an email address that is not in your Encharge account, it will be created as a person in Encharge.


# Benefits and Features

Explore all the nice things that the Encharge Transactional Email API can do for you

## Awesome looking emails - everywhere

Sending HTML over email is a mess. Knowing what email clients support what HTML features can be a full-time job.&#x20;

With Encharge, you can use our Visual Drag-and-Drop editor or our Simple editor to create a standard-compliant email that will look properly in all email clients. Then, you can send the template using this API.

## Track Email Activity

Transactional email opens and clicks, as well as deliveries will appear in your users' timeline.

## Email Deliverability

The API uses the DKIM and SPF settings you have set in your [Encharge email settings](https://app.encharge.io/settings/email). This way your emails will come from your own domain.

{% hint style="info" %}
If you haven't set the required records, Encharge will use its own DKIM and SPF settings, which come with high deliverability by default. Please note, that in this case some of your recipients might see "via encharge-mail.com" next to your domain name in their inbox: <https://cl.ly/ccfa2de9a8df>
{% endhint %}

## UTM tags

Encharge automatically appends UTM tags to your links if enabled in your [Encharge email settings](https://app.encharge.io/settings/email), as follows:

* **utm\_source** is who sent the email. It will be set to "encharge".
* **utm\_medium** is the marketing channel used, which will be set to “email.”
* **utm\_campaign** is the name of the marketing campaign. It is set to "transactional".
* **utm\_content** is set to the subject of your email.

{% hint style="info" %}
You can set the `UTMTags` parameter to `false` in your request, to disable this behavior.
{% endhint %}


# Technical Overview

See the [complete API reference](https://docs.encharge.io/transactional-email-api/reference). Alternatively, check the [API documentation](https://documenter.getpostman.com/view/460427/TVRj5o3E) in Postman.

The Transactional Email API:

* Accepts and outputs **JSON**.
* **Authenticates** using API key passed via the `token` query parameter or the `X-Encharge-Token` header. Get your API key from [your Account](https://app.encharge.io/account/info).
* Returns **202 Accepted** on success.
* Returns descriptive error messages with meaningful HTTP response codes. The response has the following format:

```javascript
{
    "error": {
        "message": "Missing email content. Please pass `template`, `html` or `text`",
        "markdown": "<p>Missing email content. Please pass <code>template</code>, <code>html</code> or <code>text</code></p>\n",
        "traceId": "9751fe70-0957-11eb-a6b8-3baf67de29f8"
    }
}

```


# Send an email from template

To send an email from a prepared template, set the `template` parameter to the template name.&#x20;

To create a new email template, open the [Emails section](https://app.encharge.io/emails) in Encharge and click the + icon in the lower-left. You can skip this step if you've already created your email template.

{% hint style="info" %}
If you have previously created the recipient  in Encharge, you can use personalization tags, for example `{{ person.firstName }}` in your email's text. See what fields you can use in [Person Fields](https://app.encharge.io/settings/person-fields).
{% endhint %}

```javascript
const axios = require('axios');

// Send a POST request
axios({
  method: 'post',
  url: 'https://api.encharge.io/v1/emails/send?token=yourAPIKey',
  data: {
    "to": "recipient@example.com",
    "template": "Welcome Email",
    /**
   * Optionally, you can include a dictionary of fields to be replaced.
   * For example, passing
   * `{ "loginURL": "https://app.encharge.io/login/3n2l3ad99"}`
   * will replace
   * `{{ loginURL }}` in the email template.
   */
    "templateProperties": {
      "loginURL": "https://app.encharge.io/login/3n2l3ad99"
    }
  }
});
```

{% hint style="warning" %}
If you provide the `from` parameter, it will overwrite the sender address specified in the template.
{% endhint %}

{% hint style="info" %}
To use the template ID instead of the template name, pass a number to the `template` parameter above. \
Finding the template ID is easy - open the template in the Encharge app. Look at the URL to find the email ID. In the following URL [https://app.encharge.io/emails?email=123](https://app.encharge.io/emails?emails-folder-item=allEmails\&email=40995), the template ID is 123.
{% endhint %}


# Send custom HTML email

If you'd like to set your own HTML for an email, use the `html` parameter.&#x20;

{% hint style="warning" %}
Sending HTML over email is a mess. Knowing what email clients support what HTML features can be a full-time job.&#x20;

We recommend using our Visual Drag-and-Drop editor to create a standard-compliant email that will look properly in all email clients. [Learn more](https://docs.encharge.io/transactional-email-api/send-an-email-from-template)
{% endhint %}

To send a custom HTML email, send a request to the API as follows:

```javascript
const axios = require('axios');

// Send a POST request
axios({
  method: 'post',
  url: 'https://api.encharge.io/v1/emails/send?token=yourAPIKey',
  data: {
    "to": "recipient@example.com",
    "from": "sender@acme.org",
    "subject": "Welcome",
    "html": "<div>Hello and welcome, <b>{{ person.firstName }}</b>!</div>",
    /**
   * Optionally, you can include a dictionary of fields to be replaced.
   * For example, passing
   * `{ "loginURL": "https://app.encharge.io/login/3n2l3ad99"}`
   * will replace
   * `{{ loginURL }}` in the email html or subject.
   */
    "templateProperties": {
      "loginURL": "https://app.encharge.io/login/3n2l3ad99"
    }
  }
});
```

{% hint style="success" %}
If you have previously created the recipient  in Encharge, you can use personalization tags, for example `{{ person.firstName }}` in your email's text. See what fields you can use in [Person Fields](https://app.encharge.io/settings/person-fields).
{% endhint %}


# Send a plain-text email

To send a plain-text email (i.e. one that appears to be sent manually) via the Encharge Transactional Email API, specify the `text` parameter. You'll also need to provide the email subject as `subject` and the sender email as `from`

{% hint style="info" %}
If you have previously created the recipient in Encharge, you can use personalization tags, for example `{{ person.firstName }}` in your email's text. See what fields you can use in [Person Fields](https://app.encharge.io/settings/person-fields).
{% endhint %}

```javascript
const axios = require('axios');

// Send a POST request
axios({
  method: 'post',
  url: 'https://api.encharge.io/v1/emails/send?token=yourAPIKey',
  data: {
    "to": "recipient@example.com",
    "from": "sender@acme.org",
    "subject": "Welcome",
    "text": "Hello and welcome, {{ person.firstName }}!",
    /**
   * Optionally, you can include a dictionary of fields to be replaced.
   * For example, passing
   * `{ "loginURL": "https://app.encharge.io/login/3n2l3ad99"}`
   * will replace
   * `{{ loginURL }}` in the email text or subject.
   */
    "templateProperties": {
      "loginURL": "https://app.encharge.io/login/3n2l3ad99"
    }
  }
});
```


# Authentication

Authenticate by passing an API key in the `token` query parameter or the `X-Encharge-Token` header. Get your API key from [your Account](https://app.encharge.io/account/info).

Continue to the [API Reference](https://docs.encharge.io/transactional-email-api/reference).


# Reference

You can also view the [API documentation](https://documenter.getpostman.com/view/460427/TVRj5o3E) in Postman.

## Send Email

<mark style="color:green;">`POST`</mark> `https://api.encharge.io/v1/emails/send`

Send transactional emails with Encharge.

#### Query Parameters

| Name  | Type   | Description            |
| ----- | ------ | ---------------------- |
| token | string | Your Encharge API key. |

#### Request Body

| Name               | Type    | Description                                                                                                                                                                                                                                                       |
| ------------------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| template           | string  | <p>The name of the email template to use.<br><em>Only</em> <em>one of `text`, `html` or `template` may be set.</em></p>                                                                                                                                           |
| html               | string  | <p>The content of your HTML email.<br><em>Only one of `text`, `html` or `template` may be set.</em></p>                                                                                                                                                           |
| text               | string  | <p>The content of your plain-text email.<br><em>Only one of `text`, `html` or `template` may be set.</em></p>                                                                                                                                                     |
| to                 | string  | <p>Email address of the recipient.<br><em>If the person has been previously created in Encharge, you can pass an object with `userId` and we'll use the email we have for this user.</em></p>                                                                     |
| from               | string  | <p>Email address of the sender.<br><em>If you'd like to set the sender name, pass an object with `email` and `name`. If a template is specified, this will overwrite the sender details in the template.</em></p>                                                 |
| templateProperties | object  | <p>Dictionary of properties to be replaced in the email.   <br>For example, passing <br>{"loginURL":"<https://app.encharge.io/login/3n2l3ad99"}>  will replace `{{ loginURL }}` in the email body or subject. </p>                                                |
| unsubscribeCheck   | boolean | <p>By default, we will not send to people who have unsubscribed from your emails.<br>Using caution, you can send to unsubscribed people by setting this flag to `false`.</p>                                                                                      |
| UTMTags            | boolean | <p>If you've enabled Automatic UTM tagging in your Encharge account, we will tag all links in your emails.<br>To disable this behavior, set this flag to `false`.</p>                                                                                             |
| cc                 | String  | Email addresses to CC in the current email. Multiple addresses can be passed as a comma-separated string.                                                                                                                                                         |
| bcc                | String  | Email addresses to BCC in the current email. Multiple addresses can be passed as a comma-separated string.                                                                                                                                                        |
| reply              | String  | <p>Email address to reply to.<br><em>Uses the <code>from</code> address if unspecified. If you'd like to set the reply name, pass an object with `email` and `name`. If a template is specified, this will overwrite the sender details in the template.</em></p> |

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

```
```

{% endtab %}

{% tab title="400 " %}

```javascript
{
    "error": {
        "message": "Missing email content. Please pass `template`, `html` or `text`",
        "stack": "Error: \n    at new APIException (/home/slav/code/monorepo/packages/domain/exceptions/api_exceptions.ts:34:18)\n    at new BadRequestException (/home/slav/code/monorepo/packages/domain/lib/exceptions/api_exceptions.js:22:9)\n    at Function.getTemplate (/home/slav/code/monorepo/packages/api/src/services/TransactionalEmailService.ts:153:15)",
        "markdown": "<p>Missing email content. Please pass <code>template</code>, <code>html</code> or <code>text</code></p>\n",
        "traceId": "9751fe70-0957-11eb-a6b8-3baf67de29f8"
    }
}
```

{% endtab %}
{% endtabs %}


# Sending to unsubscribed contacts

Occasionally, you might need to contact people who have unsubscribed from your emails.

You can do so by setting the `unsubscribeCheck` parameter to `false` .

{% hint style="danger" %}
Please, use this with caution as sending too many emails to unsubscribers can lead to spam reports and suspension of your Encharge account.
{% endhint %}


# Activity Stream

Activity Stream is an advanced feature that enables you to receive a real-time stream of all events that happen to people in your Encharge Account. You can store this activity in your data warehouse for further analytics.

### How to get started?

Activity Stream is an add-on that is available for an extra fee. Please get in touch with your account manager or contact <support@encharge.io>.

Please prepare your endpoint where events will be POSTed to. See below for a sample of an activity stream event.

{% hint style="info" %}
You can supply Segment.com [HTTP Tracking API source](https://segment.com/docs/connections/sources/catalog/libraries/server/http-api/#http-tracking-api-source) instead of your own endpoint.
{% endhint %}

The endpoint should return a success response (2XX code) in 2 seconds or less.

Each event will contain information (ID and email) about the person that triggered the event.

The timestamp that indicates when the event occured is attached to each event. The timestamp is UNIX time in milliseconds.

### What activities are streamed?

Below you'll find a list of activities that Encharge will send.&#x20;

{% hint style="info" %}
Please note that curly brackets indicated a value that will be replaced when the event is emitted. For example: `added-tag-{tag}` will become `added-tag-tag1` when the person is tagged with "tag1".
{% endhint %}

Name: `updatedUser` \
Type: `updatedUser`\
Person was updated. See `changedFields` in `properties` for changed fields, and their previous and new values.

Name: `newUser`\
Type: `newUser`\
Person was created.

Name: `unsubscribedUser` \
Type: `unsubscribedUser`\
Person unsubscribed from all emails.

Name: `added-tag-{tag}`\
Type: `tag`\
Person was tagged. The tag is also passed as `tag` in `properties`.

Name: `removed-tag-{tag}`\
Type: `tag`\
Person was untagged. The tag is also passed as `tag` in `properties`.

Name: `page-visited`\
Type: `page`\
Person visited a page on your site (when Site Tracking is installed). URL is available in `url` in `properties`.

Name: `form-submitted`\
Person submitted a from on your site (when Site Tracking is installed). URL is available in `url` in `properties`. Form data is available in `form` in `properties`.

Name: `sms-sent`\
Type: `sms`\
Person was sent an SMS. Message is available as `message` in `properties`.&#x20;

Name: `sms-failed` \
Type: sms\
Person couldn't be sent an SMS. Message is available as `message` in `propertis`.&#x20;

#### Email Events

In `properties` , each of these events will contain:

* Email Id as `emailId`&#x20;
* Flow ID (if applicable) as `flowId`.
* Flow Name (if applicable) as `flowName`.
* Email name as `emailName`.

Name: `email-delivered`\
Type: `email`\
Person received an email.&#x20;

Name: `email-open`\
Type: `email`\
Person opened an email.&#x20;

Name: `email-click`\
Type: `email`\
Person clicked an email. Clicked link URL can be found in `url` in `properties` .

Name: `email-reply`\
Type: `email`\
Person replied to an email.&#x20;

Name: `email-blocked`\
Type: `email`\
Person couldn't receive an email (soft bounce).

Name: `email-bounce`\
Type: `email`\
Person couldn't receive an email (hard bounce).

Name: `email-dropped`\
Type: `email`\
Person couldn't receive an email because they are unsubscribed, have an invalid email address, or if they've received this marketing email before. See `reason` in `properties` .

Name: `email-spamreport`\
Type: `email`\
Person reported this email as spam.

####

#### Flows Events

Name: `performed-step:{stepId}`\
Type: `step`\
Person performed a step. You can find the step and the flow ID as `stepId` and `flowId`  in `properties` .

Name: `errored-step:{stepId}`\
Type: `step`\
An error occured while the person was performing a step. You can find the step and the flow ID as `stepId` and `flowId`  in `properties` .

#### Custom Objects/Companies Events

All object events will include the available object information in the `object` property.

Name: `newObject-{objectName}`\
Type: `object`\
Custom object/company was created. Object data will be available in `properties`.\
For example, event named `newObject-company` will trigger when a new company is created.

Name: `updatedObject-{objectName}`\
Type: `object`\
Custom object/company was updated. See `changedFields` in `properties` for changed fields, and their previous and new values. \
For example, an event named `updatedObject-invoice` will trigger when an invoice is updated.

Name: `deletedObject-{objectName}`\
Type: `object`\
Custom object/company was deleted. The object `id` and `externalId` will be available in `properties`.

#### Object associations

Name: `newAssociation-{associationId}`\
Type: `association`\
Triggers when a new association with a specific ID is created.\
For example, an event named `newAssociation-123` will trigger when a new association of ID 123 is created between objects. \
The following properties are available in `properties`:  `associationId`, `fromId`, `fromObject`, `toId`, `toObject`.

Name: deletedAssociation-{associationId}\
Type: association\
Triggers when a new association with a specific ID is deleted.\
For example, an event named `deletedAssociation-123` will trigger when a new association of ID 123 is deleted. \
The following properties are available in `properties`:  `associationId`, `fromId`, `fromObject`, `toId`, `toObject` .

### Example payloads

#### Tag added

Person was tagged.

```json
{
  "event": "added-tag-test",
  "type": "tag",
  "properties": {
    "tag": "test"
  },
  "user": {
    "id": "c1756f7d-8086-4704-ac73-b242857feb1a",
    "email": "201c3420-2ab1-11ec-ab62-4f0b3dac823e-e2e-test-user@mailsac.com"
  },
  "timestamp": 1562914373005
}
```

#### Email Clicked

Email was delivered to person.

```json
{
  "event": "email-delivered",
  "type": "email",
  "properties": {
    "emailId": 59969,
    "flowId": "48918",
    "flowName": "New Flow",
    "emailName": "Welcome email"
  },
  "user": {
    "id": "1ad75773-a8d9-4676-b2e8-d2beebf3742f",
    "email": "someone@example.com"
  },
  "timestamp": 1562914373005
}
```

#### Person Updated

Field `company` was changed from "Acme" to "Encharge".

```json
{
  "event": "updatedUser",
  "type": "updatedUser",
  "properties": {
    "changedFields": {
      "company": {
        "newValue": "Encharge",
        "oldValue": "Acme"
      },
    },
    "source": "manual"
  },
  "user": {
    "id": "b361b760-f6c9-4b23-80a8-82a968987fb8",
    "email": "someone@example.com"
  },
  "timestamp": 1562914373005
}

```


