How to extract email addresses from Gmail

How to extract email addresses from Gmail

You can use the below Apps Script code to extract email addresses from Gmail label.

function extractEmailAddresses() {
  var emailAddresses = [];
  
  // Replace "INBOX" with the label you want to search
  var threads = GmailApp.search("label:INBOX");
  
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var message = messages[j];
      var subject = message.getSubject();
      var to = message.getTo();
      var cc = message.getCc();
      var bcc = message.getBcc();
      
      // Add the email addresses from the "To" field to the emailAddresses array
      emailAddresses = emailAddresses.concat(to);
      
      // Add the email addresses from the "Cc" field to the emailAddresses array
      emailAddresses = emailAddresses.concat(cc);
      
      // Add the email addresses from the "Bcc" field to the emailAddresses array
      emailAddresses = emailAddresses.concat(bcc);
    }
  }
  
  // Remove duplicates from the emailAddresses array
  emailAddresses = emailAddresses.filter(function(item, pos) {
    return emailAddresses.indexOf(item) == pos;
  });
  
  // Log the email addresses
  Logger.log(emailAddresses);
}

This script searches for emails in the “INBOX” label and extracts the email addresses from the “To”, “Cc”, and “Bcc” fields of each email. It then removes any duplicates and logs the email addresses.

To search for emails based on matching words in the subject, you can modify the GmailApp.search() method like this:

var threads = GmailApp.search("label:INBOX subject:searchterm");

Replace “searchterm” with the word or phrase you want to search for.

To search for emails based on a search criteria, you can use the GmailApp.search() method like this:

var threads = GmailApp.search("label:INBOX criteria");

Replace “criteria” with your search criteria. You can use the same search operators that you would use when searching for emails in Gmail. For example, you can use from: to search for emails from a specific sender, subject: to search for emails with a specific subject, has:attachment to search for emails with attachments, and so on.

This is a very useful way to extract emails that can be further used to feed your emailing services like Mailchimp, ActiveCampaign etc. or your CRM like Salesforce.