> You are reading the Docusign Developer Documentation. For clean Markdown of any page, append .md to the page URL.
>
> Documentation indexes by section:
> - APIs and SDKs: https://docusign.docs.buildwithfern.com/docs/llms.txt
> - Platform 101: https://docusign.docs.buildwithfern.com/platform/llms.txt
> - Extension Apps: https://docusign.docs.buildwithfern.com/extension-apps/llms.txt
> - Docusign CLI: https://docusign.docs.buildwithfern.com/docusign-cli/llms.txt
>
> Authentication (OAuth, JWT Grant, M2M): https://docusign.docs.buildwithfern.com/platform/auth
> Webhooks and Connect: https://docusign.docs.buildwithfern.com/platform/webhooks
>
> OpenAPI specifications: https://docusign.docs.buildwithfern.com/openapi.json
> MCP server: https://docusign.docs.buildwithfern.com/_mcp/server

# How to request a signature by email using a template

> This topic demonstrates how to use a template containing predefined attributes to create new envelopes and send them by email.

This topic demonstrates how to use a template to create an envelope and send it by email. When a recipient receives and signs an envelope by email, the process is called *remote signing*.

> **Note**
>
> Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects: [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).

## Required data

Running the code in this how-to requires this data:

| Data element          | Description                                                                                                                                                                                                                                                                                                            |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \{API_ACCOUNT_ID}     | A [GUID](http://guid.one/) value that identifies your account. This value is automatically generated by Docusign for any account you create. Copy the value from the **API Account ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                               |
| \{BASE_PATH}          | A string value that forms the root of the URL required to make API calls. The base path value in the example code is set to target the developer environment at https\://\<domain>/restapi Where \<domain> is demo.docusign.net for the developer environment and is the result of the GetUserInfo call in production. |
| \{CC_RECIPIENT_EMAIL} | A string value for the email address of the carbon copy recipient.                                                                                                                                                                                                                                                     |
| \{CC_RECIPIENT_NAME}  | A string value for the name of the carbon copy recipient.                                                                                                                                                                                                                                                              |
| \{SIGNER_EMAIL}       | A string value for the email address where the signer will receive a notification of the signing request.                                                                                                                                                                                                              |
| \{SIGNER_NAME}        | A string value for the full name of the signer.                                                                                                                                                                                                                                                                        |
| \{TEMPLATE_ID}        | A [GUID](http://guid.one/) value that identifies a Docusign [template](/docs/esign-rest-api/esign101/concepts/templates) that is used to create a Docusign [envelope](/docs/esign-rest-api/esign101/concepts/envelopes). This value is automatically generated by Docusign when the template is created.               |

## Step 1. Obtain your OAuth token

To make the API call shown in this how-to, you need a valid OAuth access token. Docusign supports access tokens for three different recommended OAuth grant types: Public Authorization Code Grant, Confidential Authorization Code Grant, and JSON Web Token (JWT) Grant. Choose the OAuth grant type appropriate for your scenario.

> **Note**
>
> See [Confidential Authorization Code Grant](/platform/auth/authcode#confidential-authorization-code-grant) for guidance on your options to get an Confidential Authorization Code Grant  OAuth token.

![Three icons that represent the three methods a user can use to obtain an OAuth token: JSON Web Token (JWT), Public Authorization Code Grant (ACG), and Confidential Authorization Code grant](/_fern-files/_img/64f473773042ee439449a096bf7673292b1585b86a4ccc55f82ba0dda41f61a1.webp)

## Step 2. Create an envelope definition from a template

The first step in requesting a signature by email is to create a new envelope definition. Unlike creating an envelope definition without a template, the documents, tabs, and most of the other envelope data will be automatically populated by your chosen template. Instead, you must specify the ID of the template to use and provide the names and emails of the parties acting in each of the roles that the template specifies.

Define a method to create the envelope definition, `makeEnvelope`, with this code.

**`Bash`**

```bash title="Bash"
request_data=$(mktemp /tmp/request-eg-009.XXXXXX)

printf \
'{
    "templateId": "'"${template_id}"'",
    "templateRoles": [
        {
            "email": "'"${SIGNER_EMAIL}"'",
            "name": "'"${SIGNER_NAME}"'",
            "roleName": "signer"
        },
        {
            "email": "'"${CC_EMAIL}"'",
            "name": "'"${CC_NAME}"'",
            "roleName": "cc"
        }
    ],
    "status": "sent"
}' >> $request_data
```

**`C#`**

```csharp title="C#"
public static EnvelopeDefinition MakeEnvelope(
    string signerEmail,
    string signerName,
    string ccEmail,
    string ccName,
    string templateId)
{
    // Data for this method
    // signerEmail
    // signerName
    // ccEmail
    // ccName
    // templateId
    EnvelopeDefinition env = new EnvelopeDefinition();
    env.TemplateId = templateId;

    TemplateRole signer1 = new TemplateRole();
    signer1.Email = signerEmail;
    signer1.Name = signerName;
    signer1.RoleName = "signer";

    TemplateRole cc1 = new TemplateRole();
    cc1.Email = ccEmail;
    cc1.Name = ccName;
    cc1.RoleName = "cc";

    env.TemplateRoles = new List<TemplateRole> { signer1, cc1 };
    env.Status = "sent";
    return env;
```

**`Java`**

```java title="Java"
public static EnvelopeDefinition makeEnvelope(
        String signerName,
        String signerEmail,
        String ccEmail,
        String ccName,
        String templateId) {
    TemplateRole signer = new TemplateRole();
    signer.setEmail(signerEmail);
    signer.setName(signerName);
    signer.setRoleName(EnvelopeHelpers.SIGNER_ROLE_NAME);

    TemplateRole cc = new TemplateRole();
    cc.setEmail(ccEmail);
    cc.setName(ccName);
    cc.setRoleName(EnvelopeHelpers.CC_ROLE_NAME);

    EnvelopeDefinition envelope = new EnvelopeDefinition();
    envelope.setTemplateId(templateId);
    envelope.setTemplateRoles(Arrays.asList(signer, cc));
    envelope.setStatus(EnvelopeHelpers.ENVELOPE_STATUS_SENT);

    return envelope;
}
```

**`Node.js`**

```javascript title="Node.js"
function makeEnvelope(args) {
  // Data for this method
  // args.signerEmail
  // args.signerName
  // args.ccEmail
  // args.ccName
  // args.templateId

  // The envelope has two recipients.
  // recipient 1 - signer
  // recipient 2 - cc

  // create the envelope definition
  let env = new docusign.EnvelopeDefinition();
  env.templateId = args.templateId;

  // Create template role elements to connect the signer and cc recipients
  // to the template
  // We're setting the parameters via the object creation
  let signer1 = docusign.TemplateRole.constructFromObject({
    email: args.signerEmail,
    name: args.signerName,
    roleName: 'signer',
  });

  // Create a cc template role.
  // We're setting the parameters via setters
  let cc1 = new docusign.TemplateRole();
  cc1.email = args.ccEmail;
  cc1.name = args.ccName;
  cc1.roleName = 'cc';

  // Add the TemplateRole objects to the envelope object
  env.templateRoles = [signer1, cc1];
  env.status = 'sent'; // We want the envelope to be sent

  return env;
}
```

**`PHP`**

```php title="PHP"
public static function makeEnvelope(array $args): EnvelopeDefinition
{
    # create the envelope definition with the template_id
    $envelope_definition = new EnvelopeDefinition([
      'status' => 'sent', 'template_id' => $args['template_id']
    ]);
    # Create the template role elements to connect the signer and cc recipients
    # to the template
    $signer = new TemplateRole([
       'email' => $args['signer_email'], 'name' => $args['signer_name'],
       'role_name' => 'signer'
    ]);
    # Create a cc template role.
    $cc = new TemplateRole([
       'email' => $args['cc_email'], 'name' => $args['cc_name'],
       'role_name' => 'cc'
    ]);

    # Add the TemplateRole objects to the envelope object
    $envelope_definition->setTemplateRoles([$signer, $cc]);

    return $envelope_definition;
}
```

**`PowerShell`**

```text title="PowerShell"
@{
    templateId    = "$(Get-Content .\config\TEMPLATE_ID)";
    templateRoles = @(
        @{
            email    = $variables.SIGNER_EMAIL;
            name     = $variables.SIGNER_NAME;
            roleName = "signer";
        };
        @{
            email    = $variables.CC_EMAIL;
            name     = $variables.CC_NAME;
            roleName = "cc";
        };
    );
    status        = "sent";
} | ConvertTo-Json -Depth 32 > $requestData
```

**`Python`**

```python title="Python"
def make_envelope(cls, args):
    """
    Creates envelope
    args -- parameters for the envelope:
    signer_email, signer_name, signer_client_id
    returns an envelope definition
    """

    # create the envelope definition
    envelope_definition = EnvelopeDefinition(
        status="sent",  # requests that the envelope be created and sent.
        template_id=args["template_id"]
    )
    # Create template role elements to connect the signer and cc recipients
    # to the template
    signer = TemplateRole(
        email=args["signer_email"],
        name=args["signer_name"],
        role_name="signer"
    )
    # Create a cc template role.
    cc = TemplateRole(
        email=args["cc_email"],
        name=args["cc_name"],
        role_name="cc"
    )

    # Add the TemplateRole objects to the envelope object
    envelope_definition.template_roles = [signer, cc]
    return envelope_definition
```

**`Ruby`**

```ruby title="Ruby"
def make_envelope(args)
  # Create the envelope definition with the template_id
  envelope_definition = DocuSign_eSign::EnvelopeDefinition.new({
                                                                 status: 'sent',
                                                                 templateId: args[:template_id]
                                                               })
  # Create the template role elements to connect the signer and
  # cc recipients to the template
  signer = DocuSign_eSign::TemplateRole.new({
                                              email: args[:signer_email],
                                              name: args[:signer_name],
                                              roleName: 'signer'
                                            })
  # Create a cc template role
  cc = DocuSign_eSign::TemplateRole.new({
                                          email: args[:cc_email],
                                          name: args[:cc_name],
                                          roleName: 'cc'
                                        })

  check1 = DocuSign_eSign::Checkbox.new(
    tabLabel: 'ckAuthorization',
    selected: true
  )

  check3 = DocuSign_eSign::Checkbox.new
  check3.tab_label = 'ckAgreement'
  check3.selected = true

  text = DocuSign_eSign::Text.new
  text.tab_label = 'text'
  text.value = 'Jabberwocky!'

  # Pull together the pre-filled tabs in a Tabs object
  tabs = DocuSign_eSign::Tabs.new
  tabs.checkbox_tabs = [check1, check3]
  tabs.text_tabs = [text]
  signer.tabs = tabs

  # Add the TemplateRole objects to the envelope object
  envelope_definition.template_roles = [signer, cc]
  envelope_definition
end
```

## Step 3. Create and send the envelope

Next, use the envelope definition you just created in the `makeEnvelope` method to create a new envelope and send it, adding your access token and base path to the request header. Follow these steps:

* Instantiate the Docusign API client.
* Set the following default request header to add your access token to all API calls. `"Authorization" : "Bearer {ACCESS_TOKEN}"`
* Initialize the Envelopes API.
* Create an envelope by passing in the generated envelope definition and your account ID to the `CreateEnvelope` method.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/eSignature/eg009UseTemplate.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/eSignature/Examples/CreateEnvelopeFromTemplate.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/eSignature/services/UseTemplateService.java), [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/eSignature/examples/useTemplate.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/eSignature/UseTemplateService.php), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/eSignature/eg009UseTemplate.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/eSignature/examples/eg009_use_template.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/main/app/services/e_sign/eg009_use_template_service.rb)

**`Bash`**

```bash title="Bash"
response=$(mktemp /tmp/response-eg-009.XXXXXX)

echo ""
echo "Sending the envelope request to DocuSign..."
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @${request_data} \
  --request POST ${base_path}/v2.1/accounts/${account_id}/envelopes \
  --output ${response}
```

**`C#`**

```csharp title="C#"
var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);

EnvelopesApi envelopesApi = new EnvelopesApi(docuSignClient);
EnvelopeDefinition envelope = MakeEnvelope(signerEmail, signerName, ccEmail, ccName, templateId);
var result = envelopesApi.CreateEnvelopeWithHttpInfo(accountId, envelope);

result.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
result.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}

return result.Data.EnvelopeId;
```

**`Java`**

```java title="Java"
public static EnvelopeSummary createEnvelopeTemplate(
        EnvelopesApi envelopesApi,
        String accountId,
        EnvelopeDefinition envelope) throws ApiException {
    var createEnvelopeResponse = envelopesApi.createEnvelopeWithHttpInfo(accountId, envelope,
            envelopesApi.new CreateEnvelopeOptions());
    Map<String, List<String>> headers = createEnvelopeResponse.getHeaders();
    java.util.List<String> remaining = headers.get("X-RateLimit-Remaining");
    java.util.List<String> reset = headers.get("X-RateLimit-Reset");

    if (remaining != null & reset != null) {
        Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
        System.out.println("API calls remaining: " + remaining);
        System.out.println("Next Reset: " + resetInstant);
    }
    return createEnvelopeResponse.getData();
}
```

**`Node.js`**

```javascript title="Node.js"
const sendEnvelopeFromTemplate = async (args) => {
  // Data for this method
  // args.basePath
  // args.accessToken
  // args.accountId

  let dsApiClient = new docusign.ApiClient();
  dsApiClient.setBasePath(args.basePath);
  dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
  let envelopesApi = new docusign.EnvelopesApi(dsApiClient);

  // Make the envelope request body
  let envelope = makeEnvelope(args.envelopeArgs);

  // Call the Envelopes::create API method
  // Exceptions will be caught by the calling function
  let results = await envelopesApi.createEnvelope(args.accountId, {
    envelopeDefinition: envelope,
  }, (error, data, response) => {
      const headers = response?.headers;

      const remaining = headers?.['x-ratelimit-remaining'];
      const reset = headers?.['x-ratelimit-reset'];

      if (remaining && reset) {
        const resetInstant = new Date(Number(reset) * 1000);

        console.log(`API calls remaining: ${remaining}`);
        console.log(`Next Reset: ${resetInstant.toISOString()}`);
      }
  });

  return results.data;
};
```

**`PHP`**

```php title="PHP"
# Create the envelope request object
$envelope_definition = UseTemplateService::makeEnvelope($args["envelope_args"]);

# Call Envelopes::create API method
# Exceptions will be caught by the calling function
$envelope_api = $clientService->getEnvelopeApi();
$envelopeResponse = $envelope_api->createEnvelopeWithHttpInfo($args['account_id'], $envelope_definition);

$remaining = $envelopeResponse[2]['X-RateLimit-Remaining'] ?? null;
$reset =  $envelopeResponse[2]['X-RateLimit-Reset'] ?? null;

if ($remaining !== null && $reset !== null) {
    $resetInstant = (new DateTime())->setTimestamp((int)$reset);
    error_log("API calls remaining: $remaining");
    error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
}

return ['envelope_id' => $envelopeResponse[0]->getEnvelopeId()];
```

**`PowerShell`**

```text title="PowerShell"
Invoke-RestMethod `
    -Uri "${apiUri}/v2.1/accounts/${accountId}/envelopes" `
    -Method 'POST' `
    -Headers @{
    'Authorization' = "Bearer $accessToken";
    'Content-Type'  = "application/json";
} `
    -InFile (Resolve-Path $requestData).Path  `
    -OutFile $response
```

**`Python`**

```python title="Python"
def worker(cls, args):
    """
    1. Create the envelope request object
    2. Send the envelope
    """
    envelope_args = args["envelope_args"]
    # 1. Create the envelope request object
    envelope_definition = cls.make_envelope(envelope_args)

    # 2. call Envelopes::create API method
    # Exceptions will be caught by the calling function
    api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])

    envelope_api = EnvelopesApi(api_client)
    (results, status, headers) = envelope_api.create_envelope_with_http_info(account_id=args["account_id"], envelope_definition=envelope_definition)

    remaining = headers.get("X-RateLimit-Remaining")
    reset = headers.get("X-RateLimit-Reset")

    if remaining is not None and reset is not None:
        reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
        print(f"API calls remaining: {remaining}")
        print(f"Next Reset: {reset_date}")

    envelope_id = results.envelope_id
    return {"envelope_id": envelope_id}
```

**`Ruby`**

```ruby title="Ruby"
def worker
  envelope_args = args[:envelope_args]
  # Create the envelope request object
  envelope_definition = make_envelope(envelope_args)
  # Call Envelopes::create API method
  # Exceptions will be caught by the calling function
  envelope_api = create_envelope_api(args)
  results, _status, headers = envelope_api.create_envelope_with_http_info args[:account_id], envelope_definition

  remaining = headers['X-RateLimit-Remaining']
  reset = headers['X-RateLimit-Reset']

  if remaining && reset
    reset_date = Time.at(reset.to_i).utc
    puts "API calls remaining: #{remaining}"
    puts "Next Reset: #{reset_date}"
  end

  envelope_id = results.envelope_id
  { envelope_id: envelope_id }
end
```

## Expected response

If you run this code example from our Quickstart or launcher projects, you should see a JSON response similar to the code shown.

In addition, the signer receives an email containing a signing link that they can use to open and electronically sign a document using the Docusign mobile app or the Docusign website. After signing is complete, the recipient receives a carbon copy (CC) of the email that includes all of the completed and signed documents.

**`Sample response`**

```json title="Sample response"
{
  "envelopeId": "eead435f-xxxx-xxxx-xxxx-25b7d8523d2b",
  "uri": "/envelopes/eead435f-xxxx-xxxx-xxxx-25b7d8523d2b",
  "statusDateTime": "2020-08-18T23:36:26.8830000Z",
  "status": "sent"
}
```

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* Find out more about [templates](/docs/esign-rest-api/esign101/concepts/templates).
* Learn [How to request a signature using a composite template](/docs/esign-rest-api/how-to/request-signature-composite-template-embedded).
* Review [Working with Templates](https://support.docusign.com/s/document-item?bundleId=xry1643227563338\&topicId=dqj1578456412286.html\&rsc_301) on Docusign Support.
* See how to [Go-Live](/docs/esign-rest-api/go-live) with a completed app and find the base path for API calls in the production environment.