Introduction
messageSummary counts messages and unread flags per sender; live mode searches up to ten threads. The application's entry point is analyzeMessages(). Baseline limitation, as stated in the workshop: Live inbox option accesses real messages; default uses synthetic rows.
Key building blocks: GmailApp.search(); getMessages(); isUnread(); Map.
Practical use cases
Support triage and personal email workload.
Prerequisites
- Basic Sheets.
- Interactive Learning Mode: a modern browser. Nothing else.
- Real Workspace Build: a Google account.
Source data
| Sender | Subject | Date | Unread |
|---|---|---|---|
| alex@example.com | Question | 2026-11-01 | TRUE |
| alex@example.com | Follow-up | 2026-11-02 | FALSE |
| jamie@example.com | Update | 2026-11-02 | TRUE |
Setup in your own Google account
- Download 12-email-analytics-dashboard.zip (Code.gs, starter.csv, README).
- In Google Drive, create a lesson folder and a new Google Sheets file inside it.
- Rename the first tab to exactly
Messages, then File → Import → Upload starter.csv → Replace current sheet. - Extensions → Apps Script. Replace Code.gs with the downloaded file. Save.
- Reload the spreadsheet, choose Workshop → Run application and authorize when asked.
- Check the result: Alex 2 messages/1 unread; Jamie 1/1.
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 12-email-analytics-dashboard at commit 4a26d919, SHA-256 e7accf831805. Unchanged.
// Email Analytics Dashboard
// Entry point: analyzeMessages; source data stays intact unless explicitly noted.
function onOpen(){SpreadsheetApp.getUi().createMenu("Workshop").addItem("Run application","analyzeMessages").addItem("Analyze live inbox","analyzeLive").addToUi();}
function analyzeMessages(){
// Use fictional sample messages by default, not the real inbox.
messageSummary(input('Messages'));
}
function input(name) { const s=SpreadsheetApp.getActive().getSheetByName(name); if(!s) throw Error('Missing tab: '+name); return s.getDataRange().getValues().slice(1).filter(r=>r.some(v=>v!=='')); }
function output(name,headers,rows) { const ss=SpreadsheetApp.getActive(); const s=ss.getSheetByName(name)||ss.insertSheet(name); s.clearContents(); s.getRange(1,1,1,headers.length).setValues([headers]).setFontWeight('bold'); if(rows.length) s.getRange(2,1,rows.length,headers.length).setValues(rows.map(r=>r.map(v=>typeof v==='string' && /^[=+@-]/.test(v)?"'"+v:v))); s.setFrozenRows(1); return s; }
function messageSummary(rows){const m={};rows.forEach(r=>{const k=r[0];m[k]=m[k]||[0,0];m[k][0]++;if(r[3]===true||String(r[3]).toLowerCase()==='true'||String(r[3]).toLowerCase()==='yes')m[k][1]++;});output('Analytics',['Sender','Messages','Unread'],Object.entries(m).map(([k,v])=>[k,...v]));}
function analyzeLive(){const ui=SpreadsheetApp.getUi(),p=ui.prompt('Gmail search query (max 10 threads)');if(p.getSelectedButton()!==ui.Button.OK||!p.getResponseText().trim())return;const rows=GmailApp.search(p.getResponseText(),0,10).flatMap(t=>t.getMessages().map(m=>[m.getFrom(),m.getSubject(),m.getDate(),m.isUnread()]));messageSummary(rows);}
How the code works
Beginner explanation
analyzeMessages() counts how many messages each sender sent and how many are unread, using fictional sample rows. An optional menu item can do the same for a real Gmail search, but only in your own account.
Technical explanation
messageSummary() builds a map sender → [messages, unread]. Unread accepts true, "true" or "yes" (case-insensitive). analyzeLive() prompts for a query, limits the search to 10 threads, flattens messages and reuses the same summary function, so the logic is tested on sample data first.
Slide excerpt
This is the excerpt shown on the workshop slide. It is a fragment and cannot run on its own.
function analyzeMessages(){
// Use fictional sample messages by default, not the real inbox.
messageSummary(input('Messages'));
}Common mistakes
- Testing analytics against a real inbox before it works on sample data.
- Not limiting a Gmail search, which can be slow and hit quotas.
- Confusing threads with messages.
Run it and expected output
Choose Workshop → Run application (runs analyzeMessages()). Expected: Alex 2 messages/1 unread; Jamie 1/1.
Original workshop exercise
Change first sample unread value to FALSE; Alex unread count becomes zero.
Troubleshooting and debugging
"yes " is not counted
Someone typed "yes " (with a trailing space) for an unread message. Alex now shows 0 unread although one message is unread.
Fix: Use TRUE/FALSE (or trim values before comparing).
Free-typed status values drift. A checkbox or data validation prevents this class of bug.
The same sender appears twice
One sender was typed with a capital letter.
Fix: Normalize email addresses to lower case before grouping.
Grouping keys must be normalized, just like duplicate detection in Project 02.
Extension activity: Messages per day with a chart
Add a By Date tab with the number of messages per day and a column chart, without changing the Analytics tab.
Acceptance checks:
- Analytics unchanged
- By Date counts 1 on 2026-11-01 and 2 on 2026-11-02, with one chart
Original improvement idea from the workshop: Add date grouping and chart; distinguish threads from messages.
Extension prompt
Update the existing app without removing working features. Add date grouping and chart; distinguish threads from messages. Return complete updated files, explain changes and give regression tests. Automation option: Schedule a sample or explicitly scoped query version without UI prompts. Keep this separate from the baseline exercise.
Automation considerations
The sample version is rerun-safe. A scheduled live version must use a fixed, narrow query without UI prompts and respect privacy.
Workshop note: Schedule a sample or explicitly scoped query version without UI prompts.
Build prompt from the workshop
Act as a Google Apps Script tutor. Build a container-bound Sheets app for lesson 12: Email Analytics Dashboard. Input tab Messages, exact headers: Sender, Subject, Date, Unread. Create analyzeMessages() using sample rows by default; count messages and unread by sender. Add optional separate live function using GmailApp.search with a user-entered query and maximum 10 threads; do not write bodies. 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: Alex 2 messages/1 unread; Jamie 1/1. 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 analyzeMessages and its output behavior. Reference: https://github.com/lsvekis/Google-Apps-Script-Workshop/tree/main/12-email-analytics-dashboard. Base version limitations: Live inbox option accesses real messages; default uses synthetic rows.
Knowledge check
Why does the default menu item analyze the Messages tab instead of your inbox?
- So the logic is tested on fictional data before touching real email
- Gmail cannot be read by scripts
- It is faster
Answer
So the logic is tested on fictional data before touching real email Correct: sample first, live data second.
Which Unread values are counted?
- TRUE, "true" or "yes" in any letter case
- Any non-empty value
- Only the number 1
Answer
TRUE, "true" or "yes" in any letter case Correct: the code checks true or lower-cased "true"/"yes".
Why does analyzeLive() pass 0, 10 to GmailApp.search?
- To limit the search to the first 10 threads
- To search the last 10 days
- To skip 10 messages
Answer
To limit the search to the first 10 threads Correct: start 0, max 10 threads.
Analytics lists alex@example.com and Alex@example.com separately. Fix?
- Normalize the sender to lower case before grouping
- Delete one message
- Sort the tab
Answer
Normalize the sender to lower case before grouping Correct: grouping keys must be normalized.
A colleague wants to analyze the whole company inbox. What do you ask first?
- Whether they have permission and how the results will be protected
- Which chart color to use
- Nothing
Answer
Whether they have permission and how the results will be protected Correct: email metadata is personal data.
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: Inbox volume is hard to understand by inspection. Let us make the spreadsheet do it.
- 0:00–0:45 — Problem and input. Show the Workspace view, Sheets service. Point at the Messages tab and its headers: Sender, Subject, Date, Unread. Say what goes in and what should come out.
Narration: Inbox volume is hard to understand by inspection. Practical uses: Support triage and personal email workload. - 0:45–1:30 — Predict and run. Ask the room: How many unread messages will Alex have? Click ▶ Run application (the same as Workshop → Run application). Open Trace to show each step the code took.
Narration: Expected: Alex 2 messages/1 unread; Jamie 1/1. - 1:30–3:00 — Explain the code. Click the Code tab. Select analyzeMessages() in the function list; read what it reads, writes and calls. Switch Beginner / Technical as needed.
Narration: analyzeMessages() counts how many messages each sender sent and how many are unread, using fictional sample rows. An optional menu item can do the same for a real Gmail search, but only in your own account. - 3:00–4:15 — Change one input and rerun. Back to the Workspace tab. Select the Messages tab, click cell D2, type FALSE in the formula bar and press Enter. Click ▶ Run application again.
Narration: Workshop challenge: Change first sample unread value to FALSE; Alex unread count becomes zero. - 4:15–5:00 — Verify and discuss automation. Click Check result. Discuss: The sample version is rerun-safe. A scheduled live version must use a fixed, narrow query without UI prompts and respect privacy.
Narration: Baseline limitation: Live inbox option accesses real messages; default uses synthetic rows.
Closing takeaway: messageSummary counts messages and unread flags per sender; live mode searches up to ten threads.