1

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.

  • 1
    Yes @pnuts, I'm sure - association bonus doesn't count. Anyway this question here is a little different, in the sense it's specific to a label. – Basj Sep 10 '17 at 20:57
  • 1
    I tried @pnuts, but didn't work there: the site didn't let me post there. – Basj Sep 10 '17 at 21:32
  • 1
    Yes @pnuts. But not a big deal, happy to have found a solution for this email-addresses-extraction from a label :) – Basj Sep 10 '17 at 21:48
1
  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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.