Kaizen 233 Generating AI-Powered Follow-up Emails Using CRM Functions and Widgets

Kaizen 233 Generating AI-Powered Follow-up Emails Using CRM Functions and Widgets


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:
  1. Widgets for intuitive UI
  2. Functions for secure backend processing
  3. 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
InfoSubject: 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!
  1. UI Layer (Widget): Button launches it; displays, copies the draft, and sends the email.
  2. Logic Layer (Function): Fetches CRM data server-side, builds prompt, calls AI securely.
  3. 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

  1. Head to SetupModules and FieldsLeadsButtonsCreate New Button.
  2. Provide the following details:
    1. Name: Generate AI Email
    2. Placement: Record Detail Page (top or bottom)
    3. Action: Open Widget (select your widget once built)
  3. Save and add to layout.
  4. Test: Button appears on Leads; clicking loads widget in context.

Idea
Pro tip: Position near the "Send Email" button for seamless workflow.

Step 2: Build the CRM Function

  1. Go to SetupDeveloper HubFunctions+ Create Function.
  2. Enter the display name, function name, description, choose Standalone as the category.

  3. Click Create. The Functions IDE opens.
  4. 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;
    }

Notes
Note for production
  1. 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.
  2. Error Handling: Wrap invokeurl in try-catch.
  3. Limits: Cap notes at 3 to avoid token overflow and tune temperature (0.4 = consistent).
  4. Logging: Add info prompt before API call for debugging.
  5. Test: Execute with sample Lead ID. Expect clean email string back.
  6. 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">
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <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 */ }
Info
The  ZIP containing the complete index.js and index.html files used in this example is attached at the end of this post.

Refer to Creating a Widget in Zoho CRM and the JS SDK for more details on CLI installation, creating, packaging, and hosting a widget.

User experience walkthrough

  1. The salesperson clicks Generate AI Email on the record detail page and the widget opens.
  2. The salesperson clicks the Generate AI email button. The widget retrieves CRM context and generates a contextual follow-up email draft.
  3. 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:
  1. Automated meeting summaries
  2. Deal health insights
  3. Proposal drafting assistants
  4. 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!



===================================================================================



    • Sticky Posts

    • 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.
    • Kaizen #226: Using ZRC in Client Script

      Hello everyone! Welcome to another week of Kaizen. In today's post, lets see what is ZRC (Zoho Request Client) and how we can use ZRC methods in Client Script to get inputs from a Salesperson and update the Lead status with a single button click. In this
    • Kaizen #222 - Client Script Support for Notes Related List

      Hello everyone! Welcome to another week of Kaizen. The final Kaizen post of the year 2025 is here! With the new Client Script support for the Notes Related List, you can validate, enrich, and manage notes across modules. In this post, we’ll explore how
    • Kaizen #217 - Actions APIs : Tasks

      Welcome to another week of Kaizen! In last week's post we discussed Email Notifications APIs which act as the link between your Workflow automations and you. We have discussed how Zylker Cloud Services uses Email Notifications API in their custom dashboard.
    • Kaizen #216 - Actions APIs : Email Notifications

      Welcome to another week of Kaizen! For the last three weeks, we have been discussing Zylker's workflows. We successfully updated a dormant workflow, built a new one from the ground up and more. But our work is not finished—these automated processes are
      • Recent Topics

      • Major journey crash and not loading. Zoho Marketing Automation

        Hi all. Last night (19MAR, 2026) Marketing Automation for a specific journey completely crashed, and since the crash the specific journey has failed to load at all (blank journey canvas, no journey appears, no menu accessible) but other separate journey's
      • Candidate Assessments, no workflows.

        I have an issue where I would like to trigger a workflow based on a candidate assessment being completed. Sometimes a returning candidate will complete a second assessment, on completion the status of the candidate will be updated to "Unqualified" if
      • Mail Merge in Zoho Desk

        Hello Team, Do we have an option of mail merge within Zoho Desk like we have in Zoho CRM? We have a requirement to generate some pdf file in the form of mail merge doc from the ticket.
      • Workdrive backup and default storage selection

        Hi community, I have been informed by Zoho that workdrive will be the default storage mechanism for crm and projects. These 2 Apps seem to have different design on how they interact with workdrive for storage. 1. Crm: seems to have files saves at the
      • Zoho vault filling in a form it's not supposed to fill in

        Hey there, I have a problem with ZOHO Vault autofill. In a software package, we have these options: For some reason zoho vault always replaces what's in the top option and fills a 2fa password in there, and then saves that value.. Meaning whatever was
      • Zoho Booking Integration with Desk

        Just wanting to share something in case it helps someone else who may run into a similar use case as we did. Issue: Currently, the Zoho Booking integration with desk will drop a comment into the ticket when a customer books a time, however it won't change
      • Let us view and export the full price books data from CRM

        I quote out of CRM, some of my clients have specialised pricing for specific products - therefore we use Price Books to manage these special prices. I can only see the breakdown of the products listed in the price book and the specialised pricing for
      • 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.
      • Organization wide Account and Contacts Visibility/Sharing Capabilities?

        Has anyone figured out a way to make visibility or sharing of Accounts and Contacts to be available across the entire organization without having to have every individual user edit their Sharing permissions? For our sales folks they need to be able to
      • Notification of Interaction Assignment

        If a user is assigned an interaction, they should be notified via email. These are almost useless because if I assign an interaction for someone to respond to, they dont know that I assigned it to them without me telling them or them logging in and discovering
      • Countries List Global Set- Complete with Phone Country Code and Continent.

        Dear Zoho Team I saw your recent addition to the Global Sets regarding the Countries list and states. While working on it, why didn't you also add things like Continent and Phone Country Code? Also, some ISO codes from some Countries/regions are mis
      • Custom Display Field for Lookup Dropdowns in Zoho CRM

        Could Zoho CRM support changing the display field in lookup dropdowns, like Zoho Creator does? This would make it much easier to select the right record by showing a more useful field instead of only the default one. It would improve speed, clarity, and
      • Message as bot

        I would like to be able to send a Cliq message truly as a bot. the current implementation of this function, while it sends the message as a bot it sends that message inside a chat from the user how authenticated the flow cliq connection instead of directly
      • Books <-> CRM synchronisation with custom Fields

        Hello, We are synchronising Books Customers with CRM Accounts. In CRM Accounts I set up last year a "segments" multiselect field shown below In Books, I set up a custom multi-select field with the same value as in the CRM And set up the synchronisation inside Books. Want to synchronise the Books Segments with the CRM Segments, but the later doesn't exist, and another non-existing is there ?! First, I don't understand where the field Segmentation is coming from. Second, I set CRM Segmentation to sync
      • Trouble with using Apostrophe in Name of Customers and Vendors

        We have had an ongoing issue with how the system recognizes an apostrophe in the name of customers and vendors. The search will not return any results for a name that includes the mark; ie one of our vendors names is "L'Heritage" and when entering the
      • Recording overpayment?

        So a customer just overpaid me and how do I record this? I can't enter an amount that is higher than the invoice amount. Eg. Invoice is $195 and he sent $200. He's a reccuring customer so is there a way to record so that he has a $5 advance for future invoice?
      • Introducing the New Zoho Assist Quick Support Plugin

        We are thrilled to announce the new Zoho Assist Quick Support Plugin, the upgraded and enhanced version of the Zoho Assist Customer Plugin. This new plugin allows organizations and IT administrators to deploy it directly onto their customers’ devices,
      • Automate your signing workflows with Zoho Sign + n8n

        Hello! We're excited to announce that Zoho Sign is now available as a community node on n8n, a popular open-source workflow automation platform used by tens of thousands of teams worldwide. n8n lets you connect apps, APIs, and services through a visual
      • Ask the Experts 27: Onboarding and managing support reps

        Hello everyone, We are back with our Ask the Experts (ATE) series for 2026. This year, we bring experts to help you address customer support challenges using Zoho Desk. For our first ATE, we are getting into the human side of customer support. "Every
      • Retainer invoice in Zoho Finance modlue

        Hello, Is there a way of creating retainer invoices in the Zoho Finance module? If not can I request this is considered for future updates please.
      • Spotlight #27: Embed visual collaboration Spaces in your presentations using the Vani add-on

        Hello everyone! This month’s spotlight feature is the Vani add-on for Zoho Show. Every time you pause your presentation to open another tab or pull up supporting material, you lose a bit of momentum. At Zoho Show, we design features that keep everything
      • CRM

        Is anyone else experiencing this issue? Our company is not moving out of using Gmail's web app. It just has more features and is a better email program than Zoho Mail. Gmail has an extension (Zoho CRM for Gmail) that we're using but we've found some serious
      • Good news! Calendar in Zoho CRM gets a face lift

        Dear Customers, We are delighted to unveil the revamped calendar UI in Zoho CRM. With a complete visual overhaul aligned with CRM for Everyone, the calendar now offers a more intuitive and flexible scheduling experience. What’s new? Distinguish activities
      • Global Search / Command Palette in Live App

        Zoho Creator applications can contain many forms, reports, pages, and dashboards. While navigation inside the app is smooth, users still need to move through multiple menus or screens to find specific records or open particular modules. Currently, in
      • 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
      • Smarter appointment allocation with round-robin distribution

        Greetings from the Zoho Bookings team! We’re excited to introduce the Appointment Distribution feature, a new way to decide how appointments are assigned among users. By default, appointments are distributed evenly across all event types, but this enhancement
      • A2P 10DLC Opt-in Rejection Issue with Zoho Creator Public Form

        Hi everyone, I’m working on an A2P 10DLC SMS campaign and running into repeated rejections due to opt-in issues. I’m using Zoho Creator for the registration flow. The form is public (no login required). Users enter their phone number and there is an unchecked
      • Make Quick Edits to Images Before Attaching

        Hello everyone, We have enhanced how attachments are handled in tickets to help agents preview and share files more efficiently in Zoho Desk. Agents can preview image attachments before adding them to tickets and edit them using attachment annotator.
      • 3/18 オンライン勉強会のお知らせ Zoho ワークアウト (無料)

        ユーザーの皆さま、こんにちは。コミュニティチームの中野です。 3月開催のZoho ワークアウトの開催が決定しましたのでご案内します。 今回はZoomにて、オンライン開催します。 ▶︎参加登録はこちら(無料) https://us02web.zoom.us/meeting/register/BoNTN7zYR8OvOPGShqBY0A ━━━━━━━━━━━━━━━━━━━━━━━━ Zoho ワークアウトとは? Zoho ユーザー同士で交流しながら、サービスに関する疑問や不明点の解消を目指すイベントです。
      • Extend color coding to custom picklist fields

        Objectively, Projects has the best UI of any Zoho app — clean, intuitive, and never feels bloated. Big props to whoever owns the design. Feature request: color coding for custom picklist field values in field customization. You've already done it in two
      • New in Office Integrator: In-sheet text translation

        Hi users, We're pleased to introduce translation capability in the spreadsheet editor in Zoho Office Integrator. This allows you to translate the text in your spreadsheet's cells into 70+ languages from within your web app. Office Integrator's spreadsheet
      • Streamline email communication with Out of Office configuration

        Managing user communication effectively is the key to ensuring timely responses and consistent messaging. However, when users are unavailable, the absence of an Out of Office response can lead to delays and missed expectations. Managing these settings
      • Changing settings for auto logoff

        I've noticed that when I haven't used Cliq for a while, I have to re-enter my password. That is really clumsy, especially if you have a complicated password. Because it won't be filled in automatically. Is there a way to change that behaviour? We are
      • A few Issues when using "Pay Bill via Check"

        We have quite a bit of issues with how paying for Bills via Check works. Would love some feedback from the Zoho team in case we are doing something incorrectly. 1. When we go from a vendor and select "Pay Bill via Check" option, we see ALL the outstanding
      • Prevent tracking users from specific countries

        Currently, I’m receiving many bot visits from the United States and Malaysia. I would like these visits not to be recorded in SalesIQ. I already enabled the option to exclude traffic from cloud service providers, but I’m still receiving bot visits. Ideally,
      • My client requires me to have custom pdf file names to except payment for invoices, how can I customize this before emailing.

        Hello! I love the program so far but there are a few things that are standing in the way. I hope you guys can code them in so I can keep the program for years to come. My client requires I customize the pdf file names I send in for billing. Can you please
      • Edit Project Number?

        Hi all: We just signed up for a trial of zoho one, which includes ZoHo Projects. We've noticed there was a 'dummy project' preloaded in projects to help familiarize yourself with the software. We've created a couple of our own projects now but noticed since the dummy project was preloaded, our projects start with number 2 then 3, sequentially. Since it seems we will be keeping zoho past the trial, If we delete the dummy project, how do we get our own projects renumbered, beginning with 1? We'd like
      • Download pricebook products & details - not just pricebook creation date & name

        We're looking to download a copy of a pricebook and its associated products & book prices (as we have several offices in different countries selling the same products), however, when using the export feature under Data administration it only gives me
      • 554 5.1.1 – Mail sending blocked for the domain(s): [gmail.com]

        Here's your corrected text: Hello, I hope you are doing well. I was unable to send a message and received the following error: "554 5.1.1 – Mail sending blocked for the domain(s): [gmail.com]" I tried to send and deliver an email but got this error. I
      • Outgoing Mail Blocked – Suspicious Login Activity (Need Clarification and Solution)

        Hello, I’m currently facing an issue where my Zoho Mail account has been blocked due to “suspicious login activity,” and outgoing emails are restricted. Here are the details shown: Block type: Outgoing mail blocked Reason: Suspicious login activity A
      • Next Page