Gmail Add-in Is there any way to update the opened reply draft GmailApp

115 Views Asked by At

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

1

There are 1 best solutions below

0
Rafa Guillermo On

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: