Do you find yourself repeating the same tedious routine every time an invoice or travel receipt arrives via email: opening each message, downloading the PDF attachment to your PC, and manually moving it to a specific folder?
As your incoming email volume grows, downloading every attachment by hand becomes exhausting. Worse, manual work makes it all too easy to make mistakes like forgetting to save an important invoice or saving duplicates.
In this tutorial, we will explore GmailMessage.getAttachments(), the essential Google Apps Script method that lets you extract email attachments programmatically in bulk from Gmail!
By combining this method with the search and retrieval techniques we covered in previous guides, you can fully automate the extraction of PDFs, images, and other attachments directly from target emails.
Using a realistic office scenario—handling monthly snow removal invoice PDFs sent to our Sapporo office—I will walk you through sample code, practical workplace applications, and common beginner pitfalls in a clear, step-by-step guide!
1. What Is GmailMessage.getAttachments()?
GmailMessage.getAttachments() is a Google Apps Script method used to retrieve all attachments associated with a specific email message as an array.
Basic Syntax
var attachments = message.getAttachments();
message: The specific email (aGmailMessageobject) you want to inspect..getAttachments(): The method that says, “Collect and return all attached files from this message!”
Think of It as an Envelope and Enclosures!
Visualizing an email as a postal letter makes its structural hierarchy much easier to grasp:
| Email Component | Letter Metaphor | GAS Method |
| Subject | Title on the outside envelope | message.getSubject() |
| Body | The written letter inside | message.getBody() |
| Attachment | Enclosed photos or documents | message.getAttachments() ★ Featured Today! |
Just as you might pull out an enclosed receipt without reading the full letter word for word, getAttachments() quickly grabs only the enclosed files for you!
2. Essential Concepts: What Are “Blobs” and “MIME Types”?
When handling attachments in Google Apps Script, you will inevitably encounter two key technical terms. Let’s master them with simple analogies!
1. Blob Object = A Protective Capsule That Carries Raw Data
[ Image or PDF ] ➔ [ 🔒 Blob Capsule ] ➔ [ Save to Google Drive ]
- What is a Blob?
- It stands for Binary Large Object, but you do not need to memorize the name!
- Think of it as a “protective shipping container (capsule)” designed to transport raw binary data (images, PDFs, text files) without corrupting it.
- Why is a Blob necessary?
- In code, plain text (like “Hello world”) and binary files (like images or PDFs) are handled very differently under the hood.
- To prevent binary files from corrupting when loaded into memory, GAS wraps file data into an intact, dedicated container called a Blob so it can be moved or saved safely.
💡 Key Takeaway
Every single file returned by
getAttachments()is provided as a Blob object!
2. MIME Type = The Universal Identification Label for File Formats
[ 🔒 Blob Capsule ] 🏷️ Label: application/pdf ➔ "Aha, this is a PDF document!"
- What is a MIME type?
- It is a standardized identifier that programs and web services use to tell each other what kind of data a file contains.
- How is it different from a file extension?
- Extensions like
.pdfor.pngare human-friendly text strings added to the end of a filename. - A MIME type is the official system-level classification code.
- Extensions like
Common MIME types in GAS:
| File Type | Standard Extension | MIME Type (Returned in GAS) |
| PDF Document | .pdf |
application/pdf |
| PNG Image | .png |
image/png |
| JPEG Image | .jpg / .jpeg |
image/jpeg |
| CSV File | .csv |
text/csv |
| ZIP Archive | .zip |
application/zip |
3. The 4-Tier Hierarchy of Gmail in Google Apps Script
To access attachments in Gmail with GAS, you must traverse down through these four hierarchical levels in order:
Level 1: GmailApp.search("search query")
└─ Find matching "threads" (conversations)
↓
Level 2: thread.getMessages()
└─ Extract the array of individual "messages" within the thread
↓
Level 3: targetMessage (a specific message)
└─ Select the exact email you want to process
↓
Level 4: message.getAttachments() ★ Featured Today!
└─ Retrieve all "attachments (Blobs)" from that specific message!
You cannot jump straight to attachments from a search query. Always remember the path: Thread ➔ Message ➔ Attachment!
4. Step 1: Prepare a Test Email
Before running code, send a quick test email to yourself so that we have an attachment to fetch.
Setup Steps
- Open your Gmail account.
- Compose and send an email to yourself with the following details:
- To: Your own Gmail address
- Subject:
[Invoice] Jan 2026 Sapporo Office Snow Removal Expense - Body:
Hello team, please find attached the snow removal invoice PDF for this month. - Attachment: Attach any sample PDF file from your computer (an image or text file works too).
- Confirm that the message has arrived in your Gmail inbox.
5. Step 2: Extract and Log Attachment Details with GAS
Now let’s write a script to detect the email and inspect its attachment information in the execution log!
1. Open the Script Editor
Open a new Google Spreadsheet and click Extensions > Apps Script from the top menu.
2. Paste the Script
Replace the default boilerplate code with the following snippet:
function getSnowRemovalInvoiceAttachment() {
// 1. Search for threads with our target subject keywords
var threads = GmailApp.search("subject:Sapporo Office Snow Removal Expense");
// Safety check in case no matching emails exist
if (threads.length === 0) {
Logger.log("No matching emails found.");
return;
}
// 2. Get the first message from the most recent thread
var messages = threads[0].getMessages();
var targetMessage = messages[0];
// 3. Extract all attachments from the message (our main method)
var attachments = targetMessage.getAttachments();
// 4. Check whether any attachments are present
if (attachments.length === 0) {
Logger.log("No attachments found in this email.");
return;
}
// 5. Inspect each attachment Blob and log its metadata
for (var i = 0; i < attachments.length; i++) {
var file = attachments[i]; // Each item is a Blob object
// Read properties (name, size, MIME type) from the Blob
var fileName = file.getName();
var fileSize = file.getSize(); // Size in bytes
var fileType = file.getContentType(); // MIME type
Logger.log("Found an attachment!");
Logger.log("- File Name: " + fileName);
Logger.log("- Size: " + fileSize + " bytes");
Logger.log("- Format (MIME Type): " + fileType);
}
}
3. Code Breakdown
targetMessage.getAttachments()- Returns all attachments as an array. Even if an email has only one file, it returns an array containing that single element.
var file = attachments[i];- Pulls out each individual file container (a Blob) from the array.
file.getName()- Retrieves the original filename written on the container label (e.g.,
snow_removal_invoice.pdf).
- Retrieves the original filename written on the container label (e.g.,
file.getSize()- Returns the file size in bytes.
file.getContentType()- Returns the file’s MIME type (such as
application/pdf).
- Returns the file’s MIME type (such as
4. Run the Script
- Click the Save (disk icon) at the top of the editor.
- Click Run. (If this is your first time running it, approve the necessary Google account permissions).
5. Check Execution Output
If successful, you will see output similar to this in the Execution log window:
Info Found an attachment!
Info - File Name: 202601_Snow_Removal_Invoice.pdf
Info - Size: 145820 bytes
Info - Format (MIME Type): application/pdf
Without opening Gmail manually, Google Apps Script identified the target email and extracted the attachment details automatically!
6. Step 3: 3 Practical Workplace Automation Patterns
Here are three advanced patterns ready for real-world automation tasks.
Pattern 1: Filter Specific Formats (Target Only PDF Files)
Emails often contain unwanted attachments like email signature logos alongside invoices. Use the MIME type check to isolate only PDF documents!
function filterPdfAttachments() {
var threads = GmailApp.search("subject:Sapporo Office Snow Removal Expense");
if (threads.length === 0) return;
var messages = threads[0].getMessages();
var attachments = messages[0].getAttachments();
for (var i = 0; i < attachments.length; i++) {
var file = attachments[i];
// Process only if the MIME type matches application/pdf
if (file.getContentType() === "application/pdf") {
Logger.log("[PDF Detected] Ready for saving: " + file.getName());
// Insert logic to save file to Google Drive here
} else {
Logger.log("[Skipped] Non-PDF attachment: " + file.getName());
}
}
}
Pattern 2: Process Multiple Files in a Single Email
Even if an email includes an estimate, a delivery slip, and an invoice together, a simple for loop iterates over every single attachment reliably.
for (var i = 0; i < attachments.length; i++) {
// Using (i + 1) to produce friendly numbering (File 1, File 2, etc.)
Logger.log("File #" + (i + 1) + ": " + attachments[i].getName());
}
Pattern 3: Log Incoming Attachments Directly into Google Sheets
Pairing this with Sheet.appendRow() lets you create an automated audit log tracking when each attachment arrived, which email it came from, and file size!
function logAttachmentToSheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var threads = GmailApp.search("subject:Sapporo Office Snow Removal Expense");
if (threads.length === 0) return;
var message = threads[0].getMessages()[0];
var attachments = message.getAttachments();
for (var i = 0; i < attachments.length; i++) {
var file = attachments[i];
// Append timestamp, email subject, filename, and byte size
sheet.appendRow([
message.getDate(),
message.getSubject(),
file.getName(),
file.getSize()
]);
}
Logger.log("Logged attachment records to Google Sheets successfully!");
}
7. Common Traps and How to Fix Them
When errors pop up, check these four frequent troubleshooting points:
❌ Trap 1: Calling getAttachments() Directly on a GmailThread
- Incorrect Code:
var attachments = threads[0].getAttachments(); // Throws TypeError! - Reason:
getAttachments()is a method belonging to a single message (GmailMessage), not a thread (GmailThread). - Fix: Always drill down into the message first, such as
threads[0].getMessages()[0].getAttachments().
❌ Trap 2: Running the Script on an Email with Zero Attachments
- Reason: Accessing
attachments[0].getName()when the array is empty throwsCannot read properties of undefined. - Fix: Add a defensive guard clause checking array length before accessing elements:
if (attachments.length === 0) { Logger.log("No attachments found."); return; }
❌ Trap 3: Passing attachments[0] Directly to Logger.log()
- Reason: An item inside
attachmentsis a binary Blob object. Printing it directly will simply outputBlobrather than text contents or file info. - Fix: Call
.getName()to read its filename, or.getSize()to read its byte size.
❌ Trap 4: Picking Up Embedded Signature Logos Accidentally
- Reason: By default, inline images (like company logos inside email signature footers) are treated as regular attachments by Gmail.
- Fix: Pass the option
includeInlineImages: falseto ignore embedded graphics and keep only true file attachments:var attachments = message.getAttachments({ includeInlineImages: false });
8. Summary & What’s Next
In this tutorial, we covered how to locate and extract email attachments automatically using GmailMessage.getAttachments() in Google Apps Script.
Key Takeaways Recap
getAttachments()returns all attached files from an individual email message as an array.- Each attachment is returned as a
Blob, the standard data container in GAS. - Using
getContentType()lets you identify MIME types likeapplication/pdfto filter and target exact file formats.
With this workflow, you can now automate data pipelines not just for email headers or body text, but for enclosed files as well!
In our next tutorial, we will learn how to automatically label and organize processed messages using GmailThread.addLabel().
We will set up GAS to attach labels like “Processed Invoices” automatically to keep your Gmail inbox perfectly organized. Stay tuned!
