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
Send emails directly via Cases module
Greetings all, The ability to send emails from the Cases module, which users have been eagerly anticipating, is now available, just like in the other modules. In Zoho CRM, Cases is a module specifically designed for managing support tickets. If your organization
Webinar Alert: Supercharge landing pages with data insights | Zoho LandingPage
Every visitor to your landing page leaves behind valuable data, but are you leveraging it to improve conversions? Join our expert-led Landing Page Analytics webinar to learn how to track, analyze, and optimize landing page performance with Zoho LandingPage’s
Bulk Deletion of Zoho Projects Using Node.js and Zoho Projects API
Zoho Projects currently does not provide a built-in option to delete multiple projects in bulk from the UI. When working with testing environments or large numbers of temporary projects, deleting them one by one becomes time-consuming. To address this,
Show unsubscribed contacts ?
Hello, I would like to display the unsubscribed contacts. Unfortunately, I do not have this subscription type as described in the documentation (https://help.zoho.com/portal/en/kb/marketing-automation-2-0/user-guide/contacts/contact-management/articles/subscription-type-24-1-2024#Subscription_Type_field.)
Track Marketing Automation Campaigns in Zoho CRM
Hello, I've been searching but haven't found the exact answer to this question. I am looking to track Marketing Automation email campaigns and activities inside of Zoho CRM. Use Case: Action: Prospect Submits A Lead Form Outcomes: Prospect created in
Validation rule for Date field
The condition settings for a Date field are are absolutlly usless. Conditions can only be set for a specific date, which is logically ineffective in most cases. When setting a condition for a Date field, users usually need to compare the value relative
Easily map shift data fields during user imports
Greetings all, You can now include all your shift-related data for your users without any hassle during user imports. With this enhancement, the Map Import Fields to Zoho CRM option includes all shift-related fields: Current Shift, Next Shift, and Shift
Unable to send
Hello, I am unble to send any single email during the whole time due to the Zoho IP 136.143.188.16 being bloked by SpamCop.net Please help can somebody help me?
Adding new data to the sheet with most recent data being added to top row.
I am using a form that I built from within sheets. When the form is submitted, is it possible to have the data entered in (for example) row 2 (since row 1 is the heading) instead of being added into the next available row which should be hundreds of
How do you arrange order in which the speakers are listed in a session once they have been selected?
Probably another simple thing I've missed but I can't find how to arrange the order in which the speakers are listed in a session once they have been selected. We usually want the speakers listed alphabetically by last name, but sometimes not. Once the
Product Updates in Zoho Workplace applications | February 2026
Hello Workplace Community, Let’s take a look at the new features and enhancements that went live across all Workplace applications for the month of February. Zoho Mail Organize Personal Notes with Collections You can now create collections under My Personal
Introducing note actions and dynamic visibility in Kiosk Studio
Hello all, We are introducing enhancements to Kiosk Studio that will improve the product scope and meet your custom needs more precisely. What's new? Add notes as Actions: You can add notes to CRM records as kiosk Actions, as well as insert merge fields
Regarding the Recipient Email change
I was not being able to change the Recipient email. Kindly resolve the problem
Request to Customize Module Bar Placement in New Zoho CRM UI
Hello Support and Zoho Community, I've been exploring the new UI of Zoho CRM "For Everyone" and have noticed a potential concern for my users. We are accustomed to having the module names displayed across the top, which made navigation more intuitive
kanban view for client portal
Are kanban views an option for client portals? Access to Kanban views in the client portals would solve some mobile-compliant issues I have with the UI. Kanban functions very nicely on mobile and would be a super asset for my clients and vendors as they
【Zoho CRM】サンドボックスのアップデート:メール送信トレイ機能の追加
ユーザーの皆さま、こんにちは。コミュニティチームの藤澤です。 CRMのサンドボックス(テスト環境)にメールの送信トレイ機能が追加されました。 本番環境でメール配信の前に、サンドボックスで送信される全てのメールを確認・検証できます。ワークフロー、承認プロセス、一括送信など、あらゆる送信パターンに対応しています。 「メールの送信トレイ」機能を使うと、顧客へ送信する前にメールの内容を事前確認できます。項目の欠落や書式の乱れなど、あらゆる問題をサンドボックス内でチェックできるため、本番環境でのトラブルを未然に防ぐことに役立ちます。
Force mandatory entry on one of two fields on Contacts
We are finding our users aren't always entering a phone number or email address of a contact. We would like to make these fields mandatory but realize they won't always have both pieces of information, but should at least have one. Is there a way to make
How can I prevent having recepients from being added as contacts in Zoho Desk?
How can I prevent having recepients from being automatically added as contacts in Zoho Desk? There's no option to disable this.
Agent Concern
would like to ask the difference between an agent and a light agent. can a light agent close a ticket. thank you.
Train Zoho Answer Bot Based on Customer
Hi all, Is it currently possible to mark Help Centre articles to a specific customer, and restrict the answer bot to only use relevant information if it is either marked as "General", or tagged for the specific customer in question? We currently have
Non-depreciating fixed asset
Hi! There are non-depreciable fixed assets (e.g. land). It would be very useful to be able to create a new type of fixed asset (within the fixed assets module) with a ‘No depreciation’ depreciation method. There is always the option of recording land
Errorcode 554
Hello, I am unble to send any single email during the whole time due to the Zoho IP 136.143.188.16 being blocked by SpamCop. Please can somebody help me?
Spamcop
Have been trying to email several of our clients and many of our emails keep getting bounced back with an error that states: ERROR CODE :550 - "JunkMail rejected - sender4-op-o16.zoho.com [136.143.188.16]:17694 is in an RBL: Blocked - see spamcop.net/bl.shtml?136.143.188.16"
Will Zoho Search work with Zoho Learn
Currently, Zoho Search only works with Zoho Wiki which will be phased out. Moving forward, will Zoho Search be enabled for Zoho Learn? Thanks.
How to use filters on all products page? Or even a category page?
Hello, I am trying to create some filters so users can use filters to find products they are looking for. So what i am trying is to create a filter according to price lets say. So if i define it this way i am expecting to see this filter option on category
audio and video comments in tasks in zoho projects
Hi, is it planned to have the ability to post audio and video comments? the whatsapp wechat format of communicating is a reality... tools like zoho project would facilitate a lot teamwork by facilitating the way in which we can give feedback in audio and video rather than only text. thx!
Zoho Projects app update: Voice notes for Tasks and Bugs module
Hello everyone! In the latest version(v3.9.37) of the Zoho Projects Android app update, we have introduced voice notes for the Tasks and Bugs module. The voice notes can be added as an attachment or can be transcribed into text. Recording and attaching
Boas práticas de desenvolvimento em Deluge
O Deluge (Data Enriched Language for the Universal Grid Environment) é a linguagem de script utilizada em diversas aplicações do ecossistema Zoho, como Zoho Creator, Zoho CRM, Zoho Books e Zoho Flow. Ela foi projetada para permitir automações rápidas
Seeking a WhatsApp Business App (not API) Zoho CRM integration
We have a business need to integrated WhatsApp Business App (not API) into Zoho CRM to centrally manage communications between our Sales team and Leads & Contact. Is there a reputable integration available for this scenario of ours? Core features we would
Zoho Sign 2025–2026: What's new and what's next
Hello! Every year at Zoho Sign, we work hard to make document signing and agreement execution easy for all users. This year we sat down with our head of product, Mr. Subramanian Thayumanasamy, to discuss what we delivered in 2025 and our goals for 2026.
Creditos API
Queria saber se alguém poderia me ajudar a resolver um problema na compra e utilização de créditos de mensagens API do WhatsApp. ja tentei todos o tutoriais porem não consegui realizar a compre, pois ao clicar no botão de comprar créditos aparece a mensagem
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.
Emails being blocked / spamcop
Hello, I am unablr to send any single email during the whole time due to the Zoho IP 136.143.188.16 being blocked by SpamCop.net Please help on this.
Zoho IP blocked by SpamCop 136.143.188.16
Hello, I am unble to send any single email during the whole time due to the Zoho IP 136.143.188.16 being blocjed by SpamCop.net Please help on this.
Is there a way to configure dark mode for Campaigns emails that go out to customers?
I've found a lot of information on how to configure dark mode for my (The user) personal Zoho workspace and email, but is there any way to edit dark mode settings on emails that we send out to customers via campaigns? We sent out a test email the other
Can I hide empty Contact fields from view?
Some contacts have a lot of empty fields, others are mostly filled. Is there a way I can hide/show empty fields without changing the actual Layout? I would like to de-clutter my view, and also be able to add information later as I am able. I would be
Auto-publish job openings on my Zoho Recruit Careers Website
I have developed a script using the Zoho Recruit API that successfully inserts new jobOpening records to my Zoho Recruit website, but my goal is to auto-publish to the Careers Website. The jobOpening field data shows two possible candidates to make this
Credit Card Terminal for Zoho Books
Hello, Instead of punching the credit card number manually for customer payment, do you have a third-party hardware credit card reader that works with Braintree? Thank You
How do you print out the invoices comments
I have some invoices where i need to print out the comments that show when reminders and etc were sent how do we print those out in Zoho Books.
Feature Request: Enable Custom PDF Layout Editor for All Modules (Including Package Slips)
Hello Zoho Community and Product Team, I am writing to share a suggestion that would significantly enhance the customization capabilities within Zoho Books. We all appreciate the power of the Custom PDF Layouts (the "New" template engine) that allows
Next Page