Skip to content

Instantly share code, notes, and snippets.

@nosmall
Created September 17, 2025 06:49
Show Gist options
  • Save nosmall/36d93ea89fdef8709597e2365780a6a8 to your computer and use it in GitHub Desktop.
Save nosmall/36d93ea89fdef8709597e2365780a6a8 to your computer and use it in GitHub Desktop.
Saving PDF Attachments from Gmail to Google Drive via Google Apps Script

Saving PDF Attachments from Gmail to Google Drive

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.


Key Features

  • 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.

How It Works

The script follows these steps:

  1. Load Configuration: It reads two key variables from the top of the code: dotazProVyhledavani and nazevSlozkyNaDisku.
  2. Prepare Drive Folder: It verifies if a folder with the specified name exists in your Google Drive. If not, it creates it.
  3. Search for Emails: Using the GmailApp service, it performs a search in your inbox according to the specified query.
  4. Process Threads: It goes through the found email threads one by one.
  5. Iterate Through Attachments: For each message within a thread, it checks all of its attachments.
  6. 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.
  7. Completion: After processing all threads, it displays a pop-up message indicating that the process is complete.

Installation and Usage

Step 1: Create the Script

  1. Open your Google Drive.
  2. Click + New -> More -> Google Apps Script. This will open the script editor in a new tab.
  3. Paste the complete code into the editor.

Step 2: Configuration

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";
/**
* Tento skript prohledá Gmail podle zadaných kritérií (včetně časového omezení),
* najde všechny přílohy, zkontroluje, zda jsou to PDF, a uloží je do určené složky.
* V průběhu zobrazuje v logu jednoduchý číselný odpočet.
*/
function ulozPrilohyNaDisk() {
// --- ZDE UPRAVTE HODNOTY PODLE SEBE ---
// 1. Zadejte, jaké e-maily má skript prohledávat.
var dotazProVyhledavani = 'from:Pražská energetika has:attachment filename:pdf "Faktura za dobíjení v síti PREpoint" after:2024/01/01';
// 2. Zadejte název složky na Google Disku, kam se mají přílohy uložit.
var nazevSlozkyNaDisku = "Faktury PREPoint 2025";
// --- OD TÉTO CHVÍLE NENÍ TŘEBA NIC MĚNIT ---
var slozka;
var slozky = DriveApp.getFoldersByName(nazevSlozkyNaDisku);
// Zjistí, zda složka již existuje. Pokud ne, vytvoří ji.
if (slozky.hasNext()) {
slozka = slozky.next();
Logger.log("Složka '" + nazevSlozkyNaDisku + "' nalezena.");
} else {
slozka = DriveApp.createFolder(nazevSlozkyNaDisku);
Logger.log("Složka '" + nazevSlozkyNaDisku + "' byla vytvořena.");
}
// Prohledá Gmail podle zadaného dotazu
var thready = GmailApp.search(dotazProVyhledavani, 0, 500); // Prohledá až 500 vláken
Logger.log("Nalezeno " + thready.length + " e-mailových vláken ke zpracování.");
if (thready.length === 0) {
Logger.log("Nebyly nalezeny žádné nové e-maily odpovídající dotazu. Skript končí.");
Browser.msgBox("Informace", "Nebyly nalezeny žádné nové e-maily s přílohami.", Browser.Buttons.OK);
return;
}
// Projde všechna nalezená e-mailová vlákna
for (var i = 0; i < thready.length; i++) {
var zpravy = thready[i].getMessages();
// Projde všechny zprávy v jednom vláknu
for (var j = 0; j < zpravy.length; j++) {
var prilohy = zpravy[j].getAttachments();
// Projde všechny přílohy v jedné zprávě
for (var k = 0; k < prilohy.length; k++) {
var priloha = prilohy[k];
// ===== ZDE JE PŘIDANÁ KONTROLA =====
// Zpracuje přílohu, pouze pokud její název končí na ".pdf" (bez ohledu na velikost písmen)
if (priloha.getName().toLowerCase().endsWith('.pdf')) {
// Zabrání ukládání duplicitních souborů
var existujiciSoubory = slozka.getFilesByName(priloha.getName());
if (!existujiciSoubory.hasNext()) {
// Uloží soubor na Disk
var soubor = slozka.createFile(priloha);
// Zápis do logu s jednoduchým odpočtem
Logger.log("[ " + (thready.length - i) + " ] Uložen soubor: " + soubor.getName());
} else {
// Zápis do logu s jednoduchým odpočtem
Logger.log("[ " + (thready.length - i) + " ] Soubor '" + priloha.getName() + "' již ve složce existuje, přeskakuji.");
}
} // ===== KONEC PŘIDANÉ KONTROLY =====
}
}
}
Logger.log("🎉 Hotovo! Zpracování dokončeno.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment