Sifting through a mountain of emails every day to manually find the ones you need is exhausting, isn’t it? Whether you’re worried about missing crucial unread messages or spending every morning compiling specific customer inquiries by hand, email management is often a massive drain on your time.
With GAS (Google Apps Script), you can call Gmail’s powerful search capabilities right from your code and extract target emails automatically in an instant!
In this 33rd installment of our series, we will take a deep dive into GmailApp.search(), the cornerstone method for Gmail automation.
From utilizing the exact same search operators (queries) you use in the Gmail search bar every day, to understanding the difference between “threads” and “messages” (a concept that trips up nearly every beginner), and even writing practical code that auto-exports search results directly into Google Sheets—we’ll break everything down step-by-step so it’s super easy to follow!
1. What Is GmailApp.search() in the First Place?
GmailApp.search() is a Google Apps Script method used to search within your Gmail account and retrieve a collection of email conversations (threads) that match specified criteria.
In everyday Gmail usage, you probably type filters like is:unread or from:info@example.com into the search box at the top of your screen. GmailApp.search() lets you run identical search criteria programmatically.
Basic Syntax
// Search and retrieve email threads (conversations) matching criteria
var threads = GmailApp.search("search query");
2. Essential Concept: The Difference Between “Threads” and “Messages”
To master GmailApp.search(), there is one fundamental concept you must grasp: the difference between a “thread” and a “message.”
In Gmail, a series of replies and messages with the same subject line are grouped together into a single conversation. In Gmail terminology, this group is called a Thread.
Think of it as a “Binder and Letters”!
- Thread (GmailThread) = A binder (clear folder) that holds all emails related to a specific topic.
- Message (GmailMessage) = Each individual letter (single email) stored inside that binder.
[Thread: Sapporo Office Business Trip Schedule] (Binder)
├── Message 1: Initial email from Sato: "Candidate Dates"
├── Message 2: My reply: "Accepted"
└── Message 3: Confirmation email from Sato: "Detailed Information"
The result returned by GmailApp.search() is not a list of individual messages, but an array of Threads.
Therefore, to extract the actual body text or sender information from your search results, you must first grab the thread, and then extract the individual messages contained inside it.
3. Ready for Practical Use! Gmail Search Queries (Operators) Reference
Inside the parentheses of GmailApp.search(), you write the exact same query strings you would enter into the Gmail search box. Here is a summary of the most useful queries for everyday business automation.
| Search Query | Description / Behavior | Example |
is:unread |
Searches unread emails only | GmailApp.search("is:unread") |
is:read |
Searches read emails only | GmailApp.search("is:read") |
subject:XXX |
Emails containing “XXX” in the subject | GmailApp.search("subject:Sapporo Office") |
from:XXX |
Emails from the specified sender | GmailApp.search("from:city.sapporo.jp") |
to:XXX |
Emails sent to the specified recipient | GmailApp.search("to:me") |
has:attachment |
Emails with attachments | GmailApp.search("has:attachment") |
label:XXX |
Emails tagged with the specified label | GmailApp.search("label:Soup Curry Club") |
after:YYYY/MM/DD |
Emails received on or after the date | GmailApp.search("after:2026/09/01") |
before:YYYY/MM/DD |
Emails received before the date | GmailApp.search("before:2026/09/30") |
Combine Them Freely!
Separating queries with a space creates an AND search.
"is:unread subject:Sapporo City"➡ Unread emails that also contain “Sapporo City” in the subject line"from:secoma.co.jp has:attachment"➡ Emails from Seicomart that include file attachments
4. STEP 1: Preparation! Create a Test Email
First, let’s prepare a test email to verify that our GAS script searches correctly.
Steps
- Open your Gmail.
- Send a test email to yourself (your own email address):
- Subject:
[Important] Notice from Sapporo City: Autumn Disaster Drill - Body:
Dear Sapporo Office members, here is the schedule for the autumn disaster drill.
- Subject:
- Once received in your inbox, set the email status back to “Unread” (click the unread icon in your email list or right-click and choose Mark as unread).
5. STEP 2: [Hands-on] Search Unread Emails Using GmailApp.search()
Now, let’s write a script to search for that unread “Notice from Sapporo City” email automatically using GAS!
1. Open the GAS Script Editor
Open any Google Spreadsheet and click Extensions > Apps Script in the top menu to open the script editor.
2. Enter the Code
Clear any existing placeholder code in the editor and paste the following script:
function searchSapporoEmails() {
// 1. Set the search query (unread AND containing "Sapporo City" in subject)
var query = "is:unread subject:Sapporo City";
// 2. Fetch all matching threads from Gmail
var threads = GmailApp.search(query);
// 3. Log the number of matching threads found (leveraging Logger.log from Lesson 1!)
Logger.log("Matching threads found: " + threads.length);
}
3. First Run and Authorizing Access
- Click the Save (floppy disk icon) button at the top, then click Run.
- On your first run, an “Authorization required” modal will appear.
- Click Review permissions > select your Google account > click Advanced > click Go to Untitled project (unsafe) > click Allow to grant access.
4. Check the Execution Log
If you see output like the following in the Execution log at the bottom of the editor, you’re all set!
Info Matching threads found: 1
GAS scanned your Gmail inbox automatically and located the exact target email thread!
6. STEP 3: Extract and Display Subject Lines from Search Results
Now that we can count matching threads, let’s output their actual subject lines (titles) to the log.
By using the .getFirstUserMessageSubject() method available on thread objects, you can easily retrieve the subject line of that thread.
function printSapporoEmailSubjects() {
// Search for unread "Sapporo City" emails
var threads = GmailApp.search("is:unread subject:Sapporo City");
// Safety check: Exit if nothing matches
if (threads.length === 0) {
Logger.log("No matching emails were found.");
return;
}
// Loop through all retrieved threads
for (var i = 0; i < threads.length; i++) {
var thread = threads[i]; // Get the i-th thread
var subject = thread.getFirstUserMessageSubject(); // Retrieve the subject
Logger.log("[" + (i + 1) + "] Subject: " + subject);
}
}
Sample Execution Log
Info [1] Subject: [Important] Notice from Sapporo City: Autumn Disaster Drill
7. Avoid These Pitfalls! 4 Common Traps for Beginners and How to Fix Them
Here are four of the most frequent errors and traps beginners run into when working with GmailApp.search().
Trap 1: Calling Thread Methods Directly on an Array
Remember that GmailApp.search() returns an array (list) of threads, not a single thread object.
// ✕ Incorrect: threads is an array, so thread methods cannot be called directly
var threads = GmailApp.search("is:unread");
var subject = threads.getFirstUserMessageSubject(); // Throws TypeError!
// ◯ Correct: Access an element using an index like [0]
var threads = GmailApp.search("is:unread");
if (threads.length > 0) {
var subject = threads[0].getFirstUserMessageSubject();
}
Trap 2: Overlooking the Default Search Limit
When you execute GmailApp.search("query") on its own, it fetches a maximum of 50 threads by default.
If you need to process more than 50 emails at a time, use the overloaded syntax by specifying the second argument (start index) and third argument (maximum count).
// Retrieve up to 100 threads starting from index 0 (the most recent)
var threads = GmailApp.search("is:unread", 0, 100);
Trap 3: Full-Width Spaces Breaking the Query
If you accidentally introduce a full-width space (common in East Asian IME setups) between keywords, Gmail will fail to parse the search criteria properly and return zero results.
Always ensure that separator spaces in your search queries are standard half-width spaces.
Trap 4: Processing the Same Emails Over and Over
If your search query is simply GmailApp.search("subject:Invoice"), previously processed emails will match every single time the script executes.
When designing automation scripts for real-world tasks, always implement a workflow to target only “unprocessed” messages:
- Include
is:unreadin your query, and mark messages as read (markRead()) after processing. - Apply a custom label (such as “GAS-Processed”) to finished threads, and exclude them in your query using
-label:GAS-Processed.
8. Practical Application: Auto-Export Search Results to Google Sheets
Finally, let’s combine what we’ve learned so far to build a practical tool: automatically searching Gmail and appending matching email summaries directly to the bottom of a Google Spreadsheet!
We will utilize Sheet.appendRow(), which we covered in Lesson 7.
Practical Code
function exportSapporoEmailsToSheet() {
// 1. Get the active sheet (see Lessons #2 and #3)
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// 2. Extract emails matching the query
var threads = GmailApp.search("is:unread subject:Sapporo City");
if (threads.length === 0) {
Logger.log("No unread emails to export.");
return;
}
// 3. Loop through retrieved threads, log them, and append them to the sheet
for (var i = 0; i < threads.length; i++) {
var thread = threads[i];
var subject = thread.getFirstUserMessageSubject(); // Subject line
var lastMessageDate = thread.getLastMessageDate(); // Date/time of the latest message
var permalink = thread.getPermalink(); // Direct URL to the email thread
// Create an array representing one row of data (see Lesson #7)
var rowData = [
lastMessageDate,
subject,
permalink,
"Unprocessed"
];
// Automatically append to the bottom of the spreadsheet! (see Lesson #7)
sheet.appendRow(rowData);
}
Logger.log("Appended " + threads.length + " email records to the spreadsheet!");
}
By attaching a time-driven trigger to run this script on a schedule, you can start every workday with an automatically compiled summary sheet of all high-priority incoming emails!
9. Summary & Next Steps
In this lesson, we explored how to search and extract target emails seamlessly from Gmail using GmailApp.search().
Key Takeaways
GmailApp.search("query")executes searches using the exact same syntax as the Gmail search bar.- The return value is an array of Threads (conversations), not individual messages.
- Combine operators like
is:unreadandsubject:with spaces to narrow down your results. - The default limit is 50 threads, but this can be customized via additional parameters.
In the next lesson (Lesson #34), we will look at how to reach inside these retrieved threads (binders) to extract individual email bodies and sender details using GmailThread.getMessages()!
Once you have that down, you’ll be able to read inquiry text or business trip details directly into your code and use them anywhere you want. Stay tuned!
