> 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 bulk send envelopes with merge fields and data writeback

> Learn how to use the Apex Toolkit to bulk send envelopes with merge fields.

This topic demonstrates how to use the Apex Toolkit to bulk send envelopes with merge fields. Merge fields work differently with bulk sending. The following code will demonstrate how to configure your bulk envelopes with merge fields that write data back to your Salesforce objects.

## Prerequisites

1. Install the [Docusign eSignature for Salesforce](/docs/salesforce/how-to/apex-toolkit-install)  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.

## 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. Create your template with merge fields

[Create a template](https://support.docusign.com/s/document-item?language=en_US\&bundleId=srl1586134368658\&topicId=uce1617376465289.html&_LANG=enus) in the Docusign Apps Launcher. The code in this example requires that your template has a recipient defined by the role “Signer.” If you don’t already have merge fields in your Salesforce account, go to the **Merge Fields** step while editing your template to [create merge fields](https://support.docusign.com/s/document-item?language=en_US\&bundleId=srl1586134368658\&topicId=jdl1611042391715.html&_LANG=enus). The source object for all of the new merge fields should be the Contact object and you will need to create 3 new merge fields, one for each of the following fields on the Contact object: First Name, Last Name, and Title. Later in this example you will build a bulk contact list of recipients whose information will come from Contacts in Salesforce and the merge fields will use these Contacts as their source objects. Be sure to select **Allow Writeback to Salesforce** when you create your merge fields. Place the fields on the document in the **Place fields** step.

![The screen where the user defines a role for the template](/_fern-files/_img/9cd026a3881ce7feebb3a69b09a02a9b7b8d2470ad9a64668a846b2ba18794f8.webp)

## Step 2. Create your envelope custom fields

Create two [envelope custom fields](https://support.docusign.com/s/document-item?language=en_US\&rsc_301=\&bundleId=pik1583277475390\&topicId=mvu1583277383029.html&_LANG=enus) in your Docusign account. Go to Docusign eSignature Settings and select **Envelope Custom Fields** in the **Signing and Sending** section. Add two fields with the field type “Text.” One of the fields should have the name “##SFDocumentWriteBack” and the other should have the name “##SFSource.” You will add these fields to your bulk envelope in your Apex code.

![The envelope custom fields in the Docusign UI](/_fern-files/_img/61aa9e6542cc5990a947af98f7faaa66a575aa43d80888bede9224b22ca72e03.webp)

## Step 3. Add a custom field to your contact object in Salesforce

In this example, the bulk contact list is created with a SOQL query that looks for all Contacts that have the Bulk_Send\_\_c field set to true. Bulk_Send\_\_c is a custom field on the Contact object. To add a custom field, open the [Object Manager](https://help.salesforce.com/s/articleView?id=sf.extend_click_find_objectmgmt_lex.htm\&type=5) and find the Contact object. Select **Fields & Relationships** and select **New**. Choose **Checkbox** for the data type and name the field Bulk_Send as shown in the accompanying screenshot. Salesforce appends \_\_c to the names of custom fields and objects, so when you access the field through Apex code, you will use Bulk_Send\_\_c.

![The Salesforce Object Manager UI](/_fern-files/_img/56c49b21ace704d434a4eec7337ddc03d67aae0b604b6320b54a8a3185d5bad3.webp)

## Step 4. Build your bulk contact list

Create the bulk send list with the contact information for each recipient. This list may be based on any group construct and contains copies of the envelope to be sent. A recipient note, authentication options, and email subject and message may be set for each copy, but each copy must have exactly one recipient.

In this example, the contact list is built from a SOQL query that looks at the value of the Bulk_Send checkbox field from the previous step. Contacts with the checkbox checked will be added to the Bulk List. For the purposes of this example, the list is limited to five recipients.

The accompanying code demonstrates how to create a new envelope definition for each contact in the bulk list. Create two new [dfsle.CustomField](/docs/salesforce/apex-toolkit-reference/customfield.html) objects to match the envelope custom fields created in step 2. Set the value of the custom field named ##SFSource to the ID of the Contact concatenated with ~~Contact. Set the value of the custom field named ##SFDocumentWriteback to ID of the Contact concatenated with ~~NamePDF~~0~~1. These values are required to allow data writeback in the merge fields on the envelope. Use the [dfsle.Envelope.withCustomFields](/docs/salesforce/apex-toolkit-reference/envelope.html) method to add the custom fields to the bulk copy. Be sure to add the 'Signer' role to the recipients using the withRole method to match the role in your template.

**Note:** Each created bulk list persists both in Salesforce and Docusign and may be reused to send multiple envelopes. The list definition can be updated when the underlying group membership changes with [dfsle.BulkSendService.updateLists](/docs/salesforce/apex-toolkit-reference/bulksendservice.html), or it may be removed with [dfsle.BulkSendService.deleteLists](/docs/salesforce/apex-toolkit-reference/bulksendservice.html) when no longer relevant.

**`Apex`**

```java title="Apex"
@AuraEnabled
public static Id buildList(){

    List<dfsle.Envelope> myBulkCopies = new List<dfsle.Envelope>();
    //SOQL is used to gather up the list of recipients to send to. In this case we get all contacts who have the bulk send checkbox set as true
    for (Contact m : [SELECT Contact.FirstName, Contact.LastName, Contact.Email, Contact.Id FROM contact where contact.Bulk_Send__c = true LIMIT 5])
    {

        //To use merge fields and document writeback with bulk sending we have to add in the following custom fields. You first need to add them to your account under "Settings" -> "Envelope Custom Fields"
        // You need to create two envelope custom fields with the Field Name set as ##SFSource and ##SFDocumentWriteBack
        // https://developers.docusign.com/docs/salesforce/apex-toolkit-reference/customfield.html
        dfsle.CustomField sourceId = new dfsle.CustomField('text', '##SFSource', m.Id+'~Contact', null, false, true); // DocuSign custom field to capture Salesforce record Id. Replace ##SFSource with the name for your custom field
        dfsle.CustomField writeBackId = new dfsle.CustomField('text', '##SFDocumentWriteBack', m.Id+'~NamePDF~0~1', null, false, true); // DocuSign custom field to initiate document write back to Salesforce.

        //Create our recipients for the envelope
        myBulkCopies.add(dfsle.Envelope.newBulkCopy(
            dfsle.Recipient.newBulkRecipient(
                m.FirstName + ' ' + m.LastName,
                m.Email,
                null) // Source Salesforce object
            //The role needs to match up exactly with the role on your template.
            .withRole('Signer'))
            .withCustomFields(new List<dfsle.CustomField>{ sourceId, writeBackId })); // DocuSign Custom Fields
    }
    // Create the bulk list. This list persists after sending and may be reused for multiple batches of envelopes
    dfsle.BulkList myList = dfsle.BulkSendService.createLists(new List<dfsle.BulkList> {
        dfsle.BulkList.newList(
            'My bulk list', // List name
            myBulkCopies, // Envelope copies
            null) // The Salesforce source object
            })[0];
    // Save the ID for later operations
    Id myListId = myList.id;
    System.debug(LoggingLevel.INFO, myListId);
    return myListId;

}
```

## Step 5. Bulk send the envelopes

Once a list has been created, create an envelope with the document(s) you wish to send. You can use a Docusign [template](/docs/esign-rest-api/esign101/concepts/templates) as the document or use a document that leverages [Auto-place (anchor tagging)](/docs/esign-rest-api/esign101/concepts/tabs/auto-place) to add a recipient’s information automatically to generic tags within a document.

Be sure to replace the value for myTemplateId with the ID of the template created in step 1. To find the template ID, go to the Docusign Apps Launcher and choose the **Docusign Envelope Templates** tab. Select the template you want to use and copy the **Docusign template ID** GUID under the **Details** tab.

Next, use the [dfsle.BulkSendService.sendEnvelope](/docs/salesforce/apex-toolkit-reference/bulksendservice.html)  method to bulk send the envelope to each member in the list you created previously, as demonstrated in the accompanying code. These steps need to be done within an [@future](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_invoking_future_methods.htm) method to prevent the code from failing due to Apex's DML and callout limitations.

**`Apex`**

```java title="Apex"
@future(callout=true)
/**
*  bulkSendEnvelopes method
*  Use myListId from buildList method
*/
public static void bulkSendEnvelopes(Id myListId){

    dfsle.UUID myTemplateId = dfsle.UUID.parse('3df1fb4c-xxxx-xxxx-xxxx-cdf3cb0fe6b1'); // Substitute with your template ID
    dfsle.Document myDocument = dfsle.Document.fromTemplate(
        myTemplateId, // templateId in dfsle.UUID format
        'myTemplate'); // name of the template

    // Create the draft bulk envelope. This will have exactly one placeholder bulk recipient
    dfsle.Envelope myEnvelope = dfsle.BulkSendService.getDraftEnvelope(
        new List<dfsle.Document> { myDocument },	null); // Optional Salesforce source entity

    // Send envelope with a placeholder bulk recipient
    dfsle.BulkList.Result myResult = dfsle.BulkSendService.sendEnvelope(myListId, myEnvelope);
    System.debug(myResult);
}
```

## Step 6. Execute your methods

To execute your code, go to the [Developer Console](https://help.salesforce.com/s/articleView?language=en_US\&id=sf.code_dev_console.htm\&type=5) in Salesforce, open the **Debug** menu, then select **Open Execute Anonymous Window**. Type the accompanying code in the window and select **Execute**.

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

**`Apex`**

```java title="Apex"
Id myListId = BulkSendWriteback.buildList();
BulkSendWriteback.bulkSendEnvelopes(myListId);
```

## Expected response

If your API call is successful, envelopes will be sent to the emails of the Salesforce contacts in your bulk list. When the recipient opens the envelope, they will see a tab containing the name of the opportunity that was used to create the merge field. If the recipient edits the text in the tab, the opportunity name in your Salesforce org will be updated accordingly.

## Next steps

* See all available Apex Toolkit [How-to guides](/docs/salesforce/how-to).
* Learn more about [Bulk sending envelopes](/docs/esign-rest-api/esign101/concepts/envelopes/bulk-send).
* See [How to bulk send envelopes](/docs/salesforce/how-to/bulk-send).
* Learn [How to send an envelope with merge fields](/docs/salesforce/how-to/send-envelope-with-merge-fields).
* See [How to perform unit testing](/docs/salesforce/how-to/unit-testing) to ensure that you have adequate code coverage.