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
merhaba
merhaba sosyal medya paketimiz mevcut ama yorumları göremiyoruz ve o yüzden cevap veremiyoruz destek rica ediyoruz.
Teaminbox not working
We couldn't send or receive any mail within the team inbox. Displaying error 'Unable to process this request.'
Related lists New option in missing
hi I have created quite a few modules and added as related lists to my main module. Some have new, some dont I can not see why?
Cliq and ToDo integrations?
I'm a bit surprised not to find any way to open a Cliq chat for the current thread, or to create a Zoho Mail ToDo from a thread. Are these on the roadmap?
Reply-to names are mangled
Hello, I'm seeing an odd behavior in replies. Steps to reproduce: 1. Click reply to an email from "John Doe <doe.john@example.com> in TeamInbox Expected outcome: TO field pre-filled with "John Doe <doe.john@example.com>" Actual outcome: TO field pre-filled
I CANT UPGRADE MY FREE ACCOUNT
I TRY TO UPGRADE MY FREE ACCOUNT AND I COULD NOT UPGRADE IT CAN SOMEBODY TELL ME WHY? AND I HAVE THE MONEY SO.
Level up your ASO game with tags & categories in store reviews
Introducing tags and categories in Apptics' store reviews Dear Apptics community, If your app is listed on the Play Store or App Store, you already know how important store reviews and ratings are. They’re one of the most direct signals of user sentiment
Including attachments with estimates
How can attachments be included when an estimate is sent/emailed and when downloaded as a .pdf? Generally speaking, attachments should be included as part of an estimate package. Ultimately, this is also true for work orders and invoices.
Adding VENDOR SKU to PURCHASE ORDERS
how can we add the Vendor SKU when issuing a Purchase Order , so the PO shows the Supplier SKU and our own Internal SKU , which is what we want to receive into the system .
Possible to freely prompt/query CRM data using Zia?
Is it possible to prompt Zia to query on any information stored in the CRM, especially on the data stored in custom text fields? My use case is the people in my organisation have entered lots of text in custom text fields to capture information from an
Restrict employees to take only one day holiday from a multi-day festival holiday
Hi everyone, I have a requirement related to Optional/Festival Holidays in Zoho People. For example, in the month of May there are three optional holiday dates: May 11, May 12, and May 13. Employees can choose one of these days as their optional holiday.
Cannot modify colours in invoice email template
I have tried switching browsers... but I cannot change the (pretty horrible) default colours in the preset email when sending an invoice... the blue banner, red outstanding total and the bright green button... I can change other things but not the colours?
Cannot find zpuid for Zoho Projects user
I'm using the Zoho Projects v3 API to create a task. The task is created successfully, but in order to assign the task owner, the "Create a Task" API also requires the zpuid of the task owner. Unfortunately I cannot find any user-related API calls that
Print a document from Zoho Writer via Zoho Creator
If i use the code below i can get writer to create a new document or email it to me but i want to be able to print it directly from the browser and not have to send it via email and then print. Below is the code im using. Attached options form zoho writer
Allow styling for specific Subform fields in Zoho Creator
Sometimes in forms we need to visually highlight a specific field inside a Subform (for example Sanctioned Amount, Approved Value, Critical Fields, etc.) so that users immediately notice it while entering data. Currently there is no direct UI option to
Career site URL - Suggestion to modify URL of non-english job posting
Hi, I would like to suggest making a few modification to career sites that are not in english. Currently, the URL are a mix of different languages and are very long. It makes for very unprofessional looking URLs... Here is an example of one of our URL
3/18 オンライン勉強会のお知らせ Zoho ワークアウト (無料)
ユーザーの皆さま、こんにちは。コミュニティチームの中野です。 3月開催のZoho ワークアウトの開催が決定しましたのでご案内します。 今回はZoomにて、オンライン開催します。 ▶︎参加登録はこちら(無料) https://us02web.zoom.us/meeting/register/BoNTN7zYR8OvOPGShqBY0A ━━━━━━━━━━━━━━━━━━━━━━━━ Zoho ワークアウトとは? Zoho ユーザー同士で交流しながら、サービスに関する疑問や不明点の解消を目指すイベントです。
New 2026 Application Themes
Love the new themes - shame you can't get a little more granular with the colours, ie 3 different colours so one for the dropdown menu background. Also, I did have our logo above the application name but it appears you can't change logo placement position
Placeholder format in Number field does not reflect Max Digits configuration
When the Max Digits (Maximum digits of number) property is set to a smaller value (for example, 2 digits), the placeholder in the input field still displays a 7-digit format (#######). The same behavior can also be observed in Decimal and Currency field
How does SKU work when selling products in parts in Zoho Inventory
Hello everyone, Zoho Inventory does not understand the physical cutting of the piece.. It only tracks quantities of the unit (like feet ). So when you sell part of an item, the system simply reduces quantity for that SKU. Assume that i have a 50 ft long
CRM Cadences - working timesThe Friday afternoon? The next Monday morning? Not at all?
I think I’m writing saying that cadence emails are only sent during the organisations set working hours in CRM. So if a particular email is set to send for example in three days and that lands on a Sunday (when working hours are not operational) when
CRM Cadences - working times
I think I’m right in saying that cadence emails are only sent during the organisations set working hours in CRM. So if a particular email is set to send for example in three days and that lands on a Sunday (when working hours are not operational) when
Push Notification for New Bookings in Zoho Bookings App
when a someone schedules an appointment through the booking page, is there any option to receive a push notification in the mobile app?
Intergrating multi location Square account with Zoho Books
Hi, I have one Square account but has multiple locations. I would like to integrate that account and show aggregated sales in zoho books. How can I do that? thanks.
Add the same FROM email to multiple department
Hi, We have several agents who work with multiple departments and we'd like to be able to select their names on the FROM field (sender), but apparently it's not possible to add a FROM address to multiple departments. Is there any way around this? Thanks.
Zoho Desk View Open Tickets and Open Shared Tickets
Hi, I would like to create a custom view so that an agent can view all the open tickets he has access to, including the shared tickets created by a different department. Currently my team has to swich between two views (Open Tickets and Shared Open Tickets).
Clone Banking Transaction
Why is there no option to CLONE a Transaction in the Banking module?? I often clone Expenses (for similar expense transactions each month) so I would also like to clone Income transactions. But there is no option in Banking to clone an existing Income
Zoho Expense - Bi-Weekly Report Automation
Hi Zoho Expense Team, My feature request is to please include an option to automate creation of reports bi-weekly (every 2 weeks)
Application Architecture in Zoho Creator: Why You Should Think About It from the Start
Many companies begin using Zoho Creator by building simple forms to automate internal processes. This is natural — the platform is extremely accessible and allows applications to be built very quickly. The challenge begins to appear when the application
Arquitetura de Aplicações no Zoho Creator: Por que pensar nisso desde o início
Muitas empresas começam a utilizar o Zoho Creator criando formulários simples para automatizar processos internos. Isso é natural — a plataforma é extremamente acessível e permite construir aplicações rapidamente. O problema começa a aparecer quando a
Dark Mode - Font Colors Don't Work
When editing a document in Dark Mode and selecting font colors, they don't show up on screen. Viewing/editing the same document in Light Mode shows them just fine.
How to Customize & Reorder Spaces in Zoho One 25 (Spaces UI) — Admin Tips Not in the Docs
Hey Zoho Community, After digging around in the new Spaces UI, I found a couple of admin features that aren't well documented yet but are really useful. Sharing here in case others are looking for the same things. 🔁 How to Change the Default Space Users
System Components menu not available for Tablet to select language
I have attached a screenshot of my desktop, mobile, and tablet menu builder options. I am using 2 languages in my application. Language Selection is an option under the System Components part of the menu, but only for my desktop and phone(mobile). My
Approvals in Zoho Creator
Hi, This is Surya, in one of my creator application I have a form called job posting, and I created an approval process for that form. When a user submits that form the record directly adding to that form's report, even it is in the review for approval.
How Zoho Desk contributes to the art of savings
Remember the first time your grandmother gave you cash for a birthday or New Year's gift, Christmas gift, or any special day? You probably tucked that money safely into a piggy bank, waiting for the day you could buy something precious or something you
Estimate PDF Templates - logo too large
Hello, I cloned a standard estimate template, but my logo is showing up much larger than intended. This doesn’t happen with the standard invoice template, where the logo displays correctly. How can I adjust the logo size in the estimate template? Thank
Select CRM Custom Module in Zoho Creator
I have a custom module added in Zoho CRM that I would like to link in Zoho creator. When I add the Zoho CRM field it does not show the new module. Is this possible? Do i need to change something in CRM to make it accesible in Creator?
Invoice emails not sending but reminders are
I am a new user. I have been creating some dummy invoices before I go live and have struck a block. Emails for the invoice are not being recieved by the recipient, however, when I send a reminder for the same invoice the email is sent. NOTE: I have checked
Deleted account recovery
I ended up accidentally deleting our Zoho invoice account while trying to work something out. Emailed support for recovery and restoration of the deleted account, if possible, but they responded by saying they can't find an account associated with that
Devis et factures multipage coupées
Bonjour, je suis sur Zoho invoice et je rencontre un problème sur mes devis et factures lorsqu'ils dépassent 1 page. je me retrouve souvent avec des lignes coupées ou le sous total page 1 et le total page 2. j'aimerai savoir s'il existe une possibilité
Next Page