> 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 send an envelope from an Apex trigger

> Learn how to use the capabilities of the Apex Toolkit to send envelopes through an Apex trigger.

This topic demonstrates how to send an envelope using an [Apex trigger](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm).

## Prerequisites

1. Install the [Docusign eSignature for Salesforce](https://appexchange.salesforce.com/appxListingDetail?listingId=a0N30000001taX4EAI) managed package.
2. Create a subdomain for your Salesforce organization by enabling "My Domain."
3. Select the **Docusign Setup** tab and complete the login step.
4. Configure the Contact object within your Salesforce organization with the custom fields necessary to run the code below. In the Object Manager menu, find **Contact** then navigate to **Fields & Relationships** where you can select **New** to add a custom field. Add a new field of type **Picklist** with the label **Docusign_Status**. The picklist needs to have values **Email Docusign**.

## Required data

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

| Data element   | Description                                                                                                                                                                                                                                                                                              |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| \{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. Define your class with an inner class

The accompanying code demonstrates how to define an inner class creating the `EnvelopeSendResponse` object that will be returned by methods defined later in this how-to. The object contains a message string and a boolean status to indicate whether the envelope was sent successfully. The class definition shown here should be used to replace the class stub shown in the class declaration from Step 1.

**`Apex`**

```java title="Apex"
public with sharing class SendEnvelopeFromTriggerController {
    public class EnvelopeSendResponse {

        public String message {get; private set;}
        public Boolean status {get; private set;}

        public EnvelopeSendResponse(final String message, final Boolean status){
            this.message = message;
            this.status = status;
        }
    }
}
```

## Step 2. Write a method to send the envelope

Define a method that will send the envelope when the actions defined in the trigger have been completed. First, use a Salesforce Object Query Language (SOQL) query to get the contact’s information using their source ID. Create a new envelope using the [dfsle.EnvelopeService.getEmptyEnvelope](/docs/salesforce/apex-toolkit-reference/envelopeservice.html) method. Add the customer’s information to a new `dfsle.Recipient` object and add that recipient to the envelope.

Next, create a new document and add it to the envelope. In this example, you create a document representing a Docusign template using the [dfsle.Document.fromTemplate](/docs/salesforce/apex-toolkit-reference/document.html) method and passing in the ID of a valid Docusign template. Then, use the envelope's [dfsle.Envelope.withDocuments](/docs/salesforce/apex-toolkit-reference/envelope.html) method to add the document to the envelope. Finally, send the envelope using the [dfsle.EnvelopeService.sendEnvelope](/docs/salesforce/apex-toolkit-reference/envelopeservice.html) method.

**`Apex`**

```java title="Apex"
public static EnvelopeSendResponse sendEnvelope(final Id mySourceId) {
    EnvelopeSendResponse response;
    try {

    // Capture customer details
    Contact myCustomer = [SELECT Id, Name, Email FROM Contact WHERE Id =:mySourceId];

    // Create an empty envelope
    dfsle.Envelope myEnvelope = dfsle.EnvelopeService.getEmptyEnvelope
    (new dfsle.Entity(mySourceId));

    // Setup recipient data
    dfsle.Recipient myRecipient = dfsle.Recipient.fromSource
    (myCustomer.Name, myCustomer.Email, null, 'Signer 1', new dfsle.Entity(mySourceId));

    // Add Recipient to the Envelope
    myEnvelope = myEnvelope.withRecipients(new List<dfsle.Recipient> { myRecipient });

    // myTemplateId contains the DocuSign Id of the DocuSign Template
    dfsle.UUID myTemplateId = dfsle.UUID.parse('bf7ca600-XXXX-XXXX-XXXX-06e7f3b9e8ce');

    // Create a new document for the Envelope
    dfsle.Document myDocument = dfsle.Document.fromTemplate(
        myTemplateId, // templateId in dfsle.UUID format
        'myTemplate'); // The name of the template

    // Add document to the Envelope
    myEnvelope = myEnvelope.withDocuments(new List<dfsle.Document> { myDocument });

    // Send the envelope
    myEnvelope = dfsle.EnvelopeService.sendEnvelope(
        myEnvelope, // The envelope to send
        true); // Send now?

    response = new EnvelopeSendResponse('Envelope sent successfully', true);
    }
    catch(Exception ex) {
        response = new EnvelopeSendResponse(ex.getMessage(), false);
    }
    return response;
}
```

## Step 3. Create a trigger handler class

The accompanying code defines the class and method that will be called within the trigger. This method will execute the method defined in the previous step, calling the Docusign API to send an envelope. The trigger cannot call the method defined in Step 3 directly because Apex requires that methods with Web Service Callouts are executed asynchronously from triggers. The `@future` annotation is added to this method to ensure that the call to the Docusign eSignature API is made asynchronously.

**`Apex`**

```java title="Apex"
public class DocuSignStatusTriggerHandler{
    @future (callout=true)
      // Handler for Order complete
      public static void handleOrderComplete(final Id contactId) {
          // Call the SendEnvelopeFromTriggerController class sendEnvelope method to invoke the DocuSign API's for sending envelope
          SendEnvelopeFromTriggerController.sendEnvelope(contactId);
      }
}
```

## Step 4. Create a trigger

Finally, create the trigger that will determine the conditions under which the envelope will be sent. This trigger listens for updates on Contact objects and executes the `DocuSignStatusTriggerHandler` class when a Contact’s custom field, **Docusign_Status**, is set to the value **Email Docusign**. Notice that the Docusign_Status field becomes `DocuSign_Status__c` in the code. All custom fields are given the `__c` suffix in the code to differentiate them from default objects and fields. Create a new trigger in the Developer Console by opening the **File** menu and selecting **New**, then **Apex Trigger**. Replace the code that says `before insert` with `after insert, after update, after delete` as shown in the accompanying code. This will allow your trigger to take action after the Contact object has been updated.

**Note:** Unlike the code in other examples, the code in this how-to won’t be executed through the [Developer Console](https://help.salesforce.com/s/articleView?language=en_US\&id=sf.code_dev_console.htm\&type=5) in Salesforce. It will be executed when the conditions defined by the trigger are met. To run this code, edit a Contact object in Salesforce and set its **Docusign_Status** field to **Email Docusign**.

> **Note**
>
> View the source code for this how-to on GitHub: [Apex](https://github.com/docusign/code-examples-apex/blob/master/force-app/main/default/classes/SendEnvelopeFromTriggerController.cls).

**`Apex`**

```java title="Apex"
trigger Trigger_ContactAfterUpdate on Contact (after insert, after update, after delete) {
        if (trigger.isUpdate)
    {
        for(contact aC : trigger.new)
        {
            if (aC.DocuSign_Status__c=='Email DocuSign') // Test Field called on the contact. This is not a DocuSignStatus Object
            {
                 DocuSignStatusTriggerHandler.handleOrderComplete(aC.Id);
            }
        }
    }
}
```

## Next steps

* See all available Apex Toolkit [How-to guides](/docs/salesforce/how-to).
* Learn [How to send an envelope](/docs/salesforce/how-to/send-envelope).
* See [How to perform unit testing](/docs/salesforce/how-to/unit-testing) to ensure that you have adequate code coverage.