Mail Merge is a feature of Microsoft Word for quickly and easily creating documents like letters, labels and envelopes. Aspose.Words Cloud takes the standard mail merge and advances it many steps ahead, turning it into a full-fledged reporting solution that allows you to generate even more complex documents such as reports, catalogues, inventories, and invoices. The advantages of the Aspose.Words Cloud reporting solution are:

  • Design reports in Microsoft Word using standard mail merge fields
  • Define regions in the document that grow such as detail rows of an order
  • Insert images during mail merge
  • Insert HTML during mail merge

Basic Steps

Steps to perform a mail merge are quite easy. First, you use Microsoft Word to create and design a Word document normally called a template. Note that the document does not have to be a Microsoft Word Template (.dot), it can be a normal .doc document. You insert some special fields called merge fields into the template in places where you want data from your data source to be later inserted. Then with Aspose.Words REST API you execute a mail merge operation. The mail merge operation will take data from your data source and merge it into the document.

You can also designate repeatable merge regions in the document or insert special merge fields that allow you to insert other content such as images. Depending on how you set up mail merge fields and repeatable regions inside the document, the document will grow to accommodate multiple records in your data source. If you do not use mail merge regions, then the mail merge will be similar to Microsoft Word mail merge and the whole document content will be repeated for each record in the data source. Using repeatable mail merge regions, you can designate portions inside a document that will be repeated for each record in the data source. For example, if you mark a table row as a repeatable region then this table row will be repeated, causing the table to dynamically grow to accommodate all of your data.

Prepare a Document

Before you execute a mail merge, you need to prepare the document template. You should insert merge fields that will be replaced with values from your data source.

Inserting Merge Fields into a Document

To Insert Merge Fields into a Document:

  1. Open your document in Microsoft Word.
  2. In the document, click where you want to place a merge field.
  3. Open the Insert menu and select Field to open the Field dialog.
  4. From the Field names list, select MergeField.
  5. In the Field name text box, enter a name for the merge field and press OK.

Since a merge field is a regular Microsoft Word field, you can switch between displaying field codes and results in your document in Microsoft Word using the keyboard shortcut Alt+F9. Field codes appear between curly braces.

Simple Mail Merge

In order to prepare your template to perform a simple mail merge (without regions, similar to the classic mail merge available in Microsoft Word) you should just insert one or more merge fields in the places you want to be populated with data from the data source.

Let us take a look at the Dinner Invitation demo. It creates a letter for a list of clients defined in the data source. The template contains a number of merge fields that are populated from two data sources; in other words, two mail merges are performed one after the other. First, data from the first data source is merged into the template. This data source contains only one row because this is information about the inviter, so the whole document content is not repeated and only the appropriate fields are filled with data. Then the second mail merge operation is executed. The data source it uses contains information about the clients. The whole template is repeated for each data row and every repeated copy is populated with the corresponding client’s data.

mail merge

As a result, we have a document that consists of five filled-in, complete, and personalized invitation letters (a fragment of the very first one is shown below):

perform mail merge

As you can see, it is possible, and sometimes useful to perform more than one merge operation with the same template to add data in stages. You can insert NEXT fields in the Word document to cause the mail merge engine to select the next record from the data source and continue merging. When the engine encounters a NEXT field, it just selects the next record in the data source and continues merging without copying any content. This can be used when creating documents such as mailing labels.

The code to perform Simple Mail Merge is given below:

Mail Merge with Regions

If you want to dynamically grow portions inside the document, use mail merge with regions. To specify a mail merge region in the document you need to insert two mail merge fields to mark the beginning and end of the mail merge region. All document content that is included inside a mail merge region automatically will be repeated for every record in the data source.

To mark the beginning of a mail merge region, insert a MERGEFIELD with the name TableStart:MyTable, where MyTable corresponds to the tag or key in XML or JSON respectively. To mark the end of the mail merge region insert another MERGEFIELD with the name TableEnd:MyTable. Between these marking fields, place merge fields that correspond to the fields of your data source. These merge fields will be populated with data from the first row of the data source, then the whole region will be repeated, and the new fields will be populated with data from the second row, and so on.

Follow these simple rules when marking a region:

  • TableStart and TableEnd fields must be inside the same section in the document
  • If used inside a table, TableStart and TableEnd must be inside the same row in the table
  • Mail merge regions can be nested inside each other
  • Mail merge regions should be well formed (there is always a pair of matching TableStart and TableEnd with the same table name)

As an example, have a look at the Item Catalog demo. Here is a fragment of a region prepared for mail merge:

mail merge

Note that both the marking fields TableStart:Item and TableEnd:Item are placed inside the same row of the Word table. After executing the mail merge, here is the result:

Simple mail merge

The code to perform Mail Merge with Regions is given below:

Mail Merge using ‘Mustache’ Template Syntax

This syntax allows you to create templates for use with mail merge that use plain text markers instead of merge fields. These markers look like this: {{ FieldName }}

Object.Attribute Syntax

You can easily merge attributes of fields using the following syntax:

  {{ Address.Street }}  

This will merge data from XML data which looks like this:

<Order> // <-- Current context is here.  
    <Street>Nelson Street</Street>  
  <PhoneNumber>543 1234</PhoneNumber>  

Foreach Blocks

You can merge data from multiple records using the foreach tag. This is similar to mail merge regions with conventional merge fields. You can nest such blocks.

{{ #foreach Order }}  
  {{ Number }}  
    {{ Address.Street }}  
      {{ #foreach Item }}  
        {{ Description }} {{ Cost}} {{ Total }}  
      {{/foreach Item }}  
{{ /foreach Order }} 

You can also mix these fields and place them inside other Microsoft Word fields such as IF or Formula fields.

Conditional Block

You can use mail merge with IF statement using Aspose.Words Cloud. The IF block executes only if the Boolean expression associated with it is true. The syntax of IF is shown below.

{ IF "{{ GENDER }}" = “MALE” “true text” “false text” }

The code to perform Mail Merge using ‘Mustache’ Template is given below:

Insert HTML During Mail Merge

Both executeMailMerge and executeTemplate APIs provide support for inserting HTML on a merge field. You just need to make sure you escape HTML characters in data source string and use “format”=“html” attribute as shown below:

  "dataSourceList": {   
    "contractDS": {  
      "contractDescription": {  
        "htmlText": "<b>Test me 1<br><br><i>Test me 2<br><br><u>Test me 2</u></i></b><br>"         

Following code shows how to insert HTML during mail merge:

Insert Images During Mail Merge

You can also insert images on a merge field. Scale factor for images can be set using ‘%’, ‘px’ or ’’ (proportional scaling). The code to insert images during Mail Merge is given below:

Cloud SDKs

Although the above code is in .NET, Aspose.Words Cloud SDKs are available in five different languages: .NET, Java, Ruby, Python and Node.js. Therefore, you can conveniently call Mail Merge APIs in any of these languages.

Suggested Post:

Execute Mail Merge in PHP