Skip to content

Instantly share code, notes, and snippets.

@white-hat-vaibhs
Created January 6, 2025 20:47
Show Gist options
  • Save white-hat-vaibhs/59190bb74d7036ce3b26c2e5ae96413e to your computer and use it in GitHub Desktop.
Save white-hat-vaibhs/59190bb74d7036ce3b26c2e5ae96413e to your computer and use it in GitHub Desktop.
/**
* Extracts email addresses from sent emails ("from:me") and writes them to a Google Sheet.
*
* This script processes Gmail threads in batches, extracts unique email addresses
* from the "To" field, and appends them to a Google Sheet. It also supports resuming
* from the last processed thread, enabling efficient handling of large email volumes.
*
* Author: Vaibhav Jain
* GitHub: https://github.com/white-hat-vaibhs
*/
function extractEmailAddressesFromMe() {
const userProperties = PropertiesService.getUserProperties();
// Retrieve the last processed thread index, defaulting to 0.
const lastProcessedThreadIndex = parseInt(userProperties.getProperty('LAST_PROCESSED_THREAD_INDEX') || '0', 10);
const batchSize = 100; // Number of threads to process in each execution
// Fetch threads from Gmail based on the "from:me" query in batches.
const threads = GmailApp.search('from:me', lastProcessedThreadIndex, batchSize);
Logger.log(`Threads fetched: ${threads.length}`);
// Exit if no threads are found.
if (threads.length === 0) {
Logger.log('No threads found. Exiting...');
return;
}
let emailAddresses = []; // Array to store unique email addresses.
// Process each thread to extract email addresses.
threads.forEach(thread => {
Logger.log(`Processing thread ID: ${thread.getId()}`);
// Get all messages in the thread.
const messages = thread.getMessages();
messages.forEach(message => {
Logger.log(`Processing message ID: ${message.getId()}`);
// Extract recipients from the "To" field.
const recipients = message.getTo().split(',');
// Add unique email addresses to the array.
recipients.forEach(email => {
email = email.trim(); // Remove leading/trailing spaces.
if (!emailAddresses.includes(email)) {
emailAddresses.push(email);
}
});
});
});
Logger.log(`Total unique email addresses extracted: ${emailAddresses.length}`);
// Write extracted email addresses to the active Google Sheet.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// Add a header row if the sheet is empty.
if (sheet.getLastRow() === 0) {
sheet.appendRow(['Email Addresses']);
}
// Append each email address to the sheet.
emailAddresses.forEach(email => sheet.appendRow([email]));
Logger.log('Finished writing email addresses to the sheet.');
// Update the last processed thread index and trigger the next batch if needed.
if (threads.length === batchSize) {
const nextThreadIndex = lastProcessedThreadIndex + batchSize;
userProperties.setProperty('LAST_PROCESSED_THREAD_INDEX', nextThreadIndex);
// Schedule the next execution after 1 second.
ScriptApp.newTrigger('extractEmailAddressesFromMe')
.timeBased()
.after(1000)
.create();
} else {
// Clear the property if all threads are processed.
userProperties.deleteProperty('LAST_PROCESSED_THREAD_INDEX');
}
}
/**
* - This script automates Gmail and Google Sheets integration.
* - Keywords: Gmail App Script, Google Sheets, Email Extraction, Automation, JavaScript.
* - Use this script for email marketing, CRM updates, or personal productivity.
*/
@white-hat-vaibhs
Copy link
Author

Gmail Email Extractor Script for Google Sheets

Description

This Google Apps Script automates the process of extracting email addresses from Gmail threads where you are the sender (from:me) and saves them to a Google Sheet. It processes threads in batches, ensures only unique email addresses are stored, and supports resumption for large email volumes.

This script is ideal for:

  • Email marketing: Quickly extract recipient email addresses for targeted campaigns.
  • CRM updates: Automate contact collection from sent emails.
  • Personal productivity: Manage your communication data with ease.

Features

  • Extracts recipient email addresses from Gmail messages using the from:me query.
  • Writes unique email addresses to a Google Sheet.
  • Processes Gmail threads in batches, resuming from the last processed thread to handle large datasets.
  • Automated scheduling for batch processing.
  • Fully commented code for easy customization and understanding.

How to Use

  1. Open the Google Apps Script Editor (script.google.com).
  2. Copy and paste the code into a new project.
  3. Link the script to your Gmail account and a Google Sheet.
  4. Run the script to start extracting email addresses from your sent emails.

SEO Keywords

  • Gmail email extraction
  • Google Sheets integration
  • Google Apps Script automation
  • Email marketing automation
  • CRM automation
  • Batch email processing

Example Use Cases

  • Export a list of recipients you’ve emailed for creating targeted campaigns.
  • Automate contact management for email-based workflows.
  • Simplify email data collection for analytics or reporting.

File Name

gmail-email-extractor.gs

Feel free to reach out if you have questions or need help customizing the script!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment