Automatic Mail-Merge Document Creation Using Zoho CRM APIs

Automatic Mail-Merge Document Creation Using Zoho CRM APIs

Efficient communication and personalized document generation are crucial for maintaining strong customer relationships in your business. Manual document generation can be time-consuming, repetitive and error-prone, decreasing productivity and customer satisfaction. You can solve this with automatic document generation by creating merged documents from predefined mail merge templates.
With Zoho CRM's mail merge templates you can create personalized documents, including forms, envelopes, and letters, by utilizing variables also known as merge fields. These templates enable you to merge data from variables, ensuring accurate information is incorporated into the documents without the need for manual data entry for each record. For additional information, please consult the guidelines on Managing Mail Merge Templates. 

In Zoho CRM, you can automate document generation using its mail merge template APIs. You can send, sign, and download customized documents automatically. 
Send Mail Merge API : To send emails to users using mail merge template. You can also attach files either as inline images or separate attachments with the email through the API.
Sign Mail Merge API : To sign and approve a merged document.
Download Mail Merge API: To download a mail merged document.

Let us discuss two use cases where these APIs are used. Assume you manage your business for a technological company, Zylker Technologies, using Zoho CRM. 

Prerequisites
  • Create a connector with required scopes. For the below use cases a connector with the below scopes was created -ZohoSign.documents.ALL, ZohoCRM.modules.ALL, ZohoWriter.documentEditor.ALL, ZohoWriter.Merge.ALL, ZohoCRM.settings.mailmerge.CREATE

Use Case 1: Using Mail Merge APIs for sending Letter of Intent for customers
 Let us consider a scenario where you want to send a LOI (Letter of Intent) to be signed by your customer. A Letter of Intent is a formal document that contains a preliminary agreement and commitment to move forward with the deal, outlining key terms and conditions. You can create a mail merge template for your LOI with merge fields from your Customer module. You can find mail merge templates in Zoho CRM UI under Setup > Customization > Templates > Mail Merge. Refer the below image for a sample LOI mail merge template. 

Sample Mail Merge Template for Letter of Intent

Note that the merge fields given in the mail merge template are fields from Accounts module (renamed as Customers) with additional custom fields.
You can automate sending the LOI to your customer using a custom button with an associated function for the Customers module. In this case, a custom button "send LOI" is added as shown in the screenshot below.
Screenshot of Customer module showing sendLOI button

The below function calls sign mail merge API which sends the merged letter of intent document to your customer for signing.  The customer will receive an email notification containing the document which can be signed using Zoho Sign. Sign mail merge API's response includes a Zoho Writer document link that can be used to track the signing status. In the below function, the system will send mail to the customer along with the mail-merged document for them to sign, and it will store the link to track the sign status in a custom URL field named Document Sign Details.  This field allows you to access and review the document from your record conveniently.

customerMap = zoho.crm.getRecordById("Accounts",customerId.toLong());
name = customerMap.get("Account_Name");
to_email = customerMap.get("customer_Email");
merge_template_name = "LOI";
//Replace with your mail merge template name
info name;
info to_email;
input_json = "{'sign_mail_merge':[{'mail_merge_template':{'name':'" + merge_template_name + "'},'file_name':'letterofintent','sign_in_order':false,'signers':[{'recipient_name':'" + name + "','action_type':'sign','recipient':{'type':'email','value':'" + to_email + "'}}]}]}";
header_data = Map();
header_data.put("Content-Type","application/json");
response = invokeurl
[
url :"https://www.zohoapis.com/crm/v5/Accounts/" + customerId.toLong() + "/actions/sign_mail_merge"
type :POST
parameters:input_json
connection:"zylkercrm"
];
//Replace above connection name with your connection name
info response;
details = response.getJSON("sign_mail_merge").toJSONList();
link = "";
for each  detail in details
{
link = detail.get("details").get("report_link");
info link;
}
mp = Map();
mp.put("Document_Sign_Details",link);
update = zoho.crm.updateRecord("Accounts",customerId.toLong(),mp);
return "";

The system sends a merged document, as shown in the screenshot below, to the customer.
Final Merged Document sent to Customer

Use case 2: Using mail merge API for sending different types of SLA 
Assume that in Zylker Technologies, when you sell a product, your customer can opt for different types of after sales support . A check list field - Support Type - indicates type of support - Standard or Premium.  SLA document(Service Level Agreement) is a contract between you and your customer that defines level of service and the metrics used to measure the service.The service level provided to different customers will be different based on the kind of support they opted for and you need to send different SLA document based on this.  This can be achieved by maintaining two SLA mail merge templates. 
Similar to use case 1, a custom button can invoke the below function and in the function, a mail merge template is selected based on the type of service provided. The support_Type fields gets the value of the "Support Type" check list. Merge mail template is decided based on this field and send mail merge API is called to send the merged document. After sending the mail with appropriate mail merge template document, the function downloads the merged document and uploads it to the Attachments related list. 
Using download mail merge API, the merged document is obtained and then attached to the Contacts module with the attachFile function.


customerMap = zoho.crm.getRecordById("Accounts",customerId.toLong());
to_email = customerMap.get("customer_Email");
from_email = customerMap.get("Owner").get("email");
support_Type = customerMap.get("Support_Type");
if (support_Type == "Premium" )
{
merge_template_name = "SLA_Premium";
}
else 
{
merge_template_name = "SLA_Std";
}
//Replace above merge template names with your merge template names
input_json = "{'send_mail_merge':[{'mail_merge_template':{'name':'" + merge_template_name + "'},'from_address':{'type':'email','value':'" + from_email + "'},'to_address':[{'type':'email','value':'" + to_email + "'}],'subject':'Hi there','type':'attachment','attachment_name':'testdocument','message':'Big Deal'}]}";
header_data = Map();
header_data.put("Content-Type","application/json");
response = invokeurl
[
url :"https://www.zohoapis.com/crm/v5/Accounts/" + customerId + "/actions/send_mail_merge"
type :POST
parameters:input_json
connection:"zylkercrm"
];
//Replace above connection name with your connection name
input_json = "{'download_mail_merge':[{'mail_merge_template':{'name':'" + merge_template_name + "'},'output_format':'pdf'}]}";
header_data = Map();
header_data.put("Content-Type","application/json");
//The merged document is stored to file_object
file_object = invokeurl
[
url :"https://www.zohoapis.com/crm/v5/Accounts/" + customerId.toLong() + "/actions/download_mail_merge"
type :POST
parameters:input_json
connection:"zylkercrm"
];
//Replace above connection name with your connection name
response = zoho.crm.attachFile("Accounts",customerId,file_object);
return "";

The benefits of using the mail merge template APIs from Zoho CRM, which enable automated document generation, are highlighted in this article. These APIs enable the easy customization of the documents like Letters of Intent (LOIs), Service Level Agreements (SLAs), Request for Proposal (RFPs), etc. Businesses can increase efficiency, accuracy, and customer happiness by automating this procedure.
We hope you found this article useful. We will be back next week with another interesting topic. If you have any questions, write to us at support@zohocrm.com or let us know in the comment section. 

    Access your files securely from anywhere







                            Zoho Developer Community





                                                  Use cases

                                                  Make the most of Zoho Desk with the use cases.

                                                   
                                                    

                                                  eBooks

                                                  Download free eBooks and access a range of topics to get deeper insight on successfully using Zoho Desk.

                                                   
                                                    

                                                  Videos

                                                  Watch comprehensive videos on features and other important topics that will help you master Zoho Desk.

                                                   
                                                    

                                                  Webinar

                                                  Sign up for our webinars and learn the Zoho Desk basics, from customization to automation and more

                                                   
                                                    
                                                  • Desk Community Learning Series


                                                  • Meetups


                                                  • Ask the Experts


                                                  • Kbase


                                                  • Resources


                                                  • Glossary


                                                  • Desk Marketplace


                                                  • MVP Corner




                                                            • Sticky Posts

                                                            • Kaizen #197: Frequently Asked Questions on GraphQL APIs

                                                              🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
                                                            • Kaizen #198: Using Client Script for Custom Validation in Blueprint

                                                              Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
                                                            • Celebrating 200 posts of Kaizen! Share your ideas for the milestone post

                                                              Hello Developers, We launched the Kaizen series in 2019 to share helpful content to support your Zoho CRM development journey. Staying true to its spirit—Kaizen Series: Continuous Improvement for Developer Experience—we've shared everything from FAQs
                                                            • Kaizen #193: Creating different fields in Zoho CRM through API

                                                              🎊 Nearing 200th Kaizen Post – We want to hear from you! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
                                                            • Client Script | Update - Introducing Commands in Client Script!

                                                              Have you ever wished you could trigger Client Script from contexts other than just the supported pages and events? Have you ever wanted to leverage the advantage of Client Script at your finger tip? Discover the power of Client Script - Commands! Commands


                                                            Manage your brands on social media



                                                                  Zoho TeamInbox Resources



                                                                      Zoho CRM Plus Resources

                                                                        Zoho Books Resources


                                                                          Zoho Subscriptions Resources

                                                                            Zoho Projects Resources


                                                                              Zoho Sprints Resources


                                                                                Qntrl Resources


                                                                                  Zoho Creator Resources



                                                                                      Zoho CRM Resources

                                                                                      • CRM Community Learning Series

                                                                                        CRM Community Learning Series


                                                                                      • Kaizen

                                                                                        Kaizen

                                                                                      • Functions

                                                                                        Functions

                                                                                      • Meetups

                                                                                        Meetups

                                                                                      • Kbase

                                                                                        Kbase

                                                                                      • Resources

                                                                                        Resources

                                                                                      • Digest

                                                                                        Digest

                                                                                      • CRM Marketplace

                                                                                        CRM Marketplace

                                                                                      • MVP Corner

                                                                                        MVP Corner







                                                                                          Design. Discuss. Deliver.

                                                                                          Create visually engaging stories with Zoho Show.

                                                                                          Get Started Now


                                                                                            Zoho Show Resources


                                                                                              Zoho Writer Writer

                                                                                              Get Started. Write Away!

                                                                                              Writer is a powerful online word processor, designed for collaborative work.

                                                                                                Zoho CRM コンテンツ








                                                                                                  Nederlandse Hulpbronnen


                                                                                                      ご検討中の方




                                                                                                            • Recent Topics

                                                                                                            • Engineering Change Order Process using Tickets?

                                                                                                              Hi Zoho Community, I'm working with my company to create an Engineering Change Order/Request (ECO/ECR) process where engineers can internally create tickets for changes in a product that must be reviewed, approved and implemented by people or teams in
                                                                                                            • How can I move a ticket from Department A to Department B?

                                                                                                              Hi there, how do I move ticket from Department A to Department B? I went in the ticket and tried to scroll down the menu under the "department" but it won't let me, I am a support admin. Did I do anything wrong? or am I doing it in the wrong place?
                                                                                                            • Validation Rules Trigger on Untouched Fields

                                                                                                              In Zoho Desk, validation rules trigger for ALL fields during an update—even fields that weren't modified in the current edit. This behavior is fundamentally different from Zoho CRM and other Zoho products, where validation rules only apply to fields actually
                                                                                                            • How to work with getFieldNames formdata functions ,Any Examples

                                                                                                              I don't find any example showing usage of getFieldNames. Where do i find .is there any Help documents available
                                                                                                            • Zoho Notifications - Received two notifications for one message and none for the other

                                                                                                              We had a client reply to a ticket twice in one minute. The ticket owner received two emails for the second message but none for the first (which was crucial content and unfortunately was therefore missed). I'm assuming this created a race condition -
                                                                                                            • What is the difference between "Reply" and "Public Comment" in a ticket?

                                                                                                              Hey, my company is thinking about switching to Zoho Desk but we do not understand the difference between the "Reply" and the "Public Comment" feature. When should we use which? And why? What is the difference between them? Thank you for your help! Kindest
                                                                                                            • Tasks View for Opportunity/Jobs does not indicate "Related To" account

                                                                                                              How can ZoHo be setup so that when a task is created for an Opportunity, the subject automatically lists the underlying account? Right now, it's impossible to link the Account to the task when the task is created from the Job.  Therefore, the open task view is inadequate.  And it's a lot of maintenance to have to manually add the account to the subject...defeating the purpose of "Automated" workflow. 
                                                                                                            • can i show alert when i finish running the function?

                                                                                                              how i can show alert inside the custom function or popup notification. when i use alert inside the custom function it show this error Error at line number:  2 'ALERT' task can be used only in on load, on validate and on change actions ​
                                                                                                            • CRM calendar not syncing with Zoho Calendar

                                                                                                              The sync is not happening: This is my Zoho Calendar CalDAV synced with Outlook This is my Zoho CRM Calendar (sadly empty ...) I have enabled CalDAV Access. In Zoho Calendar, I have set up APP Calendar sync like this: What else can I check? Thank
                                                                                                            • Pipeline in Custom Modules

                                                                                                              I love the way the Sales Pipeline looks and functions with reports. I would like to add the save pipeline features and visualization to a custom module, however, I only see that these pipelines are only available for the Deals module. Is there a way to add pipelines to custom modules?
                                                                                                            • Cannot associate event with other objects when creating?

                                                                                                              I am attempting to associate an Event with one or more other objects when creating it via the API. According to the API docs, the "Related_To" property is a jsonobject even though the description says "Provide the details about the entities the event
                                                                                                            • How to disable subform records dynamically

                                                                                                              Hi Everyone I have a requirement to dynamically disable or hide subform fields based on certain criteria. However, the code I tried didn't work as expected. It either disabled or hid all the fields in all subform records or none at all. What I actually
                                                                                                            • Client Script Operate Timeout

                                                                                                              Hi Zoho, I have set a client script that use for ( i =1; length < i , i++) to fetch all of the product in order I have an order have 30+ products, seems this script will be stopped when it is checking rough 10 + products because of timeout (may be). May
                                                                                                            • Why and When to Manually Regenerate Reports?

                                                                                                              What is the protocol for needing to regenerate reports?  It is very confusing when data in reports pulls correctly sometimes, but are inaccurate other times.   Why is report regenerating necessary at all - can the report function not read the live data as inputted into the forms?  We have built lots of reports and it is very tedious and time consuming to have to regenerate the report before each use of that data to make sure it is accurate.  Is there a way to know when a report should or shouldn't
                                                                                                            • Import template from Zoho Writer

                                                                                                              I am trying to import a mail merge template - tried to import direct from my .docx file on my hard drive and the formatting went all over the place. I then imported the .docx file in my Zoho Docs and then fixed up the formatting within Zoho Writer. Can
                                                                                                            • Button Duplication when emails forwarded or replied

                                                                                                              When I create a new email template in campaigns and send it out it looks fine to all the users, however if that email is then on forwarded or replied to then all buttons within the email duplicate.  See below The one on the left is the original one.
                                                                                                            • Enhancements to Custom Connectors in Zoho Creator

                                                                                                              Hello everyone, At Zoho Creator, we believe in providing you with the necessary tools to achieve a well connected ecosystem of apps. Our Custom Connectors feature is a testament to this, enabling you to integrate with a wide range of external services
                                                                                                            • AutoScan Not Working Since April -Support says it with engineering

                                                                                                              Hi there, Autoscan has not been working on my account since April. Without this feature, completing expenses reports is laborious and error-prone. I keep asking for updates seeing as this is a critical feature, but told that it's being looked into and
                                                                                                            • Zoho books bulk update for invoices

                                                                                                              Hi Zoho team, Why only 25 invoices can be bulk update at a time. I am booking 800 to 900 invoices in a month. Please increase this limit? Please dont tell that you dont have enough request for this task. 25 limit for bulk update is too much low
                                                                                                            • Querying CloudSQL using NodeJS?

                                                                                                              How can I query CloudSQL over nodejs? Are there any rest apis from which I perform Select Queries in the data of a Workspace? In the v1 we had C#, Python, Java for CloudSQL Now I only see Java? I am confused about the overall API of Analytics, there any
                                                                                                            • Rename Record Templates in Zoho Creator

                                                                                                              Hi Team, I need to rename the Record Templates based on the name of the employee which i have configured in Zoho Creator Deluge Script. How to do this one? // Attachments :template:PDF_ECF:Exit_Clearance_Form input.ID as PDF
                                                                                                            • Les Zoholics 2025 sont de retour

                                                                                                              Bonjour à tous, Préparez-vous pour deux jours exceptionnels au cœur de l’écosystème Zoho ! Nous avons le plaisir de vous convier à Zoholics France 2025, un événement dédié à l’innovation, à l’expertise et à la communauté Zoho. Au programme : • Présentations
                                                                                                            • Salutation

                                                                                                              Hey there, I want to make an indvidual salutation. It is possible to use if statements in the email templates? For exampe: When is male then wirte "Dear Mr." else write "Dear Mrs." Thanks David
                                                                                                            • Personal Expenses

                                                                                                              I have reviewed the board and found a few scenarios like mine however not exactly so sorry if this is a re-post.  I just recently joined Zoho Books and had to go through 2000 transactions manually which took FOREVER. So the dilemma that I am facing is that I have attached my personal and business checking cards to my account because it was not until half way through 2015 that I decided to open up a business account as an independent contractor.  When I first started my account I placed the opening
                                                                                                            • Not receiving instagram verfication emails

                                                                                                              Hi- I'm not receiving Not receiving instagram verfication emails.  I have seen other users having the same issue and your answer was to contact instagram.  But instagram no longer has a support email.  
                                                                                                            • Change work hours per day for employees

                                                                                                              Hello, Is there a way to modify the work hours per day for employees in Zoho projects? This would be helpful for resource allocation to more accurately see when an employee who works 35 hours a week vs 40 hours has a full schedule. Thanks.
                                                                                                            • Zoho Commerce

                                                                                                              Hi, I have zoho one and use Zoho Books. I am very interested in Zoho Commerce , especially with how all is integrated but have a question. I do not want my store to show prices for customers that are not log in. Is there a way to hide the prices if not
                                                                                                            • PROBLEMA AL CONECTAR EL DOMINIO

                                                                                                              hola buenas tardes hoy estoy tratando de crear mi registro y no me deja conectar el dominio  me dice que el dominio ya está vinculado a una cuenta y la verdad no tiene conectado el dominio a ninguna cuenta  tengo acceso al hosting y cpanel que se compro pero al revisar los dns estan apuntando al mismo hosting del panel  del proveedor del domini ... como hago para poder crear la cuenta con ese dominio, incluso cree un registro pero no  me deja vincularlo el dominio es integrasoft.co agradezco me ayuden  
                                                                                                            • Delay in delivery of emails

                                                                                                              I'm experiencing random delays for emails sent from Zoho account. Headers show that the message reached mx.zohomail.com almost instantly, followed by a delay of anywhere from 3-15 minutes (and counting). Please confirm whether this is a system-wide
                                                                                                            • Zoho Mail not working. Constant OTP

                                                                                                              Firstly, my emails have been playing up for over a year. They are struggling to send and I have to press Send a few time to make them going. They mostly hover with a loading note saying Sending. I emailed Zoho and they got it working, but now it is doing
                                                                                                            • Zoho Mail Storage Usage Discrepancy – Incorrect Storage Reporting

                                                                                                              Dear Zoho Support Team and Community, I previously raised a concern about inaccurate storage usage reporting in Zoho Mail but did not receive a clear or satisfactory response. To investigate further, I meticulously calculated the storage used by all folders
                                                                                                            • Announcing 12 new connectors in Zoho DataPrep

                                                                                                              We’ve just made data management even easier - Zoho DataPrep now supports 12 new external connectors to help you build more robust, scalable ETL pipelines. Why it matters: ✅ Broader data access ✅ More automation, less manual work ✅ Smarter pipelines, better
                                                                                                            • What Is ZOHO-Workplace? Why was I charged?

                                                                                                              Hi, Today my PayPal account was charged $12.72 for ZOHO-Workplace. The transaction ID is 15S32484H3826544W. What is this charge for? It is the first time I am seeing it.
                                                                                                            • Building a custom site

                                                                                                              do we have an option in Zoho to build custom sites like adding custom functionalities? want to make a site like https://trackscourier.com/jnt-tracking-ph/. Is it doable? Please assist.
                                                                                                            • Missing Payload Details

                                                                                                              Hi All, Does anyone know how to fix missing webhook payload data in the next step of the flow? Payload comes into the webhook -- All details here When i go to use the webhook data in the next step -- the majority of the payload data is missing
                                                                                                            • Numeric options in Decision

                                                                                                              Zoho really needs to add options for numeric comparisons in the Decision action. These are the ones that should be implemented: Greater than Less than Greater than or equal to Less than or equal to Equal to (although this is actually handled already)
                                                                                                            • Supercharge your VoC analyses with data from anywhere: Modules are now sources for VoC

                                                                                                              Dear customers, We hope you're well! Your customers talk about your brand, praise your service, criticize your offerings, or promote your business—literally from anywhere on the internet—and it has become strategically necessary to factor in all possible
                                                                                                            • Nouveautés Zoho Flow - Intégration SAP S/4HANA et SAP HANA

                                                                                                              Bonne nouvelle! Deux applications très attendues dans la galerie d’intégrations de Zoho Flow sont désormais disponibles : ✨ SAP S/4HANA ✨ SAP HANA Que vous gériez des opérations d’entreprise ou des systèmes de données, ces intégrations vous permettent
                                                                                                            • Record/edit view to pop-up simultaneously with button click from report of a different form

                                                                                                              I have two forms: Form A & Form B. Form B contains all of the same fields of Form A, plus a few additional fields. I've created a button in the report view of Form A that creates a new record in Form B and populates all the applicable fields, (I've posted the code I used below), but visually nothing happens on the screen. If I want to finish filling out the remaining fields in Form B, I have to navigate to the report and open the record. How do I get this new record to just pop-up when I click the
                                                                                                            • How to get NSE/BSE Stock Prices in Zoho sheets?

                                                                                                              I've been looking for a function that provides me with the NSE/BSE listed stocks price in Zoho Sheets like GOOGLEFINANCE in Google sheets, but I found none. Please help if there is any way to het stock prices?
                                                                                                            • Next Page