In the previous tutorial (#33 on GmailApp.search()), we learned how to automatically search for target email conversations (threads) across Gmail using search queries! If you are looking to automate email workflows with Google Apps Script, mastering how to parse conversations is essential.
Many of you might have felt excited, thinking, “Now I can find any conversation whenever I want!”
However, what we retrieved in the last tutorial was only the “thread (GmailThread)” object—a container that bundles an entire conversation together.
In actual business automation, what you usually need is the specific information from each individual email within that thread, such as the sender of the first email, the body text of the second email, or the timestamp of the latest reply.
That brings us to today’s essential method: GmailThread.getMessages(), which retrieves all individual messages contained inside a thread at once!
Using our Sapporo office’s annual highlight—the “Autumn Company Trip to Hakodate” planning thread—as a sample, we will thoroughly explore the difference between threads and messages, how to process the retrieved array data, and common pitfalls beginners often face.
1. What Is the Difference Between GmailThread and GmailMessage?
When manipulating Gmail using Google Apps Script, the very first hurdle beginners encounter is the difference between a thread (GmailThread) and a message (GmailMessage).
If you leave this concept vague, you might run into errors like “My code seems fine, but I can’t extract the email body…”
Let’s clarify their relationship using a familiar analogy!
Think of a “Clear Folder” and the “Documents Inside”!
Gmail’s data structure is easy to understand if you compare it to an office folder and the sheets of paper kept inside it.
GmailThread= [The Clear Folder (Bundle)]- The entire group of emails exchanged under the same subject or topic. It manages the cover page (subject line) and the total number of interactions.
GmailMessage= [Each Document Inside the Folder]- Each individual email contained within the thread. It holds specific data such as the sender, body text, timestamp, and attachments.
[GmailThread (Clear Folder)]
├── Document 1 (GmailMessage): Proposal Draft (Subject, Body, Sender)
├── Document 2 (GmailMessage): Reply with Dates (Subject, Body, Sender)
└── Document 3 (GmailMessage): Final Confirmation (Subject, Body, Sender)
What you obtain with GmailApp.search() is simply a list of “clear folders” (GmailThread objects).
Just holding a clear folder does not let you read the detailed text inside. You need to open the folder and pull out the individual sheets of paper.
Opening that folder and taking out all the documents (messages) inside is exactly what GmailThread.getMessages() does!
2. Understanding the Syntax: What Is GmailThread.getMessages()?
Let’s look at the syntax and role of our key method today.
var messages = thread.getMessages();
Role and Characteristics of getMessages()
When called on a specific GmailThread object, this method retrieves all emails (GmailMessage objects) contained in that thread as a one-dimensional array (list).
Notice the Plural “s” at the End!
As we saw with Range.getValues() (#13) and Range.setValues() (#14), methods in GAS ending with a plural s return an array (a list of items).
Even if a thread contains only one single email message, getMessages() will still return an array with one element: [GmailMessage].
messages[0]➡ The first email in the threadmessages[1]➡ The second email in the threadmessages[messages.length - 1]➡ The latest (last) email in the thread
By specifying a zero-based index, you can precisely access whichever email you need.
3. STEP 1: Preparation – Create the “Hakodate Trip Planning” Test Thread
Let’s set up test data in your Gmail account so we can practice hands-on!
We will create a sample thread simulating planning a company trip to Hakodate by taking the Limited Express Hokuto from our Sapporo office.
Setup Steps (Creating Test Emails)
- Open your Gmail.
- Click “Compose” and send an email to yourself (your own email address) with the following details:
- To: Your email address
- Subject:
[Sapporo Office] Autumn Company Trip (Hakodate) Planning - Body:
This year's company trip is confirmed for Hakodate! We plan to travel on the JR Limited Express Hokuto. Let's make sure to grab some yakitori bento from Hasegawa Store for an evening snack!
- Open the received email, click “Reply”, and send a reply to yourself:
- Reply Body:
Sounds great! Chinese Chicken Burgers from Lucky Pierrot for dinner are also a must. I'll move forward with schedule coordination!
- Reply Body:
Now you have a single thread containing two messages (replies) ready to test!
4. STEP 2: Hands-On – Count Messages in a Thread Using getMessages()
With our test thread ready, let’s open the Google Apps Script editor and write some code.
First, we will search for our target thread using GmailApp.search(), retrieve its messages using getMessages(), and count how many emails it contains.
1. Enter the Code
Open your Google Sheets script editor or a standalone GAS editor, and paste the following code:
function countHakodateTripMessages() {
// 1. Search for the "Hakodate Trip" thread using search criteria (Review from Part 33!)
var searchQuery = 'subject:"[Sapporo Office] Autumn Company Trip (Hakodate) Planning"';
var threads = GmailApp.search(searchQuery);
// Guard clause in case no matching thread is found
if (threads.length === 0) {
Logger.log("No matching planning thread was found.");
return;
}
// 2. Extract the first thread (clear folder) found
var targetThread = threads[0];
// 3. [Main Feature!] Retrieve all messages (documents) within the thread at once
var messages = targetThread.getMessages();
// 4. Get the message count (array length) and log it
var messageCount = messages.length;
Logger.log("■ Retrieved Thread Subject: " + targetThread.getFirstUserMessageSubject());
Logger.log("■ Message count in this thread: " + messageCount + " email(s)");
}
2. Line-by-Line Code Explanation
var threads = GmailApp.search(searchQuery);- The search command learned in Part 33. It returns an array of threads (folders) matching the search query.
var targetThread = threads[0];- Retrieves the first thread object (index
0) from the array of search results and assigns it totargetThread.
- Retrieves the first thread object (index
var messages = targetThread.getMessages();- Today’s highlight! Calling
.getMessages()ontargetThreadstores all individual emails in the thread into themessagesarray.
- Today’s highlight! Calling
var messageCount = messages.length;- Counts how many emails are stored inside using the
.lengthproperty of the array.
- Counts how many emails are stored inside using the
3. Save and Execute
- Click the “Save” (floppy disk) icon at the top of the editor.
- Ensure the selected function is
countHakodateTripMessages, then click “Run”. - If this is your first run, an authorization dialog will appear asking for Google permissions. Review and approve access.
4. Check the Execution Log
If you see an output like this in the execution log below, your script ran successfully!
Info ■ Retrieved Thread Subject: [Sapporo Office] Autumn Company Trip (Hakodate) Planning
Info ■ Message count in this thread: 2 email(s)
GAS correctly detected both messages inside the single conversation thread!
5. STEP 3: Advanced Loop – Iterate Through All Emails Using a for Loop
Because getMessages() returns an array, it works seamlessly with for loops or forEach(), which we covered in earlier lessons (#11 and #13).
Let’s run a script that loops through the thread from the first message to the latest reply and logs the sender, date, and preview text in sequential order.
1. Enter the Code
function printAllMessagesInThread() {
var searchQuery = 'subject:"[Sapporo Office] Autumn Company Trip (Hakodate) Planning"';
var threads = GmailApp.search(searchQuery);
if (threads.length === 0) return;
// Get the array of messages from the first thread
var messages = threads[0].getMessages();
Logger.log("=== Hakodate Trip Planning Thread History ===");
// Use a for loop to log details for each email in order
for (var i = 0; i < messages.length; i++) {
var msg = messages[i]; // GmailMessage object at index i
// Previewing methods we will study closely in Part 35!
var sender = msg.getFrom(); // Sender
var date = msg.getDate(); // Sent date and time
var snippet = msg.getPlainBody(); // Plain text email body
Logger.log("[ Email #" + (i + 1) + " ]");
Logger.log("From: " + sender);
Logger.log("Date: " + date);
Logger.log("Body Snippet: " + snippet.substring(0, 40) + "..."); // Show only first 40 characters
Logger.log("--------------------------------------------------");
}
}
2. Check the Output
Info === Hakodate Trip Planning Thread History ===
Info [ Email #1 ]
Info From: Your Name <your_email@example.com>
Info Date: Wed Sep 23 2026 10:00:00 GMT+0900 (Japan Standard Time)
Info Body Snippet: This year's company trip is confirmed for...
Info --------------------------------------------------
Info [ Email #2 ]
Info From: Your Name <your_email@example.com>
Info Date: Wed Sep 23 2026 10:05:00 GMT+0900 (Japan Standard Time)
Info Body Snippet: Sounds great! Chinese Chicken Burgers from...
Info --------------------------------------------------
Each past exchange stored in the thread has been retrieved and separated cleanly in chronological order!
Combining array iterations like this makes it straightforward to build automation systems that export complete email histories into Google Sheets for meeting minutes or audit logs.
6. Four Common Beginner Traps and How to Fix Them
Here are four common pitfalls people face when using GmailThread.getMessages(), along with their solutions.
Trap 1: Calling GmailApp.getMessages() Resulting in a TypeError
A very frequent mistake is writing code like this:
// Incorrect: Calling getMessages directly on GmailApp
var messages = GmailApp.getMessages();
// ➡ TypeError: GmailApp.getMessages is not a function
Cause & Solution
getMessages() is not a method belonging to top-level GmailApp (the overall manager); it belongs to an individual GmailThread object (the clear folder).
Always remember the rule: First obtain a thread using GmailApp.search() or GmailApp.getThreadById(), then call .getMessages() on that thread variable!
Trap 2: Getting Confused by Nested Arrays (threads and messages)
Operating Gmail in GAS can become confusing because arrays appear inside arrays:
GmailApp.search()➡ Returns an array of threads:[Thread, Thread, Thread]thread.getMessages()➡ Returns an array of messages:[Message, Message]
Coding Tip to Avoid Confusion
The best defense is naming your variables carefully. Pay close attention to singular versus plural terms: use threads for the thread array, targetThread for an individual thread, messages for the message array, and firstMsg for a specific message!
var threads = GmailApp.search(...); // Plural: array of threads
var thread = threads[0]; // Singular: one thread
var messages = thread.getMessages(); // Plural: array of messages
var firstMsg = messages[0]; // Singular: one message
Trap 3: Forgetting [0] When There Is Only One Email
Thinking “there’s only one email in this thread anyway,” some try to call message methods without array brackets, causing runtime errors.
// Incorrect: messages is an "array", so you cannot get the body directly!
var body = messages.getPlainBody(); // Throws an error!
// Correct: Even with one message, access index [0] to get the Message object
var body = messages[0].getPlainBody();
Keep in mind that the return value of getMessages() is always an array.
Trap 4: Typos Between getMessages() (Plural) and getMessage() (Singular)
In Google Apps Script, the plural method getMessages() exists, but there is no singular getMessage() method on a thread.
When typing manually without autocomplete, forgetting the trailing s frequently triggers a TypeError.
When typing in the script editor, type getMess... and select the suggestion with the Tab key to prevent typos!
7. Summary and What’s Next
Today, we covered GmailThread.getMessages(), the key method for extracting all emails from an email thread in bulk.
Key Takeaways from Today
GmailThreadis the “folder (bundle),” whileGmailMessageis the “document inside (individual email)”thread.getMessages()returns all emails inside a thread as a 1D array of[GmailMessage]- Even if there is only one email, it is returned in an array, so specify an index like
messages[0] - Combining this with
forloops orforEach()lets you process an entire conversation history automatically
Now that you know how to extract individual messages from a thread, the pieces of Gmail automation are truly coming together!
Next, how do we pull specific details like the subject, sender email address, and message body out of each GmailMessage object?
In Part 35, we will dive deep into GmailMessage.getSubject() and getBody()!
We will build a practical script that parses confirmation emails from an online winter clothing order and writes clean records automatically into Google Sheets. Stay tuned!
