Gmail AutomationDifficulty: Intermediate⚡ Time-driven Trigger (Hourly)

Automatically Save Inbound Gmail Attachments to Google Drive

Monitors incoming emails matching a search query (such as invoices or vendor receipts), downloads attachments (PDF, PNG, JPG), and saves them into an organized Google Drive folder.

Required OAuth Scopes: https://www.googleapis.com/auth/gmail.modify • https://www.googleapis.com/auth/drive
Code.gs (Apps Script V8 Runtime)
function saveAttachmentsToDriveFolder() {
  const folderId = 'PASTE_YOUR_DRIVE_FOLDER_ID_HERE';
  const folder = DriveApp.getFolderById(folderId);
  const query = 'has:attachment label:receipts is:unread';
  const threads = GmailApp.search(query, 0, 15);
  
  threads.forEach(thread => {
    const messages = thread.getMessages();
    messages.forEach(msg => {
      if (msg.isUnread()) {
        const attachments = msg.getAttachments();
        attachments.forEach(att => {
          folder.createFile(att);
        });
        msg.markRead();
      }
    });
  });
}

Line-by-Line Code Explanation

Line 2-3: Connects to the destination Google Drive folder using its unique 33-character folder ID.
Line 4-5: Searches unread emails tagged with the label "receipts" that contain attachments.
Line 7-13: Loops through messages, extracts all file attachments, and saves each file blob to Drive.
Line 15: Marks message as read to avoid duplicate uploads in subsequent runs.

Step-by-Step Setup & Deployment

  1. Create a folder in Google Drive named "Receipts" and copy its ID from the browser URL.
  2. Replace PASTE_YOUR_DRIVE_FOLDER_ID_HERE in Line 2 with your copied folder ID.
  3. In Apps Script, save and click Run to test authentication.
  4. Create a time-driven trigger to run every hour.

Best Practices for Quota & Rate Limit Management

When deploying this automation in Google Workspace, adhere to these operational principles:

  • Batch Reads & Writes: Never execute getValue() or setValue() inside loops. Read ranges into memory in 1 call, process arrays in V8 memory, and commit changes with a single setValues() call.
  • Execution Timeouts: Apps Script terminates scripts exceeding 6 minutes. For multi-thousand row datasets, implement batch pagination with resume timestamps stored in PropertiesService.
  • OAuth Permissions: Scope your manifest (appsscript.json) narrowly to prevent security prompts from alarming external team members.

Frequently Asked Questions

Is Google Apps Script completely free to use?

Yes. Google Apps Script is built into all free Google accounts and Google Workspace editions. There are no server fees or subscription costs for running scripts within daily quotas.

Can I run this script on an automated schedule without keeping my computer on?

Yes. Time-driven triggers execute on Google's cloud infrastructure. Your script will run reliably even when your computer is closed or offline.

More Gmail Automation Snippets