Often searched for as Google Scripts, Google Apps Script is Google’s JavaScript-based platform for automating and extending Google Workspace. It runs on Google’s servers, so there’s nothing to install. The most useful business scripts are small ones: they save Gmail attachments to Drive, route form requests, create documents from a template, add calendar events from a sheet, or flag risky file sharing. If your task fits a simple “when this happens, do that” pattern, a Google Workspace Studio flow may get you there without code.
Below are seven examples you can adapt, each with a short snippet, followed by a side-by-side look at when to use Apps Script, when to use Workspace Studio, and when to use both.
Snippets are short on purpose. They show the core idea, not a finished production tool. Replace the IDs and email addresses with your own, test in a copy of your data first, and read what to sort out before a script goes live below.
How to run these examples
- Open the Google Sheet, Doc or Form you want to automate and go to Extensions > Apps Script. This creates a script bound to that file. For a standalone script, go to script.google.com.
- Paste the code, fill in the IDs, and run the function once from the editor. Google asks you to authorize the scopes the script needs (Gmail, Drive and so on).
- Add a trigger so it runs on its own. Use the Triggers (clock icon) panel in the editor, or create one in code with an installable trigger.
1. Save Gmail attachments to a Drive folder
Good for: finance teams that receive invoices or statements by email and file them by hand.
The script searches Gmail for messages that have an attachment and “invoice” in the subject, copies each attachment into a Drive folder, then labels the thread so it isn’t processed twice.
const FOLDER_ID = 'YOUR_DRIVE_FOLDER_ID';
const DONE_LABEL = 'saved-to-drive';
function saveInvoiceAttachments() {
const folder = DriveApp.getFolderById(FOLDER_ID);
const label = GmailApp.getUserLabelByName(DONE_LABEL) || GmailApp.createLabel(DONE_LABEL);
const threads = GmailApp.search(`has:attachment subject:invoice -label:${DONE_LABEL}`, 0, 50);
threads.forEach((thread) => {
thread.getMessages().forEach((message) => {
message.getAttachments({ includeInlineImages: false })
.forEach((attachment) => folder.createFile(attachment.copyBlob()));
});
thread.addLabel(label);
});
}
// Run once to check Gmail every hour.
function createHourlyTrigger() {
ScriptApp.newTrigger('saveInvoiceAttachments').timeBased().everyHours(1).create();
}
Tip: the search uses normal Gmail search operators, so you can narrow it to one sender (from:billing@example.com) before you widen it. Processing 50 threads per run keeps each run well inside the 6-minute execution limit. Because the label goes on the whole thread, a later invoice sent as a reply in the same thread is skipped; if invoices often arrive that way, track the last run time instead of relying on the label alone.
2. Create personalized Gmail drafts from a Sheet
Good for: account managers sending renewal reminders or onboarding notes who want a person to check each email before it goes out.
Each row in a “Renewals” sheet becomes a Gmail draft. The script writes the time it ran back to the sheet, so running it again doesn’t create duplicates. Drafts (not sends) keep a human in the loop.
function createRenewalDrafts() {
const sheet = SpreadsheetApp.getActive().getSheetByName('Renewals');
const [header, ...rows] = sheet.getDataRange().getValues();
const col = (name) => header.indexOf(name);
rows.forEach((row, i) => {
const email = row[col('Email')];
if (!email || row[col('Draft created')]) return; // skip blanks and rows already done
GmailApp.createDraft(
email,
'Your renewal is coming up',
`Hi ${row[col('First name')]},\n\nYour plan renews soon. Reply to this email if anything has changed.\n\nThanks,`
);
sheet.getRange(i + 2, col('Draft created') + 1).setValue(new Date());
});
}
The sheet needs the columns Email, First name and Draft created. If you later switch to sending directly with MailApp, keep Google’s daily recipient quota in mind (see the limits table below).
3. Route Google Form requests to the right team
Good for: IT, facilities or HR request forms where every submission currently lands in one shared inbox.
Link the form to a Google Sheet, open the sheet’s script editor and add this code. A form-submit trigger passes the answers in e.namedValues, keyed by question title.
const ROUTING = {
IT: 'it-requests@example.com',
Finance: 'finance-requests@example.com',
};
function onRequestSubmitted(e) {
const answers = e.namedValues;
const team = answers['Team'][0];
const to = ROUTING[team] || 'operations@example.com';
MailApp.sendEmail({
to: to,
subject: `New ${team} request from ${answers['Name'][0]}`,
body: `${answers['Details'][0]}\n\nSee row ${e.range.getRow()} in the responses sheet.`,
});
}
// Run once to connect the function to form submissions.
function createFormTrigger() {
ScriptApp.newTrigger('onRequestSubmitted')
.forSpreadsheet(SpreadsheetApp.getActive())
.onFormSubmit()
.create();
}
The keys (Team, Name, Details) must match your form’s question titles exactly. This one is a good candidate for Workspace Studio too, which has a built-in Google Forms starter. Reach for Apps Script when the routing rules get complicated or need data from another system.
4. Generate a document and PDF from a template
Good for: offer letters, welcome packs, statements of work or certificates built from the same template every time.
Make a Google Doc with placeholders like {{Name}} and {{Start date}}. The script copies the template, fills in the placeholders and saves a PDF next to it.
const TEMPLATE_ID = 'YOUR_TEMPLATE_DOC_ID';
const OUTPUT_FOLDER_ID = 'YOUR_OUTPUT_FOLDER_ID';
function createWelcomeLetter(name, startDate) {
const folder = DriveApp.getFolderById(OUTPUT_FOLDER_ID);
const copy = DriveApp.getFileById(TEMPLATE_ID).makeCopy(`Welcome letter - ${name}`, folder);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
body.replaceText('{{Name}}', name);
body.replaceText('{{Start date}}', startDate);
doc.saveAndClose();
return folder.createFile(copy.getAs(MimeType.PDF));
}
Call createWelcomeLetter() from a form-submit trigger (example 3) or a custom menu in Sheets, and you have a self-serve document generator. Note that replaceText treats the search text as a regular expression, so keep placeholder names simple.
5. Flag Drive files shared with “anyone with the link”
Good for: teams that want a quick, regular check on how a sensitive folder is shared.
This script lists the files in one folder that anyone on the internet, or anyone with the link, can open, and writes them to a “Sharing audit” sheet.
const AUDIT_FOLDER_ID = 'YOUR_FOLDER_ID';
function auditLinkSharing() {
const sheet = SpreadsheetApp.getActive().getSheetByName('Sharing audit');
const files = DriveApp.getFolderById(AUDIT_FOLDER_ID).getFiles();
const rows = [];
while (files.hasNext()) {
const file = files.next();
const access = file.getSharingAccess();
if (access === DriveApp.Access.ANYONE || access === DriveApp.Access.ANYONE_WITH_LINK) {
rows.push([file.getName(), file.getUrl(), String(access), file.getLastUpdated()]);
}
}
sheet.clearContents();
sheet.appendRow(['File', 'URL', 'Access', 'Last updated']);
if (rows.length) sheet.getRange(2, 1, rows.length, rows[0].length).setValues(rows);
}
It checks one folder level (not subfolders) and only sees files the person running it can access. For a domain-wide view, admins should use the reporting and security tools in the Google Admin console rather than a script.
6. Create Google Calendar events from a Sheet
Good for: onboarding schedules, training sessions or site visits planned in a spreadsheet.
Each row has a title, a start and end (as date-time cells) and a comma-separated guest list. The script stores the event ID in the sheet so a row is only scheduled once.
function createEventsFromSheet() {
const calendar = CalendarApp.getDefaultCalendar();
const sheet = SpreadsheetApp.getActive().getSheetByName('Sessions');
const rows = sheet.getDataRange().getValues().slice(1); // skip the header row
rows.forEach(([title, start, end, guests, eventId], i) => {
if (!title || eventId) return;
const event = calendar.createEvent(title, start, end, {
guests: guests,
sendInvites: true,
});
sheet.getRange(i + 2, 5).setValue(event.getId());
});
}
If the start and end cells aren’t true dates, convert them first. Times are read in the script’s time zone unless you say otherwise, so check it under Project Settings if your team spans regions.
7. Triage support emails with Gemini
Good for: shared support or sales inboxes where someone sorts every message by hand.
Apps Script can call Gemini through its Vertex AI advanced service (that’s the name you’ll see in the editor’s list of advanced services). You’ll need a Google Cloud project with billing turned on, and the API Google’s page names (currently the Agent Platform API, formerly the Vertex AI API) enabled in that project. Google’s page includes a ready-made callVertexAI(prompt) helper; this example reuses it to sort unread support emails into three labels.
const CATEGORIES = ['billing', 'technical', 'other'];
function triageSupportEmails() {
const done = GmailApp.getUserLabelByName('triaged') || GmailApp.createLabel('triaged');
const threads = GmailApp.search('in:inbox is:unread label:support -label:triaged', 0, 20);
threads.forEach((thread) => {
const text = thread.getMessages()[0].getPlainBody().slice(0, 4000);
// callVertexAI() is not defined here: copy it from
// https://developers.google.com/apps-script/advanced/vertex-ai
const answer = callVertexAI(
`Classify this email as one word: billing, technical or other.\n\n${text}`
).trim().toLowerCase();
const category = CATEGORIES.includes(answer) ? answer : 'other';
const label = GmailApp.getUserLabelByName(category) || GmailApp.createLabel(category);
thread.addLabel(label);
thread.addLabel(done);
});
}
Two habits make AI steps safer. First, only accept answers from a fixed list (as above), so an odd model reply can’t create random labels. Second, let Gemini label, summarize or draft, and leave sending and deleting to a person. Google’s sample sets a specific model name; check Google’s current model list before you deploy, because model names change.
Apps Script or Google Workspace Studio: which should you use?
Google Workspace Studio (previously known as Google Workspace Flows) lets people build automations without code. Every flow has a starter (an event, a schedule or a manual run) and one or more steps, including AI steps that use Gemini. It works across Gmail, Calendar, Chat, Drive, Docs, Forms, Sheets and Tasks, plus selected third-party apps.
Three flows that are often quicker to build in Studio than in code, all based on Google’s own getting-started examples:
- Save attachments from certain emails to a Drive folder.
- Get a Google Chat message whenever someone submits a Google Form.
- Get an AI-generated summary of new emails.
If you already use Gems in flows: Google is replacing Gems with skills, reusable instructions you can add to an “Ask Gemini” step. New “Ask a Gem” steps can’t be added any more, and flows with an “Ask a Gem” step will stop working from March 2027, so swap them for “Ask Gemini” steps before then. Skills are rolling out gradually, starting October 5, 2026.
The two aren’t rivals. Since September 2026, developers can build custom steps for Workspace Studio with Apps Script, so a business user can drop your script into their own flow. Google turns custom steps off by default, and an admin enables them in the Admin console.
| Workspace Studio flow | Apps Script | Both: Apps Script custom step in a flow | |
|---|---|---|---|
| Who builds it | Anyone with access, by describing it to Gemini or using a template | Someone comfortable with JavaScript | A developer builds the step; business users add it to their flows |
| Best for | Notifications, summaries, simple routing, saving attachments | Custom logic, bulk data work, documents from templates, other APIs | Reusable logic that many teams need in their own flows |
| Gemini | Built in as AI steps | Through the Vertex AI advanced service and a Google Cloud project | Either |
| Published limits | Up to 25 flows per user (on or off), 100 steps per flow and 25 active Gmail-started flows, plus a daily run limit | 6 minutes per run and 6 hours of trigger runtime a day on Workspace accounts | Both apply |
| Availability | Eligible editions only: Google lists Business Starter, Standard and Plus; Enterprise Standard and Plus; and some Education plans and add-ons. Your admin must turn on Gemini for your account | Google Workspace and personal Google accounts | Custom steps off by default; an admin turns them on |
| Who keeps it running | The flow owner, from the Activity tab | Whoever owns the script and its triggers | Developer (the step) and flow owner (the flow) |
A simple rule of thumb: start with a Workspace Studio flow if the task is “when X happens, tell someone or file something”. Choose Apps Script when you need loops over lots of rows, exact formatting, a custom menu or sidebar, or a connection to a system Studio doesn’t reach. If several teams need the same custom logic, build it once in Apps Script as a custom step.
Apps Script limits to know before you build
Google publishes Apps Script quotas and can change them without notice. A few that most often shape a design, for Google Workspace accounts at the time of writing:
| Limit | Google Workspace accounts |
|---|---|
| Script run time | 6 minutes per execution |
| Custom function run time (Sheets) | 30 seconds per execution |
| Total trigger run time | 6 hours per day |
| Triggers | 20 per user per script |
| Email recipients per day (for example with MailApp) | 1,500 |
| URL Fetch calls | 100,000 per day |
When a job outgrows these, split it into batches and save your place between runs (for example, the last row processed, stored in Script Properties), so the next run picks up where the last one stopped. Google’s quotas page also lists the exact error messages you’ll see when a limit is hit, such as Service invoked too many times, which makes failures quicker to diagnose.
What to sort out before a script goes live
The code is usually the easy part. These are the things that decide whether an automation is still working in six months:
- Ownership. Installable triggers always run as the person who created them. If that person leaves, the automation can stop. Agree on who owns production scripts, and document the triggers.
- Scopes. Scripts ask for access to Gmail, Drive and other data. Review the authorization scopes and keep them as narrow as the job allows.
- Settings outside the code. Keep folder IDs and similar values in Script Properties, not hard-coded in several places. Never paste passwords or API keys into the code.
- Errors. When a trigger fails, Apps Script sends the owner a failure summary email, and the Executions page shows the details. Make sure someone actually reads those.
- Overlapping runs. If a script can be started twice at once (for example by two form submissions), use the Lock service so the runs don’t overwrite each other.
- Version control. For anything business-critical, keep the code in a repository with clasp, Google’s command-line tool for Apps Script.
Talk to Premier Cloud
Frequently asked questions
Is “Google Scripts” the same as Google Apps Script?
Yes. People often search for “Google Scripts”, but the product is called Google Apps Script. You write and manage scripts at script.google.com, or from Extensions > Apps Script inside a Sheet, Doc or Form.
Do I need a Google Workspace account to use Apps Script?
No. Apps Script also works with personal Google accounts, but Google sets lower quotas for them. For example, trigger run time is 90 minutes a day on a consumer account versus 6 hours on a Workspace account.
Do I need to buy anything extra to use Apps Script?
Apps Script is included with your Google account; there’s no separate Apps Script license. Some features add requirements: calling Gemini through the Vertex AI advanced service needs a Google Cloud project with billing turned on, and Workspace Studio needs an eligible Workspace edition.
What’s the difference between a simple trigger and an installable trigger?
Simple triggers such as onOpen() run automatically but can’t call services that need authorization. Installable triggers can, and they add time-driven (clock) triggers, which run a function on a schedule as often as every minute or as rarely as once a month.
Can Apps Script use Gemini?
Yes, through the Vertex AI advanced service (see example 7). For no-code AI automation, Workspace Studio has built-in AI steps.
Should I use Workspace Studio instead of Apps Script?
Often, for simple “when this happens, do that” tasks. For custom logic, bulk data or integrations, use Apps Script, or combine the two. See the comparison table above.
What happens to my scripts if the person who created them leaves?
Installable triggers run as the account that created them, so automations owned by a departing employee can stop when that account is suspended or deleted. Plan ownership and handover before a script goes into daily use.
- Google Apps Script overview
- Workspace Studio Help: get started
- Apps Script: authorization for Google services
- Apps Script: installable triggers
- Gmail Help: search operators
- Apps Script: quotas for Google services
- Apps Script reference: MailApp
- Apps Script: event objects
- Apps Script reference: Body (Docs)
- Apps Script reference: Calendar
- Apps Script: Vertex AI advanced service
- Google Workspace Studio
- Workspace Studio Help: skills
- Workspace Studio Help: Gems to skills in flows
- Workspace Updates: custom starters and steps in Workspace Studio
- Workspace Studio Help: limits
- Apps Script: Properties service
- Apps Script: authorization scopes
- Apps Script reference: Lock service
- Apps Script: clasp command-line tool
