Having grounded ourselves in the fundamentals of Google Apps Script and the core services like GmailApp and SpreadsheetApp, it's time to move from theory to a powerful, practical application. The previous section provided the tools; this section provides the project. We're about to build something that tackles one of the most common productivity drains in the modern workplace: the overwhelming influx of email.
Imagine your inbox is constantly filling up with newsletters, project updates, customer inquiries, and automated reports. Sifting through them to find the critical information is a job in itself. What if you could have an assistant that reads each new email for you, writes a one-sentence summary, and neatly organizes it in a spreadsheet for a quick scan? That's precisely what we are going to build in this guide.
This step-by-step tutorial will walk you through creating a fully automated workflow that connects Gmail, Google's AI, and Google Sheets. By the end, you'll have a working script that monitors your inbox, summarizes new emails, and logs the results, turning your chaotic inbox into a structured, at-a-glance dashboard.
graph TD
A[New Email Arrives in Gmail] --> B{Apps Script Trigger Fires};
B --> C[Script Fetches Email Content];
C --> D[Sends Content to AI Model];
D --> E[Receives Concise Summary];
E --> F[Writes Summary to Google Sheet];
Our workflow follows a clear and logical path. Let's break down the construction into manageable steps, starting with setting up our destination.
Step 1: Prepare Your Google Sheet
Before we write any code, we need a place to store our summaries. Create a new Google Sheet. Rename it to something memorable, like "AI Email Summary Log." In the first row, create the headers for our data. A good starting point is:
- A1: Timestamp
- B1: From
- C1: Subject
- D1: Summary
- E1: Link to Email
This simple structure gives us all the key information we need. We can see when the summary was logged, who sent the email, what the subject was, the AI-generated summary, and a direct link to the original message if we need more context.
Step 2: Open the Apps Script Editor
With your Google Sheet open, navigate to Extensions > Apps Script. This will open a new tab with the script editor, bound directly to your spreadsheet. This is where we will write the code to orchestrate our workflow. Delete any boilerplate code in the Code.gs file so you have a blank slate.
Step 3: Write the Code to Fetch and Summarize Emails
Now, let's write the core logic. We'll create a single function that performs all the necessary actions. The process involves searching Gmail for unread messages, looping through them, extracting the content, sending it to Google's generative AI for summarization, and then writing the results to our sheet. Note that modern Apps Script environments have direct access to Google's AI models, simplifying what used to be a complex integration.
const SPREADSHEET_ID = 'YOUR_SPREADSHEET_ID_HERE'; // Find this in your Sheet's URL
const SHEET_NAME = 'Sheet1'; // Or whatever you named your sheet tab
const GMAIL_QUERY = 'is:unread label:process-for-summary'; // The search query for Gmail
function summarizeNewEmails() {
const sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName(SHEET_NAME);
// Find the threads that match our query
const threads = GmailApp.search(GMAIL_QUERY);
// Process each thread
for (const thread of threads) {
const message = thread.getMessages()[0]; // Get the first message in the thread
const emailBody = message.getPlainBody();
// Guard against very long emails to manage costs and processing time
if (emailBody.length > 100 && emailBody.length < 15000) {
// Use the built-in Generative AI model
const prompt = `Summarize the following email content in a single, concise sentence: \n\n${emailBody}`;
const summary = GenerativeAI.getGenerativeModel({ model: 'gemini-pro' }).generateContent(prompt).text;
// Prepare the data for the spreadsheet
const rowData = [
new Date(),
message.getFrom(),
message.getSubject(),
summary.trim(),
thread.getPermalink()
];
// Append the new row to our sheet
sheet.appendRow(rowData);
}
// Mark the thread as read and remove the label to avoid processing it again
thread.markRead();
thread.removeLabel(GmailApp.getUserLabelByName('process-for-summary'));
}
}Before you run this, a couple of important setup notes. First, create a new label in your Gmail account named process-for-summary. This is how you'll tag emails you want the script to handle. Second, replace 'YOUR_SPREADSHEET_ID_HERE' with the actual ID from your Google Sheet's URL. You'll be prompted to grant permissions the first time you try to run the script. This is normal; you are giving your code permission to access your Gmail and Sheets data.
Step 4: Set Up the Automation with a Trigger
A script that you have to run manually isn't a true workflow. The final step is to make it run automatically. In the Apps Script editor, click on the "Triggers" icon (it looks like a clock) in the left-hand sidebar.
- Click the "+ Add Trigger" button in the bottom right.
- Choose the
summarizeNewEmailsfunction to run. - Select "Time-driven" as the event source.
- Choose a "Minutes timer" and set it to "Every 15 minutes" or a frequency that suits your needs.
- Click "Save".
And that's it! You have successfully built an automated, AI-powered email summarization workflow. Now, whenever you apply the process-for-summary label to an email in Gmail, your script will pick it up within 15 minutes, generate a summary, log it to your Google Sheet, and clean up after itself by marking the email as read and removing the label.
You've taken a significant step from understanding the tools to building a genuinely useful automation. This project saves time, reduces cognitive load, and transforms raw information into a structured, actionable format. Now that you can automatically summarize content, the next logical question is: how can we make the AI do even more? What if it could not only summarize but also categorize these emails for us, sorting them into buckets like "Urgent," "Requires Action," or "General Info"? We'll tackle that exact challenge in the next section.
References
- Google. (2024). Generative AI in Google Apps Script. Retrieved from developers.google.com/apps-script/reference/generative-ai.
- Google. (2024). Installable Triggers Guide. Retrieved from developers.google.com/apps-script/guides/triggers/installable.
- Sholts, B. (2023). Automating Google Workspace: A Developer's Guide. O'Reilly Media.
- Rose, A. (2022). Google Apps Script: Web App and API Development. Apress.
- Google Cloud. (2024). Introduction to Gemini AI Models. Retrieved from cloud.google.com/vertex-ai/docs/generative-ai/learn/models.