Gmail Labels – How to Get All Email Addresses Associated with a Specific Label

gmailgmail-labelsgoogle-apps-script

How to get the list of all emails addresses associated to a Gmail label?

i.e. in a similar way than this question, but limited to a specific label?


Note: I post here with Answer your own question – share your knowledge, Q&A-style, because I don't have enough rep to post an answer in the aforementioned question.

Best Answer

  1. Create a new script on http://script.google.com,
  2. Past the code below,
  3. Open the menu Publish > Deploy web app..., and copy/paste the script URL(*),
  4. Run the script with the URL (accept the permission questions about Gmail):

    https://script.google.com/macros/s/.../dev?label=nameofthelabel
    

    It will directly display the addresses in the browser, without needing a spreadsheet or anything else.

Code:

function doGet(e) {
    var max = 100;
    var offset = 0;
    var searchThreads = [];
    var addresses = [];

    while (true) {
      var threads = GmailApp.search("label:" + e.parameter.label, offset, max);
      searchThreads = searchThreads.concat(threads);
      if (threads.length < max) { break; }
      offset += max;
    }  

    for (var i = 0; i < searchThreads.length; i++) {
      var messages = searchThreads[i].getMessages();
      for (var j = 0; j < messages.length; j++) {
        addresses.push(messages[j].getFrom());
      }
    }

    function onlyUnique(value, index, self) { return self.indexOf(value) === index; }
    var addr = addresses.filter(onlyUnique).join('\n');

    return ContentService.createTextOutput(addr).setMimeType(ContentService.MimeType.TEXT);
}

(*) Choose the "latest code" link, ending with /dev , it avoids to redeploy each time you do a tiny modification in code, as detailed here.