Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 5, 2024 💻 Tutorial ⭐ Beginner Friendly

Export Email To GoogleSheet

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

Exporting emails to Google Sheets can be automated using Google Apps Script. It connects Gmail to Sheets, extracts details like sender, subject, date, and body, and logs them into rows. This helps organize and analyze emails without manual copy-pasting, ideal for tracking leads, support requests, or client communication.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

📂 javascript
⚡ script1.js
⚡ script1.js
function exportInboxEmailsToSheet() {
  try {
    const batchSize = 500;
    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = spreadsheet.getActiveSheet();

    // Create a sheet if none exists
    if (!sheet) {
      sheet = spreadsheet.insertSheet();
    }

    // Clear previous data (except headers)
    const lastRow = sheet.getLastRow();
    if (lastRow > 1) {
      sheet.getRange(2, 1, lastRow - 1, sheet.getLastColumn()).clear();
    }

    const scriptProperties = PropertiesService.getScriptProperties();
    let lastProcessedTimestamp = scriptProperties.getProperty('lastProcessedTimestamp');

    let start = 0;
    let threads;
    let totalEmails = 0;
    const data = [];

    do {
      // Fetch threads in batches
      threads = GmailApp.search('in:inbox', start, batchSize);

      threads.forEach(thread => {
        const messages = thread.getMessages();

        messages.forEach(message => {
          const timestamp = message.getDate();

          // Skip messages already processed
          if (lastProcessedTimestamp && timestamp <= new Date(lastProcessedTimestamp)) {
            return;
          }

          const threadCount = thread.getMessageCount();
          const fromEmail = message.getFrom();
          const toEmail = message.getTo();
          const subject = message.getSubject();
          const bodyContent = message.getPlainBody().substring(0, 1000); // Limit body to 1000 chars
          const messageId = message.getId();
          const link = 'https://mail.google.com/mail/u/0/#inbox/' + messageId;

          // Add row to data array
          data.unshift([timestamp, threadCount, fromEmail, toEmail, subject, bodyContent, link]);
          totalEmails++;
        });
      });

      // Write batch to sheet
      if (data.length > 0) {
        lastProcessedTimestamp = data[0][0];
        scriptProperties.setProperty('lastProcessedTimestamp', lastProcessedTimestamp);

        sheet.getRange(2, 1, data.length, data[0].length)
          .setValues(data.reverse());

        data.length = 0; // Clear array for next batch
        SpreadsheetApp.flush();
      }

      start += batchSize;

    } while (threads.length === batchSize);

    Logger.log("Exported " + totalEmails + " new emails to the active sheet.");

  } catch (e) {
    Logger.log("Error exporting emails: " + e.toString());
    throw e;
  }
}