In our previous articles (Part 33 and Part 34), we explored how to search for email conversations with GmailApp.search() and retrieve individual messages from those threads using GmailThread.getMessages().
Once you have pinpointed an individual message (GmailMessage) from a thread, the logical next step is reading its content—specifically the subject and body—programmatically to streamline business operations and logging!
Here are a few common real-world scenarios:
- “Automatically extract the subject and total price from winter apparel order confirmation emails.”
- “Parse inquiry emails to grab contact info and order IDs, then append them to a Google Sheet.”
- “Scan incoming daily system alerts for specific warning keywords in the subject and forward them to Slack.”
These workflow automations are absolute staples whether you are streamlining office tasks or personal projects.
In this tutorial, we will take a deep dive into GmailMessage.getSubject() for getting email subjects, along with GmailMessage.getBody() and GmailMessage.getPlainBody() for retrieving email content in Google Apps Script (GAS)!
Using a sample order confirmation email for winter gear—essential for surviving a freezing Sapporo winter—we will walk step-by-step through core fundamentals, practical data extraction techniques, and common beginner pitfalls!
1. What Are GmailMessage.getSubject() and getBody()?
Both methods covered in this guide are called directly on an individual email message object (GmailMessage).
Reviewing the Class Hierarchy
When manipulating Gmail via GAS, think of the objects as nested containers:
- [Top-level] GmailApp (The root manager for your Gmail account)
- [Bundle] GmailThread (A conversation thread containing multiple related emails)
- [Single Letter] GmailMessage (An individual message) ★ Our focus today!
getSubject()➡ Retrieves the email subject (title)getBody()/getPlainBody()➡ Retrieves the message body
- [Single Letter] GmailMessage (An individual message) ★ Our focus today!
- [Bundle] GmailThread (A conversation thread containing multiple related emails)
Think of It as an Envelope and a Letter
When holding a single letter (GmailMessage):
getSubject()is like reading the header or title written at the top of the stationery.getBody()is like reading the written contents of the letter itself.
2. Key Differences: When to Use getBody() vs. getPlainBody()
There are two distinct methods for reading an email’s body: getBody() and getPlainBody(). While they sound almost identical, the format of data they return is completely different.
| Method | Returned Content | Characteristics & Best Use Cases |
GmailMessage.getSubject() |
Subject line (String) | Returns the title/subject line of the message. |
GmailMessage.getBody() |
HTML format body | Returns the email content including HTML tags like <div> and <b>, styling, and embedded images.Use this when forwarding or re-rendering formatted emails. |
GmailMessage.getPlainBody() |
Plain text format body | Returns stripped-down body text without styling or HTML markup. ★ 100% recommended for data extraction, parsing, and writing to Google Sheets! |
Why Should You Use getPlainBody() for Automation?
Most modern e-commerce notifications and corporate newsletters arrive as rich HTML emails.
If you call getBody() on these messages, you receive text cluttered with markup, such as <html><body><p>Thank you for your order</p>....
When searching for specific phrases like an “Order Number” or “Total Amount”, stick to getPlainBody() to work strictly with clean, unformatted text!
3. STEP 1: Setup a Sample Order Confirmation Email
Before running code, let’s create a test email in your inbox.
Instructions
- Open your Gmail account.
- Send a test email to yourself (or from a secondary account) with the following content:
- To: Your Gmail address
- Subject:
[North Gear Shop] Thank you for your order (Order ID: 100234) - Body: Plaintext
Thank you for shopping with Dosanko Outdoor Store.
We have received your order details below.[Order Details]
- Item: Heavy-Duty Thermal Down Coat
- Size: L
- Quantity: 1
- Total Amount: 29,800 JPYYour items will be shipped from the Sapporo Delivery Center as soon as they are prepared.
- Once you receive this email in your inbox, you are ready to script!
4. STEP 2: [Hands-On] Extract and Log Email Subject & Body
Open the Apps Script editor from Google Sheets and let’s write a script to fetch the subject line and plain text body.
1. Enter the Code
From the Google Sheets menu, navigate to Extensions > Apps Script, clear any starter template code, and paste the following snippet:
function getMailSubjectAndBody() {
// 1. Search for threads containing "North Gear Shop" in the subject/body
var threads = GmailApp.search("North Gear Shop");
// Safety check in case no matching emails are found
if (threads.length === 0) {
Logger.log("No matching emails were found.");
return;
}
// 2. Grab the first (most recent) thread from the search results
var latestThread = threads[0];
// 3. Retrieve all messages inside the thread as an array
var messages = latestThread.getMessages();
// 4. Target the latest message (the last element in the array)
var latestMessage = messages[messages.length - 1];
// 5. Retrieve the Subject and PlainBody text
var subject = latestMessage.getSubject();
var plainBody = latestMessage.getPlainBody();
// 6. Print the results to the Execution Log
Logger.log("=== Email Subject ===");
Logger.log(subject);
Logger.log("=== Email Body (Plain Text) ===");
Logger.log(plainBody);
}
2. Code Breakdown
var threads = GmailApp.search("North Gear Shop");- Uses the search query method we learned in Part 33 to return an array of matching
GmailThreadobjects.
- Uses the search query method we learned in Part 33 to return an array of matching
var messages = latestThread.getMessages();- Retrieves each individual email message (
GmailMessage) contained within the conversation thread as an array.
- Retrieves each individual email message (
var latestMessage = messages[messages.length - 1];- Pinpoints the most recent message received in that thread by selecting the final index.
var subject = latestMessage.getSubject();- Our first star method! Pulls the subject line as a string.
var plainBody = latestMessage.getPlainBody();- Our second star method! Extracts pure body text stripped of HTML tags.
3. Save and Run
- Click Save (the disk icon) in the top toolbar.
- Ensure
getMailSubjectAndBodyis selected as the active function, then click Run. - Check the Execution Log panel at the bottom of the editor.
[Sample Execution Log]
Info === Email Subject ===
Info [North Gear Shop] Thank you for your order (Order ID: 100234)
Info === Email Body (Plain Text) ===
Info Thank you for shopping with Dosanko Outdoor Store.
We have received your order details below.
[Order Details]
- Item: Heavy-Duty Thermal Down Coat
- Size: L
- Quantity: 1
- Total Amount: 29,800 JPY
Your items will be shipped from the Sapporo Delivery Center as soon as they are prepared.
Apps Script cleanly extracted both the subject line and body text from your inbox!
5. STEP 3: Real-World Automation! Parse Data and Append to Google Sheets
Once you have the subject and body as plain strings, the real power comes from parsing targeted information—like order IDs and prices—and logging them directly into Google Sheets.
Here, we will combine regular expressions with Sheet.appendRow() (covered back in Part 7) to build a practical email data logger.
Practical Code: Extract Order ID & Total Price into Sheets
function parseOrderMailAndAppend() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// 1. Search for target emails and fetch the latest message
var threads = GmailApp.search("North Gear Shop");
if (threads.length === 0) return;
var messages = threads[0].getMessages();
var message = messages[messages.length - 1];
var subject = message.getSubject();
var body = message.getPlainBody();
// 2. Extract Order ID from the subject line using RegExp
// Captures digits following "Order ID: "
var orderNoMatch = subject.match(/Order ID:\s*(\d+)/);
var orderNo = orderNoMatch ? orderNoMatch[1] : "Unknown";
// 3. Extract the total price from the body
// Captures numeric/comma string preceding "JPY"
var priceMatch = body.match(/Total Amount:\s*([0-9,]+)\s*JPY/);
var price = priceMatch ? priceMatch[1] : "Unknown";
// 4. Get email timestamp
var date = message.getDate();
// 5. Append row to the bottom of the active sheet (Part 7: appendRow)
sheet.appendRow([date, orderNo, subject, price]);
Logger.log("Data appended to spreadsheet! Order ID: " + orderNo + " / Price: " + price);
}
Spreadsheet Output Result
| Date Received | Order ID | Subject | Total Amount |
| 2026/09/23 10:15 | 100234 | [North Gear Shop] Thank you for your order… | 29,800 |
By parsing strings retrieved via getSubject() and getPlainBody() using regular expressions or split(), you can eliminate manual copy-pasting entirely!
6. 4 Common Beginner Traps and How to Fix Them
When reading email contents with GAS, beginners frequently run into the same few obstacles. Keep these troubleshooting tips handy!
Trap 1: Calling getSubject() on a GmailThread
// Incorrect: Calling on a Thread instead of a Message
var threads = GmailApp.search("North Gear Shop");
var subject = threads[0].getSubject();
// Error: TypeError: threads[0].getSubject is not a function
[Cause & Solution]
Methods like getSubject() and getBody() belong to the GmailMessage object.
Because threads[0] is a GmailThread, calling these methods triggers a type error.
Always extract the message list first with thread.getMessages(), then call messages[0].getSubject() on the specific GmailMessage instance!
Trap 2: Using getBody() and Getting Cluttered HTML Markup
Using getBody() returns raw HTML tags, like this:
<div dir="ltr">Thank you for shopping with Dosanko Outdoor Store...<br><b>Total Amount: 29,800 JPY</b></div>
[Solution]
Whenever you plan to search text, parse strings, or append readable content into Google Sheets, always use getPlainBody() instead.
Trap 3: Accidentally Grabbing the Oldest Message in a Multi-Email Thread
If a thread contains multiple back-and-forth replies, accessing messages[0] fetches the first (oldest) email originally sent in that thread.
[Solution]
To guarantee you always target the latest reply, look up the last array index using messages.length - 1:
var messages = thread.getMessages();
// Target the newest message at the end of the thread
var latestMessage = messages[messages.length - 1];
Trap 4: “Cannot read properties of undefined” When No Emails Match
If no emails match your search query, GmailApp.search() returns an empty array ([]).
Attempting to execute threads[0].getMessages() on an empty array immediately crashes the script because threads[0] is undefined.
[Solution]
Add an early-return guard condition checking the array length before processing threads:
var threads = GmailApp.search("your search query");
if (threads.length === 0) {
Logger.log("No matching emails found.");
return; // Safely exit the function
}
7. Summary & What’s Next
In this installment, we broke down how to programmatically extract email subject lines and body copy using GmailMessage.getSubject(), GmailMessage.getBody(), and GmailMessage.getPlainBody().
Key Takeaways
getSubject()retrieves the email title/subject string.getBody()returns raw HTML content, whereasgetPlainBody()yields clean, unformatted plain text.getPlainBody()is heavily recommended for data extraction and logging to Google Sheets!- Always invoke these methods on a
GmailMessageinstance, not aGmailThread. - Combining plain body text with string methods (like regex or
split()) unlocks powerful automated spreadsheet data entry!
Being able to parse subjects and email contents unlocks massive potential for your Google Workspace workflows!
Now that we can read messages, you might be asking: “What about email attachments like PDF invoices or receipts? Can we automatically download and save those?”
In Part 36, we will dive into GmailMessage.getAttachments() to automatically handle files attached to incoming emails!
We will build a practical script that extracts attached snow-removal invoice PDFs and saves them directly to Google Drive. Stay tuned!
