Download emails from GMAIL in bulk

Here is a sample Google Apps Script to download specific Gmail emails as PDF files and save them to Google Drive. We’ll be using Google Apps Script’s Gmail and Drive services.

Below is the script. This script will only handle the most recent email thread specified by the search query. You can modify the code to manage more threads.

// Import necessary Google Services
var GmailApp = GmailApp;
var DriveApp = DriveApp;

// Function to save emails
function saveEmails() {
  var query = "from:[email protected] subject:'Important Email'"; // Customize your search here

  // Search for the thread
  var threads = GmailApp.search(query, 0, 1); // Get only the most recent thread matching the query

  // Check if any threads were found
  if (threads.length > 0) {
    var thread = threads[0];

    // Create a folder in Drive to store the emails
    var folder = DriveApp.createFolder('Emails from ' + thread.getFirstMessageSubject());

    // Get all messages in the thread
    var messages = thread.getMessages();

    for (var i = 0; i < messages.length; i++) {
      var message = messages[i];
      var subject = message.getSubject();
      var body = message.getBody();
      var date = message.getDate();

      // Create a blob (binary data) of the PDF contents
      var blob = Utilities.newBlob(body, 'text/html', subject + '.pdf');

      // Save the blob as a file in the Drive folder
      folder.createFile(blob);
    }
  } else {
    Logger.log('No threads found with the specified query.');
  }
}

To execute this script, go to the Google Apps Script editor (https://script.google.com), click on File -> New -> Script File and paste the above code. Modify the query in the saveEmails() function to match your needs. Then, save and run the script.

Please note that you might have to allow this script to access your Gmail and Drive due to privacy and security considerations. It will automatically prompt you for permission when you try to run it for the first time.

This script only works for text-based emails and will not handle attachments. If the email has rich HTML, images or CSS, it might not render correctly in the PDF file. If you need to handle these situations, you may need to use a more complex solution beyond Google Apps Script.