Automation · Google Sheets

How to save leads to Google Sheets and get an email for each one

To save leads to Google Sheets automatically, deploy the Apps Script below as a web app. Your form, chatbot or AI agent posts each lead to it; the script adds a row, emails you, and merges repeats from the same email (or the same phone, when no email is given) within 24 hours. It is free and runs in your own Google account. Every Botlery AI agent does this as standard (chatbot $200 one-time, voice or phone agent $300 one-time).

Updated November 2026 · 9 min read ·

Diagram: how a lead reaches the sheet and your inbox A website form, a chatbot or AI agent, and a Google Form all send the lead to one Apps Script. The script cleans the fields and checks whether the same email (or, with no email, the same phone) arrived in the last 24 hours. If not, it adds a new row to the Leads tab and emails you. If it did, it adds the new message to the existing row and sends no second email. Websiteform Chatbot orAI agent GoogleForm Apps Script web appcleans the fields, waits its turn Same email (or phone)in the last 24 hours? NoYes Add a new rowto the Leads tab Email youthe lead Add the messageto their existing rowNo new row,no second email
Diagram: the path of one lead through the script below. Every source posts to the same web app.

Most small businesses get leads in three or four places: the website form, a chatbot, a booking page, an email or two. The problem is rarely the number of leads. It is that they land in different inboxes, some get answered twice and some not at all. One sheet that every source writes to, plus an email for each new person, fixes most of that for free.

What you will have at the end

Step 1: create the sheet and paste the script

Create a Google Sheet (or open the one you already use for leads), then choose Extensions › Apps Script. Delete the sample code, paste the script below, and change ownerEmail to the address that should get the alerts. You do not need to create the Leads tab or its headers; the script makes them the first time it runs.

Apps Script · Code.gs

/**
 * Save leads to a Google Sheet and email the owner, with duplicates merged.
 * From botlery.com/blog/ai-agents-save-leads-google-sheets.html
 *
 * Setup: open the sheet > Extensions > Apps Script, paste this file, edit CONFIG,
 * run testSaveLead once (to authorise), then Deploy > New deployment > Web app
 * (Execute as: Me, Who has access: Anyone) and copy the /exec URL.
 */
const CONFIG = {
  spreadsheetId: '',              // leave blank when the script was opened from the sheet itself
  sheetName: 'Leads',
  ownerEmail: 'you@example.com',  // who gets the "new lead" email
  dedupeHours: 24,                // same email (or phone, if no email) inside this window = the same lead
};

const HEADERS = ['Received', 'Name', 'Email', 'Phone', 'Service', 'Message', 'Source', 'Status', 'Key'];
const FIELDS = ['name', 'email', 'phone', 'service', 'message', 'source'];

// Web app entry point: your form, chatbot or webhook POSTs here.
function doPost(e) {
  const data = readBody(e);
  // Hidden honeypot field filled in: almost certainly a bot. Its name (hp_field) must not match any
  // real field a form or webhook sends — a real "website" field here would silently drop leads.
  if (data.hp_field) return reply({ ok: true });
  const result = saveLead(data);
  return reply(result);
}

// Opening the /exec URL in a browser: a quick "is it deployed?" check.
function doGet() {
  return reply({ ok: true, message: 'Send leads to this URL with POST.' });
}

// Optional: a Google Form linked to this spreadsheet. Add an installable
// "On form submit" trigger that runs this function.
function onLeadFormSubmit(e) {
  const answers = e.namedValues;   // { 'Name': ['Jane'], 'Email': ['jane@example.com'], ... }
  const pick = (question) => (answers[question] && answers[question][0]) || '';
  saveLead({
    name: pick('Name'), email: pick('Email'), phone: pick('Phone'),
    service: pick('Service'), message: pick('Message'), source: 'Google Form',
  });
}

function saveLead(data) {
  const lead = {};
  FIELDS.forEach((f) => { lead[f] = clean(data[f]); });
  lead.email = lead.email.toLowerCase();
  const digits = lead.phone.replace(/\D/g, '');
  if (!lead.email && digits.length < 6) return { ok: false, error: 'email or phone required' };

  const lock = LockService.getScriptLock();
  if (!lock.tryLock(20000)) return { ok: false, error: 'busy, please retry' };
  try {
    const sheet = getSheet();
    const key = lead.email ? 'email:' + lead.email : 'tel:' + digits;
    const now = new Date();
    const existing = findRecent(sheet, key, now);

    if (existing) {
      // Same person inside the window: add the new message to their row, no second email.
      const cell = sheet.getRange(existing, HEADERS.indexOf('Message') + 1);
      const stamp = Utilities.formatDate(now, Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm');
      const note = '[' + stamp + ' ' + (lead.source || 'repeat') + '] ' + (lead.message || '(no message)');
      cell.setValue(safe(String(cell.getValue()) + '\n' + note));
      return { ok: true, duplicate: true, row: existing };
    }

    sheet.appendRow([now, lead.name, lead.email, lead.phone, lead.service,
      lead.message, lead.source, 'New', key].map(safe));
    SpreadsheetApp.flush();          // the row is saved before we try to email
    const row = sheet.getLastRow();
    try {
      notifyOwner(lead, sheet);
    } catch (err) {                  // e.g. the daily email quota is used up: the lead is still saved
      console.error('Lead saved in row ' + row + ' but the alert failed: ' + err.message);
      return { ok: true, row: row, emailed: false };
    }
    return { ok: true, row: row };
  } finally {
    lock.releaseLock();
  }
}

function getSheet() {
  const ss = CONFIG.spreadsheetId
    ? SpreadsheetApp.openById(CONFIG.spreadsheetId)
    : SpreadsheetApp.getActiveSpreadsheet();
  let sheet = ss.getSheetByName(CONFIG.sheetName);
  if (!sheet) {
    sheet = ss.insertSheet(CONFIG.sheetName);
    sheet.appendRow(HEADERS);
    sheet.setFrozenRows(1);
  }
  return sheet;
}

// Row number of the same key inside the dedupe window (latest 500 rows only), or 0.
function findRecent(sheet, key, now) {
  const last = sheet.getLastRow();
  if (last < 2) return 0;
  const first = Math.max(2, last - 499);
  const count = last - first + 1;
  const received = sheet.getRange(first, 1, count, 1).getValues();
  const keys = sheet.getRange(first, HEADERS.length, count, 1).getValues();
  const windowMs = CONFIG.dedupeHours * 60 * 60 * 1000;
  for (let i = count - 1; i >= 0; i--) {
    const when = received[i][0];
    if (String(keys[i][0]) === key && when instanceof Date && now - when < windowMs) return first + i;
  }
  return 0;
}

function notifyOwner(lead, sheet) {
  const who = lead.name || lead.email || lead.phone;
  const mail = {
    to: CONFIG.ownerEmail,
    subject: 'New lead: ' + who + (lead.service ? ' (' + lead.service + ')' : ''),
    body: [
      'Name: ' + (lead.name || '-'),
      'Email: ' + (lead.email || '-'),
      'Phone: ' + (lead.phone || '-'),
      'Service: ' + (lead.service || '-'),
      'Source: ' + (lead.source || '-'),
      '',
      lead.message || '(no message)',
      '',
      'Open the sheet: ' + sheet.getParent().getUrl() + '#gid=' + sheet.getSheetId(),
    ].join('\n'),
  };
  if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(lead.email)) mail.replyTo = lead.email;
  MailApp.sendEmail(mail);
}

function readBody(e) {
  const body = e && e.postData && e.postData.contents;
  if (body && body.trim().charAt(0) === '{') {
    try { return JSON.parse(body); } catch (err) { /* not JSON: use the form fields */ }
  }
  return (e && e.parameter) || {};
}

function clean(value) {
  return String(value == null ? '' : value).replace(/\s+/g, ' ').trim().slice(0, 2000);
}

// Stop Sheets treating text as a formula (=, +, -, @) or a number (drops a phone's leading 0).
function safe(value) {
  return typeof value === 'string' && /^([=+\-@]|\d+$)/.test(value) ? "'" + value : value;
}

function reply(obj) {
  return ContentService.createTextOutput(JSON.stringify(obj))
    .setMimeType(ContentService.MimeType.JSON);
}

// Run once from the editor: authorises the script and writes a test row.
function testSaveLead() {
  console.log(saveLead({ name: 'Test Lead', email: 'test@example.com', phone: '+1 555 0100',
    service: 'Test', message: 'Testing the lead sheet', source: 'editor test' }));
}

What the important lines do

Step 2: authorise it and send a test lead

In the editor, pick testSaveLead from the function list and press Run. Google asks you to authorise the script: it needs to edit this spreadsheet and send email as you. Because the script is yours and unpublished, Google may show a “Google hasn’t verified this app” screen; choose Advanced, then go to the project. A Leads tab appears with one test row, and the test email arrives in the owner’s inbox. Delete the test row when you are done.

While you are in the editor, open Project Settings and check the time zone. The “Received” column and the time stamps on merged messages use it.

Step 3: deploy it as a web app

  1. Choose Deploy › New deployment, click the gear icon and select Web app.
  2. Set Execute as to Me, so rows are written with your access, and Who has access to Anyone, so a website visitor without a Google account can submit.
  3. Press Deploy and copy the web app URL that ends in /exec. Open it in a browser: you should see {"ok":true,...} from the doGet function.

Every later change needs a new version. The /exec address keeps running the version you deployed. After editing the code, go to Deploy › Manage deployments, edit the deployment, choose New version and deploy again. The URL stays the same.

Step 4: send leads to it

From your own website form

Point your form at the web app with a few lines of JavaScript. The body is sent form-encoded on purpose: a JSON content type makes the browser send a CORS “preflight” request first, and Apps Script web apps do not answer it, so the lead never arrives.

HTML and JavaScript · your contact page

<form id="lead-form">
  <input name="name" placeholder="Your name" required>
  <input name="email" type="email" placeholder="Email">
  <input name="phone" type="tel" placeholder="Phone">
  <input name="service" placeholder="What do you need?">
  <textarea name="message" placeholder="Tell us more"></textarea>
  <!-- Honeypot: people never see it, bots fill it in -->
  <input name="hp_field" tabindex="-1" autocomplete="off" aria-hidden="true"
         style="position:absolute;left:-9999px">
  <button>Send</button>
  <p id="lead-status" role="status"></p>
</form>
<script>
  const WEB_APP_URL = 'https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec';
  document.getElementById('lead-form').addEventListener('submit', async (event) => {
    event.preventDefault();
    const status = document.getElementById('lead-status');
    const body = new URLSearchParams(new FormData(event.target));
    body.set('source', 'website form');
    try {
      // A form-encoded body is a "simple" request: no CORS preflight for Apps Script to refuse.
      const res = await fetch(WEB_APP_URL, { method: 'POST', body });
      const out = await res.json();
      status.textContent = out.ok ? 'Thanks, we will be in touch.' : 'Please add an email or phone number.';
    } catch (err) {
      status.textContent = 'Something went wrong. Please email us instead.';
    }
  });
</script>

From a chatbot, AI agent or automation tool

Server-side tools have no CORS problem, so they can send JSON. Anything that can make an HTTP POST works: a chatbot platform’s webhook, an AI agent’s tool call, or a Zapier, Make or n8n step. Set source so you can tell the channels apart in the sheet. To test from a terminal:

Terminal · test with curl

curl -L -H "Content-Type: text/plain" \
  -d '{"name":"Jane Doe","email":"jane@example.com","service":"Boiler repair","message":"No hot water since Monday","source":"chatbot"}' \
  "https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec"

The -L matters: Apps Script answers a POST with a redirect to the response, and curl only follows it when asked.

From a Google Form

Link the form to this spreadsheet, then in the Apps Script editor open Triggers (the clock icon), add a trigger for onLeadFormSubmit with the event From spreadsheet › On form submit. The question titles must match the names in the function (Name, Email, Phone, Service, Message). Google still writes its own “Form Responses” tab; the Leads tab becomes the merged, cleaned list next to it.

Things that trip people up

When to hire instead

This script is a solid base for one sheet and one alert. It is worth handing over when leads should also become CRM contacts or opportunities, when several people need different alerts, when you need a weekly summary or follow-up reminders on leads nobody has called, or when nobody on the team wants to look after code.

Botlery builds these on your own Google account with a free fixed-price quote, you test it on your real leads, and the fixed price, held in Upwork escrow from the start of the job, is released when you approve it.

Once the leads are in one sheet, two jobs often follow: a dashboard that shows leads by source and week without anyone building a chart by hand, and a tracker or simple CRM in the same spreadsheet, with a status for each lead and a reminder when one goes quiet.

See Google Sheets automation by Botlery →

If you use a Botlery AI agent, this is built in

Every Botlery AI chatbot, website voice agent and AI phone agent saves each lead it collects to a Google Sheet in your account and emails you, as part of the build, at no extra cost. The agent pulls the name, contact details, request and any booking out of the conversation and writes them in the same format every time. The chatbot costs $200 one-time, built on your own accounts; the voice agent and the phone agent are $300 one-time each. You see a free working demo first. To go live you pay one fixed price through Upwork, where escrow holds it until you approve the build (how to hire Botlery). The script on this page is for everything else: your own forms, landing pages and other tools.

Frequently asked questions

Is it free to save leads to Google Sheets with Apps Script?

Yes. Apps Script comes with every Google account, and the script on this page uses only Google's own services, so there is nothing to pay. The limits are Google's daily quotas. Each alert email counts as one recipient, and Google's published quota is 100 email recipients a day for a free Gmail account and 1,500 for a Google Workspace account (Google's quota page, last updated 3 September 2026 and checked 7 October 2026). Google can change those numbers without notice, so check the page if you are close. If the email quota runs out, the leads are still saved to the sheet; only the alerts stop until the next day.

Why does my website form get a CORS error when posting to an Apps Script web app?

Because the request was sent as JSON. A Content-Type of application/json makes the browser send a preflight OPTIONS request before the real POST, and Apps Script web apps do not respond to it, so the browser blocks the call. Send the form fields form-encoded instead, for example by passing new URLSearchParams(new FormData(form)) as the fetch body, or send JSON as text/plain. Both are simple requests with no preflight, and the script on this page accepts either. Server-side tools such as Zapier, Make, n8n or a chatbot webhook are not affected by CORS, so they can send JSON.

Why do my changes to the Apps Script not show up in the web app?

Because a web app deployment runs a fixed version of the code. Saving the script changes the editor copy but not the deployed version that the /exec address runs. Open Deploy, then Manage deployments, edit the existing deployment, choose New version and deploy. The URL stays the same, so nothing on your website needs changing. Creating a brand-new deployment instead gives you a new URL, which is the most common reason a form suddenly stops saving leads after an edit.

What does a Botlery AI agent save to the Google Sheet for each lead?

For each lead, a Botlery AI agent saves a new row to your Google Sheet with the person's name, their contact details such as phone number or email, what they wanted in their own words or as the service they asked about, the date and time of the conversation, and the booking details if the agent scheduled an appointment. You can ask for extra fields that matter to your business, for example the address of a job, the make of a car, or whether a patient is new. The agent pulls these details out of the conversation and writes them in the same clean format every time, so the sheet is easy to sort and filter. The same capture works for the website chatbot, the website voice agent and the AI phone agent, so all your leads land in one list whichever way the customer reached you.

Does saving leads to Google Sheets cost extra with a Botlery AI agent?

No. Saving each lead to a Google Sheet with an instant email is included in every Botlery AI agent at no extra cost, and there is no per-lead fee. The AI chatbot costs $200 one-time, built on your own accounts. The AI voice agent for your website and the AI phone agent for your business line each cost $300 one-time, built on your own accounts, with provider usage billed to you directly by your AI and phone providers (not Botlery) in proportion to minutes used, so a quiet month may cost only a few dollars and a busy one more. The demo comes first and is free: Botlery builds a working demo trained on your real business and you watch test leads arrive in the sheet and your inbox. To go live you pay one fixed price through Upwork, where escrow holds it until you approve the build. Extra automation on top of the sheet, such as reminders, reports or CRM syncing, is a separate project from $100 with a free fixed-price quote.

Want leads from every channel in one place?

Tell us where your leads come from. AI agents start with a free working demo; automations with a free fixed-price quote.

Get a free demo or quote Hire on Upwork

Keep reading