> For the complete documentation index, see [llms.txt](https://developers.docstudio.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.docstudio.com/examples/send-envelope-from-template.md). Agents can also search and read this documentation through its [MCP server](https://developers.docstudio.com/~gitbook/mcp).

# Send Envelope from Template

This document explains how to create, send, track, and download an envelope from a DocStudio template.

### Scenario

Send a sales agreement from a saved DocStudio template. The template already contains the document structure, recipient roles, and fields, so the API request only needs to reference the selected template version, assign real recipient mailboxes to template roles, and pass field values.

Use this example when the envelope structure is already prepared in DocStudio and the external system only starts the workflow. For example, a CRM can create an envelope from a contract template, assign the customer and manager mailboxes, prefill agreement data, and save the returned envelope UUID for tracking.

### Step 1 Prepare template values

| Method | Endpoint                |
| ------ | ----------------------- |
| `POST` | `/api/v1/envelope/send` |

Prepare all identifiers before building the request. Do not create template UUIDs, template versions, role IDs, document IDs, or field names manually; these values must come from the selected template version.

You need:

{% columns %}
{% column %}

* API token
* sender mailbox UUID
* template UUID
* template version UUID
  {% endcolumn %}

{% column %}

* role IDs from the template flow
* recipient mailbox UUIDs
* document IDs from the template
* field names from the template
  {% endcolumn %}
  {% endcolumns %}

| Template value         | Used in envelope XML                 |
| ---------------------- | ------------------------------------ |
| `template/@uuid`       | `envelope/@templateUuid`             |
| `template/@version`    | `envelope/@templateVersion`          |
| `role/@id`             | `flow > roles > role/@id`            |
| recipient mailbox UUID | `flow > roles > role/@mailboxUuid`   |
| `document/@id`         | `documents > document/@id`           |
| `field/@name`          | `documents > document > field/@name` |

#### Template fragment

This simplified template fragment shows the values that must be reused in the send request. The example has two roles and one document field; the envelope XML must use the same template UUID, template version, role IDs, document ID, and field name.

```xml
<template uuid="56cacd6a-ffe7-4b77-9c0c-f928d9a18cb5" version="ab0d11cb-ebdd-42bd-a581-ddca1bb9b585">
  <flow>
    <roles>
      <role id="23f20eec-adad-4325-b553-1bde4be29198" />
      <role id="b811f2b6-1656-42aa-9420-a9b8addb0246" />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <field name="date field" type="date" />
    </document>
  </documents>
</template>
```

### Step 2 Build envelope XML

Build the envelope XML by referencing the template and assigning recipient mailboxes to the template roles. Field values must be placed under the correct document ID and field name from the same template version.

```xml
<envelope templateUuid="56cacd6a-ffe7-4b77-9c0c-f928d9a18cb5" templateVersion="ab0d11cb-ebdd-42bd-a581-ddca1bb9b585">
  <info>
    <subject>Sales agreement</subject>
    <message>Please review and complete the agreement.</message>
  </info>
  <flow>
    <roles>
      <role id="23f20eec-adad-4325-b553-1bde4be29198" mailboxUuid="9baec31c-e940-4894-b6d1-52033e1af66e" />
      <role id="b811f2b6-1656-42aa-9420-a9b8addb0246" mailboxUuid="42c95245-30c1-46ef-bd5b-a9a111deec10" />
    </roles>
  </flow>
  <documents>
    <document id="4a61f258-fd9d-406c-b47e-81c90d4e5c47">
      <field name="date field">2026-07-21</field>
    </document>
  </documents>
</envelope>
```

### Step 3 Send the request

#### Headers

| Header          | Required | Description                                     |
| --------------- | -------- | ----------------------------------------------- |
| `Authorization` | Yes      | Bearer authorization token                      |
| `Content-Type`  | Yes      | Use `application/json`                          |
| `Mailbox`       | Yes      | Sender mailbox UUID used as the mailbox context |

#### Request body

Send envelope XML as a string in `data`. Add [metadata](https://developers.docstudio.com/guides/envelope-metadata.md) when the envelope needs external identifiers or other integration references.

```xml
{
  "data": "<envelope templateUuid=\"56cacd6a-ffe7-4b77-9c0c-f928d9a18cb5\" templateVersion=\"ab0d11cb-ebdd-42bd-a581-ddca1bb9b585\"><info><subject>Sales agreement</subject><message>Please review and complete the agreement.</message></info><flow><roles><role id=\"23f20eec-adad-4325-b553-1bde4be29198\" mailboxUuid=\"9baec31c-e940-4894-b6d1-52033e1af66e\"/><role id=\"b811f2b6-1656-42aa-9420-a9b8addb0246\" mailboxUuid=\"42c95245-30c1-46ef-bd5b-a9a111deec10\"/></roles></flow><documents><document id=\"4a61f258-fd9d-406c-b47e-81c90d4e5c47\"><field name=\"date field\">2026-07-21</field></document></documents></envelope>"
}
```

| Field      | Type   | Required | Description                                                      |
| ---------- | ------ | -------- | ---------------------------------------------------------------- |
| `uuid`     | UUID   | No       | Envelope UUID, when the flow already has an envelope identifier. |
| `data`     | string | Yes      | Envelope XML string.                                             |
| `metadata` | object | No       | Custom key-value metadata added to the envelope.                 |

### Request example

{% tabs %}
{% tab title="Node.js" %}

```javascript
const envelopeXml = "{envelopeXml}";

const response = await fetch(
  "https://api.docstudio.com/api/v1/envelope/send",
  {
    method: "POST",
    headers: {
      Authorization: "Bearer {token}",
      "Content-Type": "application/json",
      Mailbox: "{senderMailboxUuid}"
    },
    body: JSON.stringify({
      data: envelopeXml
    })
  }
);

const body = await response.text();

if (!response.ok) {
  throw new Error(
    `Request failed: ${response.status}\n${body}`
  );
}

if (body) {
  console.log(body);
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$envelopeXml = "{envelopeXml}";

$payload = json_encode(
    ["data" => $envelopeXml],
    JSON_THROW_ON_ERROR
);

$curl = curl_init(
    "https://api.docstudio.com/api/v1/envelope/send"
);

curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer {token}",
        "Content-Type: application/json",
        "Mailbox: {senderMailboxUuid}"
    ],
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_RETURNTRANSFER => true
]);

$body = curl_exec($curl);

if ($body === false) {
    throw new RuntimeException(curl_error($curl));
}

$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException(
        "Request failed: {$status}\n{$body}"
    );
}

if ($body !== "") {
    echo $body;
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

envelope_xml = "{envelopeXml}"

response = requests.post(
    "https://api.docstudio.com/api/v1/envelope/send",
    headers={
        "Authorization": "Bearer {token}",
        "Mailbox": "{senderMailboxUuid}",
    },
    json={
        "data": envelope_xml,
    },
    timeout=30,
)

response.raise_for_status()

if response.text:
    print(response.text)
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require "json"
require "net/http"
require "uri"

envelope_xml = "{envelopeXml}"

uri = URI(
  "https://api.docstudio.com/api/v1/envelope/send"
)

request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer {token}"
request["Content-Type"] = "application/json"
request["Mailbox"] = "{senderMailboxUuid}"
request.body = JSON.generate(
  data: envelope_xml
)

response = Net::HTTP.start(
  uri.hostname,
  uri.port,
  use_ssl: uri.scheme == "https"
) do |http|
  http.request(request)
end

unless response.is_a?(Net::HTTPSuccess)
  raise "Request failed: #{response.code}\n#{response.body}"
end

puts response.body unless response.body.empty?
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func main() {
	envelopeXML := "{envelopeXml}"

	payload := map[string]string{
		"data": envelopeXML,
	}

	requestBody, err := json.Marshal(payload)
	if err != nil {
		panic(err)
	}

	request, err := http.NewRequest(
		http.MethodPost,
		"https://api.docstudio.com/api/v1/envelope/send",
		bytes.NewReader(requestBody),
	)
	if err != nil {
		panic(err)
	}

	request.Header.Set(
		"Authorization",
		"Bearer {token}",
	)
	request.Header.Set(
		"Content-Type",
		"application/json",
	)
	request.Header.Set(
		"Mailbox",
		"{senderMailboxUuid}",
	)

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}

	if response.StatusCode < 200 ||
		response.StatusCode >= 300 {
		panic(fmt.Sprintf(
			"Request failed: %s\n%s",
			response.Status,
			body,
		))
	}

	if len(body) > 0 {
		fmt.Println(string(body))
	}
}
```

{% endtab %}

{% tab title="Java" %}

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

public class Main {
  public static void main(String[] args) throws Exception {
    String payload = """
        {
          "data": "{envelopeXml}"
        }
        """;

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(
            "https://api.docstudio.com/api/v1/envelope/send"
        ))
        .header(
            "Authorization",
            "Bearer {token}"
        )
        .header(
            "Content-Type",
            "application/json"
        )
        .header(
            "Mailbox",
            "{senderMailboxUuid}"
        )
        .POST(
            HttpRequest.BodyPublishers.ofString(payload)
        )
        .build();

    HttpResponse<String> response =
        HttpClient.newHttpClient().send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );

    if (response.statusCode() < 200 ||
        response.statusCode() >= 300) {
      throw new RuntimeException(
          "Request failed: " + response.statusCode()
          + "\n" + response.body()
      );
    }

    if (!response.body().isEmpty()) {
      System.out.println(response.body());
    }
  }
}
```

{% endtab %}

{% tab title=".NET" %}

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

var envelopeXml = "{envelopeXml}";

var payload = JsonSerializer.Serialize(new
{
    data = envelopeXml
});

using var client = new HttpClient();

using var request = new HttpRequestMessage(
    HttpMethod.Post,
    "https://api.docstudio.com/api/v1/envelope/send"
);

request.Headers.Authorization =
    new AuthenticationHeaderValue("Bearer", "{token}");
request.Headers.Add(
    "Mailbox",
    "{senderMailboxUuid}"
);

request.Content = new StringContent(
    payload,
    Encoding.UTF8,
    "application/json"
);

using var response = await client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();

if (!response.IsSuccessStatusCode)
{
    throw new HttpRequestException(
        $"Request failed: {(int)response.StatusCode}\n{body}"
    );
}

if (!string.IsNullOrEmpty(body))
{
    Console.WriteLine(body);
}
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl --request POST \
  --url 'https://api.docstudio.com/api/v1/envelope/send' \
  --header 'Authorization: Bearer {token}' \
  --header 'Content-Type: application/json' \
  --header 'Mailbox: {senderMailboxUuid}' \
  --data '{
    "data": "{envelopeXml}"
  }'
```

{% endtab %}
{% endtabs %}

### Step 4 Save the envelope UUID

The endpoint returns `201 Created` with the created envelope UUID. Save this UUID in the external system, because it is required for follow-up operations such as retrieving the envelope, checking its status, downloading documents, or matching callback events.

```json
{
  "uuid": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}
```

| Field  | Type | Description            |
| ------ | ---- | ---------------------- |
| `uuid` | UUID | Created envelope UUID. |

### Step 5 Continue processing

After the request is processed, DocStudio creates the envelope from the selected template and sends it according to the template flow. The recipient mailboxes assigned in the XML become participants in the envelope, and the provided field values are saved to the matching fields.

Use the returned UUID to check envelope status and download the envelope archive.

### Common mistakes

{% hint style="warning" %}
Use identifiers from the same template version. Set the sender mailbox in `Mailbox`, assign each template role to the correct recipient mailbox, and pass valid XML as a JSON string in `data`.
{% endhint %}
