Search code examples
google-apps-scriptgmail-addons

Drafts is not updating by newly inserted values in gmail, google app script


I want to update or replace or insert the existing drafts using google app scripts in my gmail. I have a code below but its not inserting any text in the existing drafts.

What, I want to do is to update or insert or replace my existing drafts using google app scripts.

function buildAddOn(e)
{
  return generatedDrafts();
}

function generatedDrafts()
{
  tex = 'This needs to be inserted';

  var card = CardService.newCardBuilder();
  var cardSection = CardService.newCardSection().setHeader('Texts');

  cardSection.addWidget(CardService.newTextButton().setText(tex).setOnClickAction(CardService.newAction().setFunctionName('applyText')
  .setParameters({'updatedText':tex})));

  return card.addSection(cardSection).build();
}


function applyText(e)
{
  content = e.parameters.updatedText;

  var response = CardService.newUpdateDraftActionResponseBuilder().setUpdateDraftBodyAction(CardService.newUpdateDraftBodyAction()
  .addUpdateContent(content, CardService.ContentType.TEXT).setUpdateType(CardService.UpdateDraftBodyType.IN_PLACE_INSERT)).build();

 return response; 
}

the appscript manifesto looks like this

"gmail": {
    "contextualTriggers": [
        {
            "unconditional": {},
            "onTriggerFunction": "buildAddOn"
        }
    ],

Can any one suggest me what I am doing wrong and how can i fix my problem ?


Solution

  • Your issue is that you created a general Add-On, not one that triggers on messages.

    You want to follow these recommendations and change your manifest file to include the necessary parts.

    {
      "oauthScopes": [
        //...
        "https://www.googleapis.com/auth/gmail.addons.current.action.compose",
        //...
      ],
      "gmail": {
        /...
        "contextualTriggers": [{
          /...
        }],
        "composeTrigger": {
          "selectActions": [
            {
              "text": "Insert Text on Emails",
              "runFunction": "insertTextAction"
            }
          ],
          "draftAccess": "METADATA"
        },
    }
    

    And your code should have a insertTextAction function that creates a Card with actions that return UpdateDraftActionResponse:

    function insertTextAction(e) {
      return generatedDrafts();
    }
    

    After those changes, you should be good to go!