Hey everyone!
Welcome back to another interesting post in the Kaizen series!
Sales teams regularly capture interaction notes in CRM after speaking with prospects. However, drafting a follow-up email that reflects the conversation context can be repetitive and time-consuming.
What if CRM could automatically generate a contextual follow-up email draft based on recent interactions with the lead?
In this Kaizen post, we will create a practical tool that generates context-aware follow-up emails directly from a Lead record. You will see how it pulls recent notes, lead's details, and crafts a ready-to-send draft.
The solution uses three Zoho strengths:
- Widgets for intuitive UI
- Functions for secure backend processing
- External AI APIs (like Groq or OpenAI)
The output displays in the widget. Review, tweak if needed, copy, and paste into your email composer.
The business challenge
Sales reps log calls like "Prospect interested in 20 user licenses but concerned about pricing. Explore volume discounts."
Now, crafting a response involves recalling details, matching tone, and ensuring professionalism. Miss a nuance, and trust erodes.
Our AI generator automates this. It scans the lead's details (name, company, status) and the three most recent notes, then prompts an AI model for a draft.
Example output

Subject: Follow-up on CRM Licensing Discussion
Hi John,
Thanks for the insightful chat today about your team's CRM needs. You're considering licenses for around 20 users, and I appreciate pricing being a top priority.
I'll review our volume options and discount eligibility right away. Expect specifics by EOD tomorrow.
Best regards,
[Your Name]
This keeps the rep in control while slashing draft time from 10 minutes to 10 seconds. Scalable for high-volume teams.
High-level architecture
Think of a layered cake!
- UI Layer (Widget): Button launches it; displays, copies the draft, and sends the email.
- Logic Layer (Function): Fetches CRM data server-side, builds prompt, calls AI securely.
- AI Layer: External service generates natural language.
Flow
Rep clicks a button → Widget gets Lead ID → Calls function → Function queries CRM + AI → Draft back to widget
Secure (no client-side keys), reliable (server-side), and reusable across modules.
Developers often wonder "Why not fetch AI responses straight from widget JavaScript?"
Widgets run in a browser iframe, so embedding API keys exposes them to inspection or misuse. CORS policies can also block external requests, and complex logic like prompt building suits server-side better.
So, the best practice is to use widgets for UI and functions for secure server-side work. This hides credentials and reuses logic.
Follow these steps to build this solution.
Step 1: Add the custom Button
- Head to Setup → Modules and Fields → Leads → Buttons → Create New Button.
- Provide the following details:
- Name: Generate AI Email
- Placement: Record Detail Page (top or bottom)
- Action: Open Widget (select your widget once built)
- Save and add to layout.
- Test: Button appears on Leads; clicking loads widget in context.

Pro tip: Position near the "Send Email" button for seamless workflow.
Step 2: Build the CRM Function
- Go to Setup → Developer Hub → Functions → + Create Function.
- Enter the display name, function name, description, choose Standalone as the category.

- Click Create. The Functions IDE opens.
Enter the following function code. Note that this example uses Groq AI API.
string standalone.generate_ai_email(String leadId) {
lead = zoho.crm.getRecordById("Leads",leadId); name = ifnull(lead.get("Full_Name"),""); company = ifnull(lead.get("Company"),""); status = ifnull(lead.get("Lead_Status"),""); // Fetch recent CRM Notes notesResp = zoho.crm.getRelatedRecords("Notes","Leads",leadId); recentNotes = ""; count = 0; for each note in notesResp { noteContent = ifnull(note.get("Note_Content"),""); if(noteContent != "") { recentNotes = recentNotes + "[" + (count + 1) + "] " + noteContent + ". "; } count = count + 1; if(count == 3) { break; } } // Build AI prompt prompt = "You are a sales assistant helping draft follow-up emails. "; prompt = prompt + "Generate a professional follow-up email based on the customer's previous interactions. "; prompt = prompt + "Lead Name: " + name + ". "; prompt = prompt + "Company: " + company + ". "; prompt = prompt + "Lead Status: " + status + ". "; prompt = prompt + "Recent CRM Interaction Notes: " + recentNotes + ". "; prompt = prompt + "Write a professional follow-up email referencing the discussion."; // Sanitize prompt prompt = prompt.replaceAll("\"","\\\""); prompt = prompt.replaceAll("\n"," "); prompt = prompt.replaceAll("\r"," "); // Build AI request message = Map(); message.put("role","user"); message.put("content",prompt); messages = List(); messages.add(message); requestBody = Map(); requestBody.put("model","llama-3.1-8b-instant"); requestBody.put("messages",messages); requestBody.put("temperature",0.4); requestJSON = requestBody.toString(); // Call Groq API response = invokeurl [ type :POST parameters:requestJSON headers:{"Authorization":"Bearer YOUR_API_KEY","Content-Type":"application/json"} ]; // Extract AI email emailContent = ""; if(response.containsKey("choices")) { emailContent = response.get("choices").get(0).get("message").get("content"); } // Return generated email to widget return emailContent; } |
Note for production
- Connections: In the example, the API key is included directly in the function for simplicity. However, production deployments should use Connections instead of hard-coding credentials as they allow developers to store API credentials securely within Zoho CRM and reuse them across multiple integrations.
- Error Handling: Wrap invokeurl in try-catch.
- Limits: Cap notes at 3 to avoid token overflow and tune temperature (0.4 = consistent).
- Logging: Add info prompt before API call for debugging.
- Test: Execute with sample Lead ID. Expect clean email string back.
- Extend: Add phone/email from Lead, or filter notes by date (e.g., last 7 days via criteria).
Step 3: Develop the Widget
The widget provides the user interface for generating and copying the AI email.
When the widget loads, it retrieves the current Lead ID using the CRM widget JS SDK. When the user clicks Generate Email, the widget calls the CRM function and displays the generated email draft.
The widget also provides Send Email and Copy Email buttons that send the email to the lead record's email ID and copies the email content to the clipboard so the rep can past it into the email composer, respectively.
Sample index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> <!-- Add your style here--> </style> </head> <body> <div class="widget-card"> <div class="widget-header"> <path d="M20 4H4C2.9 4 2 4.9 2 6v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z" fill="white"/> </svg> <h2>AI Follow-up Email Generator</h2> </div> <div class="widget-body"> <div class="email-box-wrapper"> <textarea id="emailBox" placeholder="Click 'Generate Email' to create a contextual follow-up email..."></textarea> </div> <div class="action-bar"> <button class="btn btn-primary" id="generateBtn" onclick="generateEmail()"> <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 17l-6.2 4.3 2.4-7.4L2 9.4h7.6z" fill="white"/></svg> Generate Email </button> <button class="btn btn-success" id="sendBtn" onclick="sendEmail()"> <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M2 21l21-9L2 3v7l15 2-15 2v7z" fill="white"/></svg> Send Email </button> <button class="btn btn-secondary" onclick="copyEmail()"> <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M16 1H4C2.9 1 2 1.9 2 3v14h2V3h12V1zm3 4H8C6.9 5 6 5.9 6 7v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" fill="#3D4354"/></svg> Copy </button> </div> <div class="status-bar" id="statusBar"></div> </div> </div> <script src="index.js"></script> </body> </html> |
Sample index.js
let leadId; let leadEmail; let generatedEmail = "";
// Widget initialization ZOHO.embeddedApp.on("PageLoad", function(data){
if(data && data.EntityId){
leadId = data.EntityId[0];
// Fetch Lead email ZOHO.CRM.API.getRecord({ Entity: "Leads", RecordID: leadId }) .then(function(response){
if(response && response.data && response.data.length > 0){ leadEmail = response.data[0].Email; }
});
}
});
ZOHO.embeddedApp.init();
// --- Helper functions used by email generation/sending --- // function formatEmailText(raw) { /* formatting logic */ } // function textToHtml(text) { /* convert plain text to HTML */ } // function setStatus(message, type) { /* UI status logic */ }
// Generate AI email using a CRM function function generateEmail(){
var req_data = { arguments: JSON.stringify({ leadId: leadId }) };
ZOHO.CRM.FUNCTIONS.execute('generate_ai_email', req_data)
.then(function(response){
if(response && response.details){
generatedEmail = formatEmailText(response.details.output); document.getElementById('emailBox').value = generatedEmail;
}
}) .catch(function(error){
console.log('Function error:', error);
});
}
// Send email using ZRC async function sendEmail() {
const emailContent = document.getElementById('emailBox').value.trim();
if (!emailContent) return;
try {
// Get allowed "From" addresses const fromRes = await zrc.get('/crm/v8/settings/emails/actions/from_addresses'); const fromAddress = fromRes.data.from_addresses[0];
const htmlContent = textToHtml(emailContent);
// Send mail const response = await zrc.post(`/crm/v8/Leads/${leadId}/actions/send_mail`, {
data: [ { from: { user_name: fromAddress.display_name || fromAddress.user_name, email: fromAddress.email }, to: [ { email: leadEmail } ], subject: 'Follow-up', content: htmlContent, mail_format: 'html' } ]
});
console.log('Mail sent:', response);
} catch (error) {
console.error('Send mail error:', error);
}
}
// Copy generated email // function copyEmail(){ /* copy logic */ } |
The ZIP containing the complete index.js and index.html files used in this example is attached at the end of this post.
User experience walkthrough
- The salesperson clicks Generate AI Email on the record detail page and the widget opens.
- The salesperson clicks the Generate AI email button. The widget retrieves CRM context and generates a contextual follow-up email draft.
- The email appears inside the widget, allowing the salesperson to quickly review the generated message, and use the Send Email button to send it to the lead's email ID.
This workflow ensures that AI assists with drafting the message while still allowing the salesperson to review and control the final communication.
Here is a GIF explaining the use case in action.
Key takeaways
This example demonstrates how Zoho CRM developers can integrate generative AI into CRM workflows using platform-native tools.
Combine CRM Widgets for user interaction and Functions for secure server-side processing to safely integrate external AI services without exposing credentials or compromising security.
The same architecture can be extended to build more advanced AI features, such as:
- Automated meeting summaries
- Deal health insights
- Proposal drafting assistants
- Intelligent follow-up recommendations
We hope you liked this post. Let us know what you think in the comments or reach out to us at
support@zohocrm.com.
Cheers!
===================================================================================
Recent Topics
Invalid scope choice: Workdrive integration in CRM
Bug: There is an invalid option in the permission choices for Workdrive integration in CRM. If the entry "WorkDrive.teamfolder.CREATE" is selected, it will return a message indicating invalid OAuth scope scope does not exist.
What's New - February 2026 | Zoho Backstage
February 2026 brings a major new addition and a collection of enhancements across Zoho Backstage. We thought about writing a long introduction, but the updates in this release make a strong case on their own. So we’ll skip the buildup and dive straight
Attaching files to emails within CRM Deals.
Hello, We have recently started using the extension "Workdrive for CRM" (Related List) to view/store our documents for each Deal, instead of using Attachments. Overall it feels like a better way to go but the user experience is not so great when it comes
Anyone worked out how to export or screengrab a full heatmap?
I'd love to be able to include a copy of a heatmap in a report but can't work out how to grab the whole thing as there doesn't appear to be an export function? Thanks in advance.
Establishing Relationships among contacts/leads with Reciprocal
Is there any way to create a relationship between contacts and leads and be able to go into just one of the files and have it reciprocate the entry in the other file? For example, if I have two people say John and Jane Smith who are husband and wife.
Placeholder for Agent Signature in Email Templates
Dear Zoho Team, I hope this message finds you well. We currently face a limitation when designing email templates in Zoho Desk. While we can create email templates and include a footer at the end, the agent signature is always appended by default at the
Custom View and Custom Fields on Zoho Books
Hi, I have some custom fields on Estimates and Invoices. I also use Custom Views so I can have a lot of information at a glance. I want to include my custom fields as columns in my custom views of estimates / invoice, but it looks like is not possible.
%PaymentLink%
Does not work. Software creates a BAD link. ....and yes payment options are turned on. Link on the invoice pdf once opened will work but this template is a joke.
Syncing calendar with Google Calendar doesn't work when events are sent to auto repeat
Hi... The ZOHO CRM -- GOOGLE CALENDAR sync is broken. If I create a single event on either side, sync works, but if I create an event with auto repeat on either side it doesn't work. Furthermore, events created before the sync don't show up in the calendar.
Allow Global Admin to access/edit all forms without changing owners
Hi there, Please consider adding a feature where the Global Admin of the account an automatically access/edit any form in the Company Account. I'm the Global Admin on our Zoho One plan, and we have multiple users that use/create forms. But for me to access
Can Zoho Marketing Automation send OTP codes via WhatsApp during user registration?
The flow I would like to implement is: A user signs up in the mobile app and enters their phone number. The system generates a one-time verification code (OTP). The OTP is sent to the user via WhatsApp message. The user enters the code in the app to confirm
Where to show Customization Field ?
Dear Sir, I have made some New Field in Item Field Customisation. Now I don't require that field in Estimate, Sales Orders etc. I just wants that field in Sales Invoice to Show/Hide... Is that possible ?
What's New in Zoho Analytics - February 2026
Hello Users! We're back with another round of updates for Zoho Analytics. This month's release focuses on giving you greater flexibility in how you visualize, manage, and act on your data - with new features like custom visualizations, remote MCP server,
Zoho Books (and other Finance Suite Apps) - Clickable Item Name on Invoices and Reports
Hi Zoho Books team, It would be really helpful if the Item Name on Reports were clicable to take me to the item. The same on Invoices, often I am looking at an invoice and I want to look at the deails of a product. A link here would be helpful to jump
ZOHO Reports are taking longer time to get refresh
Hi Team, Since last few days, I'm facing issues in getting updated reports. For eg: right after making an expense entry or even posting a journal, it is taking longer then expected for the updated reports. Refer below: "You are viewing the report that
Display actual mileage on an invoice
My users are creating expenses in Zoho expense. For example, they expense 10 miles and get paid 7 dollars (10 miles * IRS rate of .70). If I look at the expenses in Zoho Books, it does show them at 10 miles at .70 cent When I add these expense to an invoice
Can't change form's original name in URL
Hi all, I have been duplicating + editing forms for jobs regarding the same department to maintain formatting + styling. The issue I've not run into is because I've duplicated it from an existing form, the URL doesn't seem to want to update with the new
Can you create relationships BETWEEN contacts within the same module
I am setting up my CRM, and I want to have a way to connect contacts within the same module. Is there a way to do this? If not - how do I decide how to split up contacts to make connections? What are best practices for this? We have clients who need
Function and workflow to create customer payment and send receipt
I am attempting to set up a workflow/custom function for the automatic creation of a customer payment and sending the email receipt, but am receiving the error "Improper Statement Error might be due to missing ';' at end of the line or incomplete expression" I've been over everything several times and cannot see where the error is (code is copied into the attached document). I haven't used custom functions before with Deluge, so it's very likely something very simple, or I've completely mucked
Disable Sign Up option in Zoho Creator Portal and show only Sign In page
Is it possible to disable the Sign Up option in a Zoho Creator portal? The requirement is to show only the Sign In page and completely remove or hide the Sign Up page, so users cannot create accounts directly from the portal login page. Is there any setting
Restrict Payment Methods
Allow us to restrict certain payment methods specific for each customer.
How to install Widget in inventory module
Hi, I am trying to install a app into Sales Order Module related list, however there is no button allow me to do that. May I ask how to install widget to inventory module related list?
Can I view the KB in the same way as a customer logged in as my Agent?
Sorry if this seems a mad question. I have some Articles that I want to be seen by my Agents and the status of these is set to Agents only. We also have some that are set to Public. When I sign in with my private email address (as a customer) I can
What’s New in Zoho Inventory — Latest Features, Integrations & Updates | December 2025
Zoho Inventory has evolved significantly over the past months, bringing you smarter, faster, and more connected tools to streamline your operations. Whether you’re managing multichannel sales, complex fulfillment workflows, or fast-moving stock, our newest
Which user's capacity is used for Shared Mailbox storage?
We use shared mailboxes at our company, and their size is increasing daily. Which user(s)'s total mailbox limit is being used up by this space?
Evernote (ENEX) import limitations
I have been with Evernote since 2010, but the latest price increase is ridiculous. I am currently testing Zoho Notebook as a replacement. I am impressed so far - if it were not for critical need to import legacy Evernote notes, I would 100% migrate to
Can I create a CODE 128 custom field for my items in Zoho Inventory and then use it for generating Sales Orders?
Can anyone helps me, I don't want to use the SKU code for scanning my products. Because all my products have a CODE-128 label attached.
Prevent duplicate with custom fields?
I was wondering something about custom field/custom modules in Zoho Desk. For some reason you can make a custom field mandatory but not unique? For example, if I create a custom module to manage equipment and renewal and make a field serial number no
Zoho Books' 2025 Wrapped
Before we turn the page to a new year, it’s time to revisit the updates that made financial management simpler and more intuitive. This annual roundup brings together the most impactful features and enhancements we delivered in 2025, offering a clear
Multiple Vendor SKUs
One of the big concerns we have with ZOHO Inventory is lack of Vendor Skus like many other inventory software packages offer. Being able to have multiple vendor skus for the same product would be HUGE! It would populate the appropriate vendor Sku for
Create Invoice automated with Package
Does anyone knows how to create an invoice from a SO when we have created the package? We do these manually. and validate that the product packed is the product invoiced (if the order is partially packed) Regards, JS
Unable to integrate Zoho Projects and Zoho Workdrive
I'm a Zoho One subscriber. When I go to Zoho Projects > Settings > Marketplace > Zoho Apps I do not see an option for Zoho Workdrive but I do see one for Zoho Docs that does nothing. How do I get the option to integrate Zoho WorkDrive and Zoho Proje
Disable payment thank-you emails
Hello, can someone please tell me how to disable sending of the "Payment Thank-You" emails?
How to backdate record payment for the invoice
I would like to record a payment which happened 2 days ago, but I am not able to select any date later than today. I backdated the invoice, too, but it doesn't change anything
Help with deluge script
Hi Community, this is my first Deluge script. I've pieced it together from reading various articles I want to use it in a workflow to 1 Convert a lead to a contact 2. Create a record in a custom module Below is what I have got so far but it does not fire
Marketer's Space: Why email authentication matters in Zoho Campaigns
Welcome back to another post in Marketer's Space! If you've recently started using Zoho Campaigns, you've probably come across terms like SPF and DKIM. You may have also noticed emails that show "via zcsend.net" in Gmail when testing or sending campaigns.
Feature Request: "Send Invitation" Toggle for Events
I am writing to request a critical "Quality of Life" update for the Activities module. Currently, adding people to the Participants field in an Event triggers an automatic email invitation/acceptance tracking with no way to opt-out. For general events
Edit email address that appears on invoice
Hi How do I change the email address that appears on invoices, it is showing the email address that i used to sign up to zoho with but I want to change it to another email address that we use for accounts. also is there a way to edit the position of a
Introducing Zoho Sprints 3.0
Zoho Sprints is consistently evolving in steady increments. The introduction of the latest version, with its enterprise level solutions, brings to you advanced capabilities that propel your agile efforts in the right direction. Here's a quick glimpse
Google Fonts Integration in Pagesense Popup Editor
Hello Zoho Pagesense Team, We hope you're doing well. We’d like to submit a feature request to enhance Zoho Pagesense’s popup editor with Google Fonts support. Current Limitation: Currently, Pagesense offers a limited set of default fonts. Google Fonts
Next Page