user3932313
user3932313

Reputation: 85

Getting thread id of a mail sent through google scripts

Is it possible to get the thread id of a mail sent through MailApp.sendEmail().I want to tag the sent mail with a label just after it is sent.

MailApp.sendEmail("[email protected]","Sellers Required for pilot",msg_to_bd);
//get thread id for this mail, say thread 1
thread1.addLabel(labll);

Upvotes: 4

Views: 4328

Answers (4)

Jindřich Širůček
Jindřich Širůček

Reputation: 344

Im using this, it adds uuid hidden code into message, and I can find/label particular email with 100% precision:

var uid = Utilities.getUuid();
var uidText = '<span style="color:transparent; display:none !important; height:0; opacity:0; visibility:hidden; width:0">' + uid +  '</span>';
GmailApp.sendEmail(parameters.email, subject, "", {"htmlBody":htmlEmail + uidText});
Utilities.sleep(1000);
GmailApp.search(uid)[0].addLabel(label)

Upvotes: 1

Paul Komarek
Paul Komarek

Reputation: 11

Since all of the GmailApp.send* methods (at the time of writing) do not return a message or thread identifier, and since the GmailMessage object has no send* method, the safest thing to do seems like embedding a unique identifier into the message when it is sent. Then search for an email containing the unique identifier.

This code worked for me as an experiment. Note that I had to sleep() for a couple seconds in order for the search to succeed.

  function tryit() {
    var searchTerm = Utilities.getUuid();
    GmailApp.sendEmail('[email protected]', 'oh please',
                       'custom id: ' + searchTerm);
    Utilities.sleep(2000);
    var threadIds = GmailApp.search(searchTerm);
    Logger.log(threadIds);
    if (threadIds.length != 1) {
      Browser.msgBox('Found too many threads with unique id '
                     + searchTerm);
      return;
    }
    return threadIds[0];
  }

I suspect the reason we have to jump through hoops is that the API authors don't want to make sending email synchronous (maybe it can take too long), and hence they have no way to return an error or message id upon failure or success.

If you want to go completely crazy, you could send a message to yourself with the uuid, then spin in a while-sleep-search loop until you found the uuid and hence get a thread id, then reply to the thread with the full list of recipients. This guarantees that only your inbox suffers if things go wrong.

Upvotes: 1

Jesse Scherer
Jesse Scherer

Reputation: 1512

First, since you want to add labels to the thread you just sent, you must be using GmailApp. MailApp only allows you to send mail, not interact with the user's inbox.

As you've seen, GmailApp.sendEmail() does not return a message or thread ID. In this case, you can search for the thread you just sent, but you must account for when you've sent several messages to this person.

As long as you are not sending duplicate mails very quickly, you can rely on the fact that a call to GmailApp.search() will return threads in the same order as the web UI. So a search for 'from:me to:[email protected]' might return many threads, but the first result will be the thread for the most recently sent message.

A toy example where we send a mail to a bunch of addresses listed in a tab called Recipients:

var recipients = SpreadsheetApp.getActiveSpreadsheet()
                               .getSheetByName('Recipients')
                               .getDataRange()
                               .getValues();
recipients.shift();  // Only if the Recipients sheet contained a header you need to remove
var d = new Date();  
var dateText = d.toLocaleString(); // Pretty-printed timestamp
var newLabel = GmailApp.createLabel(dateText); // Label corresponding to when we ran this
for (var i = 0; i < recipients.length; i++) {
  GmailApp.sendEmail(recipients[i], 'This is a test', 'Of the emergency broadcast system');
  var sentThreads = GmailApp.search('from:me to:' + recipients[i]);
  var mostRecentThread = sentThreads[0];
  mostRecentThread.addLabel(newLabel);
}

Upvotes: 4

Amit Agarwal
Amit Agarwal

Reputation: 11268

Apps Script won't return the thread ID but what you can do is search for the subject in your mailbox after sending the email and apply the label to the first thread in the result.

var to="[email protected]", subject="email subject";
GmailApp.sendEmail(to,subject,msg_to_bd);
var threads = GmailApp.search("to:" + to + " in:sent subject:" + subject, 0, 1);
threads[0].addLabel(label);

Upvotes: 1

Related Questions