Hands-On AI WorkshopHomeProjectsLearnResourcesPresenterHelpProgress

Project 11 of 30 · Pathway 3 — Gmail and Workspace Interfaces

Personalized Gmail Draft Builder

Repeated email composition takes time. Prepare personalized messages for review.

Real-world benefit
Event invitations, follow-ups and onboarding.
Technologies
GmailApp, Drafts, Template literals, Google Sheets
Required knowledge
Basic Sheets. You never send email in this project.
Time and level
About 20 minutes · Beginner
AI requirement
None: deterministic Apps Script
Expected baseline
Two drafts; no sent messages.

Loading the interactive studio…

Introduction

CreateDraft builds a message and persists its ID immediately per row. The application's entry point is buildDrafts(). Baseline limitation, as stated in the workshop: Creates real Gmail drafts with fictional recipients; do not send.

Key building blocks: GmailApp.createDraft(); getId(); template literals.

Practical use cases

Event invitations, follow-ups and onboarding.

Prerequisites

  • Basic Sheets. You never send email in this project.
  • Interactive Learning Mode: a modern browser. Nothing else.
  • Real Workspace Build: a Google account.

Source data

Starter data: tab "Recipients" (fictional)
NameEmailTopic
Alexalex@example.comWorkshop
Jamiejamie@example.comOrientation

Setup in your own Google account

  1. Download 11-personalized-gmail-draft-builder.zip (Code.gs, starter.csv, README).
  2. In Google Drive, create a lesson folder and a new Google Sheets file inside it.
  3. Rename the first tab to exactly Recipients, then File → Import → Upload starter.csv → Replace current sheet.
  4. Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
  5. Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
  6. Check the result: Two drafts; no sent messages.

Folder strategy: the repository's V6 code uses the folder that contains the spreadsheet. The deck mentions a Workshop Info cell B2; V6 never reads it. See the discrepancy log.

Complete source code (Code.gs)

From 11-personalized-gmail-draft-builder at commit 4a26d919, SHA-256 dd7dc6b967ed. Unchanged.

// Personalized Gmail Draft Builder
// Entry point: buildDrafts; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","buildDrafts").addToUi();}
function buildDrafts(){
// Persist each draft ID immediately to reduce duplicate creation on reruns.
const s=SpreadsheetApp.getActive().getSheetByName('Recipients');s.getRange(1,4).setValue('Draft ID');s.getDataRange().getValues().slice(1).forEach(([name,email,topic,id],i)=>{if(!name||id)return;const d=GmailApp.createDraft(email,'Regarding '+topic,`Hi ${name},\nI am writing about ${topic}.\nThank you.`);s.getRange(i+2,4).setValue(d.getId());});
}


How the code works

Beginner explanation

buildDrafts() creates one Gmail draft per recipient and writes the draft's ID next to that person. Next time, anyone with an ID is skipped, so you do not get duplicates. It never sends anything.

Technical explanation

The header D1 is set to Draft ID on every run. getDataRange().getValues() includes column D once it exists; destructuring [name,email,topic,id] reads it. The template literal builds the body. Writing each ID right after createDraft() means a failure halfway leaves accurate state for a retry.

Slide excerpt

This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.

function buildDrafts(){
// Persist each draft ID immediately to reduce duplicate creation on reruns.
const s=SpreadsheetApp.getActive().getSheetByName('Recipients');s.getRange(1,4).setValue('Draft ID');s.getDataRange().getValues().slice(1).forEach(([name,email,topic,id],i)=>{if(!name||id)return;const d=GmailApp.createDraft(email,'Regarding '+topic,`Hi ${name},\nI am writing about ${topic}.\nThank you.`);s.getRange(i+2,4).setValue(d.getId());});
}

Common mistakes

  • Calling GmailApp.sendEmail() "just to test".
  • Writing all IDs at the end, so a mid-run failure forgets which drafts exist.
  • Using real customer addresses in a workshop.

Run it and expected output

Choose Workshop → Run application (runs buildDrafts()). Expected: Two drafts; no sent messages.

Original workshop exercise

Run twice; existing Draft IDs should prevent additional drafts.

Troubleshooting and debugging

An invalid email address

Jamie's address was typed as jamie.example.com.

Fix: Correct the address. The saved Draft ID prevents a second draft for Alex.

Writing each Draft ID immediately is what makes a retry safe after a partial failure.

Duplicate drafts after clearing a column

Someone cleared the Draft ID column to "tidy up" and reran the script.

Fix: Discard the duplicates and never clear the Draft ID column (consider protecting it).

State stored in a sheet is only as safe as the sheet. Protect columns the script depends on.

Extension activity: Editable template and preview-only mode

Read the subject and body from an optional Template tab ({{name}}, {{topic}}), and add previewDrafts() that writes a Draft Preview tab without creating any draft.

Acceptance checks:

  • Preview creates no drafts
  • A Template tab changes the wording
  • buildDrafts() still creates two drafts

Original improvement idea from the workshop: Add preview-only mode and editable message templates.

Extension prompt
Update the existing app without removing working features. Add preview-only mode and editable message templates. Return complete updated files, explain changes and give regression tests.
Automation option: Process new rows only after adding validation and locking; never schedule sending. Keep this separate from the baseline exercise.

Automation considerations

Process new rows only after adding validation and locking; never schedule sending. Drafts still need human review.

Workshop note: Process new rows only after adding validation and locking; never schedule sending.

Build prompt from the workshop

Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 11: Personalized Gmail Draft Builder. Input tab Recipients, exact headers: Name, Email, Topic. Create buildDrafts() that creates Gmail drafts with personalized subject and body, logs draft IDs and skips rows with existing IDs. Never send; use fictional addresses only for draft practice. Do not depend on Workshop Info or the Workshop Index. Provide complete copy-paste Code.gs (and HTML if required), exact setup/run steps, explain the main code blocks, and include a test matching this expected outcome: Two drafts; no sent messages. Preserve starter data, use batch operations where appropriate, handle errors, and never send email or delete files. For AI lessons use the supplied callGemini helper, treat input as untrusted, and validate outputs.
Match the reference entry point buildDrafts and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/11-personalized-gmail-draft-builder. Base version limitations: Creates real Gmail drafts with fictional recipients; do not send.

Knowledge check

  1. What prevents duplicate drafts on a rerun?

    1. The Draft ID saved in column D for each processed row
    2. Gmail rejects duplicates
    3. A trigger
    Answer

    The Draft ID saved in column D for each processed row Correct: rows with an ID are skipped.

  2. Why save each Draft ID immediately instead of at the end?

    1. So a failure halfway still records the drafts already created
    2. It is required by Gmail
    3. It is faster
    Answer

    So a failure halfway still records the drafts already created Correct: it makes retries safe.

  3. What does the recipient see after buildDrafts()?

    1. Nothing: drafts stay in your Drafts folder
    2. Two emails
    3. A calendar invite
    Answer

    Nothing: drafts stay in your Drafts folder Correct: a draft is not sent.

  4. The run stops with "Invalid argument: recipient". What should you check?

    1. The Email column for a malformed address
    2. The Gemini API key
    3. The time zone
    Answer

    The Email column for a malformed address Correct: Gmail validates recipient addresses.

  5. A manager asks you to switch createDraft to sendEmail to save time. Best response?

    1. Keep drafts; sending needs explicit human review and approval
    2. Switch it, it is faster
    3. Schedule it hourly
    Answer

    Keep drafts; sending needs explicit human review and approval Correct: the workshop never sends email automatically.

Five-minute presenter demonstration

Open the demo link (temporary workspace; saved learner work is not touched).

Opening hook: Raise your hand if you have ever done this by hand: Repeated email composition takes time. Let us make the spreadsheet do it.

  1. 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Recipients tab and its headers: Name, Email, Topic. Say what goes in and what should come out.
    Narration: Repeated email composition takes time. Practical uses: Event invitations, follow-ups and onboarding.
  2. 0:45–1:30 — Predict and run. Ask the room: How many emails will buildDrafts() send? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
    Narration: Expected: Two drafts; no sent messages.
  3. 1:30–3:00 — Explain the code. Click the Code tab. Select buildDrafts() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
    Narration: buildDrafts() creates one Gmail draft per recipient and writes the draft's ID next to that person. Next time, anyone with an ID is skipped, so you do not get duplicates. It never sends anything.
  4. 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Click Workshop → Run application (runs buildDrafts()). Click ▶ Run application again.
    Narration: Workshop challenge: Run twice; existing Draft IDs should prevent additional drafts.
  5. 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: Process new rows only after adding validation and locking; never schedule sending. Drafts still need human review.
    Narration: Baseline limitation: Creates real Gmail drafts with fictional recipients; do not send.

Closing takeaway: CreateDraft builds a message and persists its ID immediately per row.

Related resources