Gmail – Add Label and Send Email to All Search Results

gmailgmail-labels

Say I sent a bunch of emails last year to people that weren't on any list then. I now want to be able to email the same people again, all in one shot ideally. I think I can do a reasonable job of creating a search query that will return the emails that I had sent. I'm thinking of trying to add some sort of label to the emails themselves, or to the email addresses (they are not currently in contacts), and then sending an email with the same text to all of them.

This is for mailing some ski places for availability in case anyone is wondering.

Best Answer

I ended up writing a script using the Gmail API from Google to do this - https://developers.google.com/gmail/api/. I ended up using the API to search all emails with particular keywords and add them all to a Contact Group. I then manually curated the group entries to filter out bad results, and finally, sent the email that I wanted to this Contact Group.

function handleMessage(the_message, contacts_group){
  var req = Gmail.Users.Messages.get('me',the_message.id, {'format':'metadata', 'metadataHeaders':['To']});
  var payload = req.payload;
  for (var j = 0; j < payload.headers.length; j++) {
    var hdr = payload.headers[j];
    var addr = hdr.value;
    var newContact = ContactsApp.createContact('', '', addr);
    contacts_group.addContact(newContact);
    Logger.log('- %s', hdr.value);
  }
}

function getMessages(){
  var query = 'ski';
  var pageToken = '';
  var userId = 'me';
  var pageCount = 1;
  var skiContacts = ContactsApp.getContactGroup('Ski Places');

  while(true){
    var resp = Gmail.Users.Messages.list(userId,{'q':query, 'pageToken': pageToken});
    var messages = resp.messages;
    for(var i = 0; i < messages.length; i++){
      handleMessage(messages[i], skiContacts)
    }

    Logger.log('- %s', pageCount);
    Logger.log('- %s', pageToken);

    pageToken = resp.nextPageToken;
    pageCount +=1;

    if(pageToken === undefined){
      break;
    }
  }
}