-1

I'm developing a gmail add-on. I have created a feature to create a reply draft when user fill some text inputs and click on a button (There are some API calls to create email body by using these details).

function composeReply(e){
            var messageId = e.messageMetadata.messageId;
            var message = GmailApp.getMessageById(messageId);
            ......
            var msg = {
              htmlBody: result['email_content'],
              subject: result['email_subject']
            }
    
            var draft = message.createDraftReply('', msg);
            return CardService.newComposeActionResponseBuilder().setGmailDraft(draft).build();

    }

In the above function I want to check whether the message have already a reply draft then update that else create a new reply draft Or Is there any way to delete the existing draft before creating a new one

TheMaster
  • 45,448
  • 6
  • 62
  • 85
Anoop
  • 2,748
  • 4
  • 18
  • 27
  • 1
    So do you basically want to check if a draft for that thread of messages does already exists and if so to delete it? – Mateo Randwolf Aug 06 '20 at 14:31
  • Yes. that's also fine for me. My issue is, now for each click addon is creating a new draft. – Anoop Aug 06 '20 at 14:43
  • So in your Add-On I assume you have a button that when pressed it creates a draft message am I right? Then why you dont want the button to create new drafts when clicked? Do you want to just create a single draft on click and then to stop the button from creating new drafts? – Mateo Randwolf Aug 10 '20 at 08:25

1 Answers1

1

Answer:

You can't do this using GmailApp, however you can use the Advanced Gmail Service to get a list of message drafts and check if the current message has the same thread ID as any of the drafts.

Example:

Using the special me value for the user ID, you can make an Advanced Gmail service call to get a list of drafts:

var response = Gmail.Users.Drafts.list("me");

As per the documentation on Users.drafts: list, you will get an array of users.drafts resources in the response:

{
  "drafts": [
    users.drafts Resource
  ],
  "nextPageToken": string,
  "resultSizeEstimate": unsigned integer
}

You can then use Users.messages: get to get the thread ID from the current message:

var threadId = Gmail.Users.Messages.get("me", messageId).threadId

or by using GmailApp:

var threadId = GmailApp.getMessageById(messageId).getThread().getId()

From here, you can loop through the drafts, checking if the thread IDs match, and if they do, then the draft already exists and you can delete it:

try {
  response.drafts.forEach(function(draft) {
    if (draft.message.threadId == threadId) {
      throw draft.id;
    }
  });
}
catch (id) {
  Gmail.Users.Drafts.remove("me", id)
}  
// create new draft here

References:

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Rafa Guillermo
  • 14,474
  • 3
  • 18
  • 54