撰寫草稿訊息

您可以在外掛程式中建立連結動作小工具。您可以使用動作撰寫新的電子郵件草稿,並視需要使用在外掛程式使用者介面中輸入的資訊,或開啟郵件中的資訊填寫草稿。舉例來說,您可以在外掛程式的訊息使用者介面中加入按鈕,讓使用者建立回覆,並預先填入外掛程式中的資訊。

觸發建構郵件的動作時,Gmail 會執行回呼函式來建構及傳回草稿。Gmail 接著會在標準電子郵件撰寫視窗中顯示該草稿,使用者可以視需要編輯並傳送。

設定動作來建立訊息草稿

如要設定小工具,在選取時啟動草稿建立動作,請完成下列步驟:

  1. 確認資訊清單包含action.compose 範圍

    https://www.googleapis.com/auth/gmail.addons.current.action.compose

    您可以改用較寬鬆的範圍,但只有在絕對必要時才應這麼做。

  2. 建立 Action 物件,並將其與您定義的回呼函式建立關聯。

  3. 呼叫小工具的 setComposeAction 小工具處理常式函式, 提供 Action 物件並指定 ComposeEmailType

  4. 實作執行草稿建構動作的回呼函式。這個函式會以引數的形式取得事件物件。回呼函式必須執行下列操作:

    1. 建立 GmailDraft 物件。
    2. 使用 ComposeActionResponseBuilder 類別和 GmailDraft 物件,建構 ComposeActionResponse 物件。
    3. 傳回建構的 ComposeActionResponse

您可以在回呼函式中建立 GmailDraft,並預先填入收件者、主旨、郵件內文和附件。草稿內容可從任何來源取得,但通常是從外掛程式本身提供的資訊、開啟的郵件內容,或從第三方服務收集的資訊衍生而來。傳遞至回呼函式的事件物件包含開啟的訊息 ID 和其他外掛程式資訊,可用於預先填入草稿。

您可以將草稿建立為新的獨立訊息,或回覆現有訊息。這是由提供給 setComposeActionComposeEmailType 列舉控制。你可以建立單一回覆或「全部回覆」訊息的回覆草稿。

獨立草稿

獨立草稿會發起新討論串,且不會回覆任何現有訊息。您可以使用下列任一 Gmail 服務函式建立獨立草稿:

回覆草稿

回覆草稿會顯示在現有訊息串中。回覆草稿分為兩種:只傳送給郵件寄件者的單一回覆,以及傳送給所有郵件收件者的「回覆所有人」草稿。您可以使用下列 Gmail 服務函式建立回覆草稿:

範例

下列程式碼片段說明如何將動作指派給按鈕,以建構回覆草稿。

var composeAction = CardService.newAction()
    .setFunctionName('createReplyDraft');
var composeButton = CardService.newTextButton()
    .setText('Compose Reply')
    .setComposeAction(
        composeAction,
        CardService.ComposedEmailType.REPLY_AS_DRAFT);

// ...

/**
 *  Creates a draft email (with an attachment and inline image)
 *  as a reply to an existing message.
 *  @param {Object} e An event object passed by the action.
 *  @return {ComposeActionResponse}
 */
function createReplyDraft(e) {
  // Activate temporary Gmail scopes, in this case to allow
  // a reply to be drafted.
  var accessToken = e.gmail.accessToken;
  GmailApp.setCurrentMessageAccessToken(accessToken);

  // Creates a draft reply.
  var messageId = e.gmail.messageId;
  var message = GmailApp.getMessageById(messageId);
  var draft = message.createDraftReply('',
      {
          htmlBody: "Kitten! <img src='cid:kitten'/>",
          attachments: [
            UrlFetchApp.fetch('https://example.com/images/myDog.jpg')
                .getBlob()
          ],
          inlineImages: {
            "kitten": UrlFetchApp.fetch('https://example.com/images/myKitten.jpg')
                          .getBlob()
          }
      }
  );

  // Return a built draft response. This causes Gmail to present a
  // compose window to the user, pre-filled with the content previously
  // specified.
  return CardService.newComposeActionResponseBuilder()
      .setGmailDraft(draft).build();
}