# How to Use Google Apps Script to Automate Gmail Attachments to Google Drive
Managing email attachments manually can be a time-consuming process, especially if you receive numerous invoices, reports, or documents that need to be organized in Google Drive. Fortunately, Google Apps Script provides a powerful way to automate this workflow.
By writing a simple script, you can automatically extract attachments from specific emails in Gmail and save them directly to a designated folder in Google Drive. This article will guide you through the process of setting up this automation, explaining the necessary code and how to schedule it to run automatically.
## Understanding Google Apps Script
Google Apps Script is a cloud-based scripting platform based on JavaScript that allows you to integrate and automate tasks across Google Workspace applications, including Gmail, Google Drive, Google Sheets, and Google Docs.
Because it runs directly on Google’s servers, you do not need to install any software or maintain a local development environment. You simply write the code in your browser, and Google handles the execution.
## Prerequisites
Before beginning, ensure you have:
– A Google account (either a personal Gmail account or a Google Workspace account).
– A clear idea of which emails you want to target (e.g., emails with a specific label or from a specific sender).
– A destination folder created in your Google Drive where the attachments will be saved.
## Step 1: Create a Destination Folder in Google Drive
First, create the folder where you want your automated attachments to be stored.
1. Open Google Drive.
2. Click **New** > **New folder**.
3. Name the folder appropriately, for example, `Automated Attachments`.
4. Open the new folder and look at the URL in your browser’s address bar. The URL will look something like this: `https://drive.google.com/drive/folders/1A2B3C4D5E6F7G8H9I0J`.
5. Copy the long string of characters at the end of the URL (`1A2B3C4D5E6F7G8H9I0J`). This is your **Folder ID**. You will need this later in the script.
## Step 2: Create a Label in Gmail (Optional but Recommended)
To ensure the script only processes specific emails, it is highly recommended to use a Gmail label. You can set up a Gmail filter to automatically apply this label to incoming emails that match your criteria (e.g., emails with attachments from a specific vendor).
1. Open Gmail.
2. Scroll down on the left sidebar and click **Create new label**.
3. Name the label, for example, `ToProcess`.
4. Create a filter to automatically apply this label to the emails you want to process.
## Step 3: Open Google Apps Script
Now, access the Google Apps Script editor to write the automation code.
1. Go to [script.google.com](https://script.google.com).
2. Click on **New project**.
3. Click on **Untitled project** in the top left corner and rename it to something descriptive, like `Save Gmail Attachments to Drive`.
## Step 4: Write the Automation Script
Replace the default code in the editor (`function myFunction() {}`) with the following script.
“`javascript
function saveAttachmentsToDrive() {
// 1. Define the Google Drive Folder ID
// Replace ‘YOUR_FOLDER_ID’ with the ID you copied in Step 1
var folderId = ‘YOUR_FOLDER_ID’;
var folder = DriveApp.getFolderById(folderId);
// 2. Define the Gmail search query
// Example: Searches for unread emails with the label ‘ToProcess’ and an attachment
var searchQuery = ‘label:ToProcess has:attachment is:unread’;
// 3. Search for threads matching the query
var threads = GmailApp.search(searchQuery);
// 4. Iterate through the threads
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
// 5. Iterate through the messages in each thread
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
// Ensure we only process unread messages to avoid duplicates
if (message.isUnread()) {
var attachments = message.getAttachments();
// 6. Iterate through the attachments in each message
for (var k = 0; k < attachments.length; k++) {
var attachment = attachments[k];
// 7. Save the attachment to the specified Google Drive folder
folder.createFile(attachment);
}
// 8. Mark the message as read so it isn't processed again
message.markRead();
}
}
}
}
```
### Explaining the Code
- **`var folderId = 'YOUR_FOLDER_ID';`**: This is where you paste the Folder ID from Step 1.
- **`var searchQuery = 'label:ToProcess has:attachment is:unread';`**: This defines which emails the script will process. In this example, it looks for unread emails with the label `ToProcess` that contain attachments.
- **`GmailApp.search(searchQuery);`**: This retrieves the email threads matching your search query.
- **`folder.createFile(attachment);`**: This is the core action that creates a new file in your Google Drive folder using the attachment data.
- **`message.markRead();`**: This is a crucial step. By marking the email as read after processing, you ensure that the script does not save the same attachment again the next time it runs.
## Step 5: Test and Authorize the Script
Before scheduling the script, you must run it manually to authorize it.
1. Ensure you have inserted your actual Folder ID into the code.
2. In the Apps Script editor, click the **Run** button (the play icon) in the toolbar.
3. Since this is the first time running the script, Google will prompt you to authorize it. Click **Review permissions**.
4. Select your Google account.
5. You may see a warning stating "Google hasn’t verified this app." Click **Advanced**, and then click **Go to Save Gmail Attachments to Drive (unsafe)**.
6. Review the permissions the script is requesting (access to Gmail and Google Drive) and click **Allow**.
The script will now execute. Check your Google Drive folder to see if the attachments from any matching emails have been saved.
## Step 6: Schedule the Script to Run Automatically
To make this a true automation, you need to set up a trigger so the script runs on a schedule (e.g., every hour).
1. In the Apps Script editor, click on the **Triggers** icon (it looks like a clock) in the left sidebar.
2. Click the **+ Add Trigger** button in the bottom right corner.
3. Configure the trigger with the following settings:
- **Choose which function to run:** `saveAttachmentsToDrive`
- **Choose which deployment should run:** `Head`
- **Select event source:** `Time-driven`
- **Select type of time based trigger:** `Hour timer` (or your preferred frequency)
- **Select hour interval:** `Every hour`
4. Click **Save**.
## Conclusion
By utilizing Google Apps Script, you have successfully created an automated workflow that extracts attachments from specific Gmail messages and organizes them in Google Drive. This simple automation can significantly improve productivity by eliminating manual file handling and ensuring that important documents are consistently archived. As you become more familiar with Apps Script, you can expand this code to rename files, filter by file type, or notify you via Slack when a new file is saved.