Quickstart: Gmail Add-on

Complete the steps described in the rest of this page, and in about five minutes you'll have created a Gmail add-on that displays other recent threads that the sender has started.

Prerequisites

To run this quickstart, you'll need:

  • Access to the internet and a web browser.
  • A Google account with Gmail enabled.
  • Access to Google Drive.

Step 1: Create the script project

  1. Create a new Apps Script project in your web browser. Apps Script places the project file in your Drive root folder so you can find it later.
  2. Choose Blank Project if presented with a welcome screen.
  3. Replace the Code.gs file contents with the following:
    var MAX_THREADS = 5;
    
    /**
     * Returns the array of cards that should be rendered for the current
     * e-mail thread. The name of this function is specified in the
     * manifest 'onTriggerFunction' field, indicating that this function
     * runs every time the add-on is started.
     *
     * @param {Object} e data provided by the Gmail UI.
     * @returns {Card[]}
     */
    function buildAddOn(e) {
      // Activate temporary Gmail add-on scopes.
      var accessToken = e.messageMetadata.accessToken;
      GmailApp.setCurrentMessageAccessToken(accessToken);
    
      var messageId = e.messageMetadata.messageId;
      var senderData = extractSenderData(messageId);
      var cards = [];
    
      // Build a card for each recent thread from this email's sender.
      if (senderData.recents.length > 0) {
        senderData.recents.forEach(function(threadData) {
          cards.push(buildRecentThreadCard(senderData.email, threadData));
        });
      } else {
        // Present a blank card if there are no recent threads from
        // this sender.
        cards.push(CardService.newCardBuilder()
          .setHeader(CardService.newCardHeader()
            .setTitle('No recent threads from this sender')).build());
      }
      return cards;
    }
    
    /**
     *  This function builds a set of data about this sender's presence in your
     *  inbox.
     *
     *  @param {String} messageId The message ID of the open message.
     *  @return {Object} a collection of sender information to display in cards.
     */
    function extractSenderData(messageId) {
      // Use the Gmail service to access information about this message.
      var mail = GmailApp.getMessageById(messageId);
      var threadId = mail.getThread().getId();
      var senderEmail = extractEmailAddress(mail.getFrom());
    
      var recentThreads = GmailApp.search('from:' + senderEmail);
      var recents = [];
    
      // Retrieve information about up to 5 recent threads from the same sender.
      recentThreads.slice(0,MAX_THREADS).forEach(function(thread) {
        if (thread.getId() != threadId && ! thread.isInChats()) {
          recents.push({
            'subject': thread.getFirstMessageSubject(),
            'count': thread.getMessageCount(),
            'link': 'https://mail.google.com/mail/u/0/#inbox/' + thread.getId(),
            'lastDate': thread.getLastMessageDate().toDateString()
          });
        }
      });
    
      var senderData = {
        "email": senderEmail,
        'recents': recents
      };
    
      return senderData;
    }
    
    /**
     *  Given the result of GmailMessage.getFrom(), extract only the email address.
     *  getFrom() can return just the email address or a string in the form
     *  "Name <myemail@domain>".
     *
     *  @param {String} sender The results returned from getFrom().
     *  @return {String} Only the email address.
     */
    function extractEmailAddress(sender) {
      var regex = /\<([^\@]+\@[^\>]+)\>/;
      var email = sender;  // Default to using the whole string.
      var match = regex.exec(sender);
      if (match) {
        email = match[1];
      }
      return email;
    }
    
    /**
     *  Builds a card to display information about a recent thread from this sender.
     *
     *  @param {String} senderEmail The sender email.
     *  @param {Object} threadData Infomation about the thread to display.
     *  @return {Card} a card that displays thread information.
     */
    function buildRecentThreadCard(senderEmail, threadData) {
      var card = CardService.newCardBuilder();
      card.setHeader(CardService.newCardHeader().setTitle(threadData.subject));
      var section = CardService.newCardSection()
        .setHeader("<font color=\"#1257e0\">Recent thread</font>");
      section.addWidget(CardService.newTextParagraph().setText(threadData.subject));
      section.addWidget(CardService.newKeyValue()
        .setTopLabel('Sender')
        .setContent(senderEmail));
      section.addWidget(CardService.newKeyValue()
        .setTopLabel('Number of messages')
        .setContent(threadData.count.toString()));
      section.addWidget(CardService.newKeyValue()
        .setTopLabel('Last updated')
        .setContent(threadData.lastDate.toString()));
    
      var threadLink = CardService.newOpenLink()
        .setUrl(threadData.link)
        .setOpenAs(CardService.OpenAs.FULL_SIZE);
      var button = CardService.newTextButton()
        .setText('Open Thread')
        .setOpenLink(threadLink);
      section.addWidget(CardService.newButtonSet().addButton(button));
    
      card.addSection(section);
      return card.build();
    }
    
  4. Click File > Save, name your project "Gmail Add-on Quickstart", and click OK.

Step 2: Update the script manifest

  1. In the script editor, select the View > Show manifest file menu item. This opens the manifest file (appsscript.json) in the editor.
  2. Delete the content of the manifest and replace it with the following:
    {
      "oauthScopes": [
        "https://www.googleapis.com/auth/gmail.addons.execute",
        "https://www.googleapis.com/auth/gmail.readonly"
      ],
      "gmail": {
        "name": "Gmail Add-on Quickstart",
        "logoUrl": "https://www.gstatic.com/images/icons/material/system/2x/bookmark_black_24dp.png",
        "contextualTriggers": [{
          "unconditional": {
          },
          "onTriggerFunction": "buildAddOn"
        }],
        "openLinkUrlPrefixes": [
          "https://mail.google.com/"
        ],
        "primaryColor": "#4285F4",
        "secondaryColor": "#4285F4",
        "version": "TRUSTED_TESTER_V2"
      }
    }
    
  3. Select File > Save to save these changes to the manifest. This step provides the add-on with required deployment information.

Step 3: Deploy the add-on

  1. In the script editor, select Publish > Deploy as > Custom from manifest.
  2. In the Deployments dialog, click the Get ID link for the Head Deployment.
  3. Locate the head deployment the Deployment ID. Copy this ID and then click Close.
  4. In the Deployments dialog, click Cancel. Creating a new deployment is not necessary, as you are using the head deployment only.
  5. Open the Gmail add-on settings tab.
  6. In the Add-ons tab, ensure that you have selected the Enable developer add-ons for my account checkbox.
  7. Paste your add-on's deployment ID into the Install developer add-on textbox and click Install.
  8. In the Install developer add-on dialog that appears, click the checkbox to indicate that you trust this developer (yourself), then click Install.

The add-on appears in the Developer add-ons list at this point. The Enable debugging information checkbox (which is checked by default) instructs Gmail to create and display an error report card when script or runtime errors occur during the execution of the add-on.

Step 4: Run the add-on

  1. On a desktop device, open Gmail. You may need to refresh the tab if Gmail is already open.
  2. Choose a message in Gmail and open it.
  3. Your installed add-ons appear as a column of icons to the right of the open email thread. Click on the bookmark icon that corresponds to the "Gmail Add-on Quickstart" you just installed.
  4. The add-on should place a contextual card on the right-side of the window, with a message asking for authorization. Click the Authorize access link to open a dialog where you can authorize the add-on.
  5. Select the account that should authorize the add-on.
  6. The next dialog may inform you that the app is not verified. In this case you can proceed by doing the following:
    1. Click Advanced.
    2. At the bottom of the dialog, click Go to Gmail Add-on Quickstart (unsafe).
    3. In the new dialog, type "Continue" into the text field, then click Next.
  7. Read the notice in the next dialog carefully, then click Allow.
  8. Once authorized, the add-on should automatically refresh and start operating.

Further reading

To learn more about Gmail add-ons and Apps Script, take a look at the following resources: