Google Script for Extracting Email Addresses from Gmail

G
Published in: Gmail - Google Apps Script

This Google Apps Script will sift through your Gmail account and extract email addresses of senders which are then saved in a Google Sheet. Useful for email marketing and mail merge.

//   Written by Amit Agarwal on 06/13/2013
function extractEmailAddresses() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  var monitor = sheet.getRange("A2").getValue();
  var processed = sheet.getRange("B2").getValue();

  var label = GmailApp.getUserLabelByName(processed);
  var search = "in:" + monitor + " -in:" + processed;

  // Process 50 Gmail threads in a batch to prevent script execution errors
  var threads = GmailApp.search(search, 0, 50);

  var row, messages, from, email;

  try {

    for (var x=0; x<threads.length; x++) {

      // Use Regular Expression to extract valid email address
      from = threads[x].getMessages()[0].getFrom();
      from = from.match(/\S+@\S+\.\S+/g);

      if ( from.length ) {

        email = from[0];
        email = email.replace(">", "");
        email = email.replace("<", "");

        row   = sheet.getLastRow() + 1;
        // If an email address if found, add it to the sheet
        sheet.getRange(row,1).setValue(email);
      }

      threads[x].addLabel(label);

    }

  }

  catch (e) {
    Logger.log(e.toString());
    Utilities.sleep(5000);
  }

  // All messages in the label have been processed?
  if ( threads.length === 0 ) {
    GmailApp.sendEmail(Session.getActiveUser().getEmail(), "Extraction Done",
                       "Download the sheet from " + ss.getUrl());
  }
}


// Remove Duplicate Email addresses
function cleanList() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getRange(4, 1, sheet.getLastRow()).getValues();
  var newData = new Array();
  for(i in data){
    var row = data[i];
    var duplicate = false;
    for(j in newData){
      if(row[0] == newData[j][0]){
        duplicate = true;
      }
    }
    if(!duplicate){
      newData.push(row);
    }
  }

  // Put the unique email addresses in the Google sheet
  sheet.getRange(4, 2, newData.length, newData[0].length).setValues(newData);
}
📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Gmail - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account
G

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube