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);
}
Published in: Gmail - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch