This Google Apps Script automates the process of downloading PDF attachments from specific emails in your Gmail inbox and saving them to a designated folder in Google Drive.
The script is ideal for regularly backing up invoices, statements, or other important documents you receive via email.
- Targeted Search: Searches Gmail based on a user-defined query (sender, subject, date range, etc.).
- Attachment Filtering: Processes and saves only files with the
.pdf
extension from the found emails. It ignores other attachments (like images in email signatures). - Automatic Organization: Creates the specified folder in Google Drive if it does not already exist.
- Duplicate Prevention: Before saving, it checks if a file with the same name already exists in the target folder, preventing duplicate downloads.
- Clear Output: Logs the processing status, including a numerical countdown of remaining emails, during execution.
The script follows these steps:
- Load Configuration: It reads two key variables from the top of the code:
dotazProVyhledavani
andnazevSlozkyNaDisku
. - Prepare Drive Folder: It verifies if a folder with the specified name exists in your Google Drive. If not, it creates it.
- Search for Emails: Using the
GmailApp
service, it performs a search in your inbox according to the specified query. - Process Threads: It goes through the found email threads one by one.
- Iterate Through Attachments: For each message within a thread, it checks all of its attachments.
- Filter and Save:
- For each attachment, it verifies that its name ends with
.pdf
. - If it is a PDF, it checks if a file with the same name already exists in the target Drive folder.
- If it doesn't exist, the script saves it and logs the action.
- If it already exists, the script skips it and logs the action.
- For each attachment, it verifies that its name ends with
- Completion: After processing all threads, it displays a pop-up message indicating that the process is complete.
- Open your Google Drive.
- Click + New -> More -> Google Apps Script. This will open the script editor in a new tab.
- Paste the complete code into the editor.
You need to edit two variables at the top of the code to fit your needs.
// --- EDIT THE VALUES BELOW ---
// 1. Specify the search query for the emails.
var dotazProVyhledavani = 'from:Pražská energetika has:attachment filename:pdf "Faktura za dobíjení v síti PREpoint" after:2024/01/01';
// 2. Specify the name of the Google Drive folder for saving attachments.
var nazevSlozkyNaDisku = "Faktury PREPoint 2025";