You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Tasks标记完成时触发Google Apps Script更新Gmail标签

Great question! You're right that Google Apps Script doesn't have a native trigger for when a Google Task is marked complete, but there are reliable workarounds to build this functionality yourself—no Zapier required, and you’ll have full control over adding/removing labels.

Workaround 1: Time-Driven Polling (Simplest Approach)

Since we can’t get a real-time trigger directly from Tasks, we can set up a script that periodically checks for newly completed tasks and updates linked Gmail messages accordingly. Here’s how to implement it:

To make this work, you need a way to connect tasks to their corresponding emails. The easiest method is to embed the Gmail message ID in the task’s notes when creating the task. You can automate this with a small script:

// Add this script to create tasks from selected Gmail messages with embedded email IDs
function createTaskFromSelectedEmail() {
  const targetTaskListName = "Your Task List"; // Replace with your task list name
  const incompleteLabel = GmailApp.getUserLabelByName("uncompleted-task");

  // Get selected emails and target task list ID
  const selectedEmails = GmailApp.getSelectedMessages();
  const taskListId = Tasks.Tasklists.list().items.find(list => list.title === targetTaskListName).id;

  selectedEmails.forEach(email => {
    // Create task with email ID in notes
    Tasks.Tasks.insert({
      title: `Follow up: ${email.getSubject()}`,
      notes: `Gmail ID: ${email.getId()}\nFrom: ${email.getFrom()}`,
      due: new Date(new Date().setDate(new Date().getDate() + 7)).toISOString()
    }, taskListId);

    // Add incomplete label to the email
    email.addLabel(incompleteLabel);
  });
}

You can add this as a custom menu in Gmail for quick access (via the script editor’s "Extensions > Apps Script" menu).

Step 2: Script to Sync Completed Tasks to Gmail

This script will check for newly completed tasks, find the linked email, swap the labels, and track processed tasks to avoid duplicates:

function syncCompletedTasksToGmail() {
  const targetTaskListName = "Your Task List"; // Match your task list name
  const incompleteLabel = GmailApp.getUserLabelByName("uncompleted-task");
  const completedLabel = GmailApp.getUserLabelByName("completed-task");
  
  // Store processed task IDs to avoid re-running
  const processedTasksProp = PropertiesService.getScriptProperties().getProperty("processedCompletedTasks") || "";
  const processedTaskIds = new Set(processedTasksProp.split(",").filter(id => id));

  // Get completed tasks from your target list
  const taskListId = Tasks.Tasklists.list().items.find(list => list.title === targetTaskListName).id;
  const completedTasks = Tasks.Tasks.list(taskListId, { showCompleted: true }).items || [];

  completedTasks.forEach(task => {
    if (!processedTaskIds.has(task.id) && task.notes.includes("Gmail ID:")) {
      // Extract Gmail ID from task notes
      const emailIdMatch = task.notes.match(/Gmail ID: (\S+)/);
      if (emailIdMatch) {
        const emailId = emailIdMatch[1];
        // Update labels on the email
        const message = GmailApp.getMessageById(emailId);
        message.removeLabel(incompleteLabel).addLabel(completedLabel);
        
        // Mark task as processed
        processedTaskIds.add(task.id);
      }
    }
  });

  // Update stored processed task IDs
  PropertiesService.getScriptProperties().setProperty("processedCompletedTasks", Array.from(processedTaskIds).join(","));
}

Step 3: Set Up a Time-Driven Trigger

  1. In the Apps Script editor, click Edit > Current project's triggers.
  2. Click Add trigger and configure:
    • Choose function: syncCompletedTasksToGmail
    • Choose deployment: Head
    • Event source: Time-driven
    • Type of time based trigger: Minute timer
    • Interval: Every 5 minutes (adjust based on how quickly you need updates)
Workaround 2: Real-Time Trigger with Pub/Sub (Advanced)

If you need near-instant updates instead of polling, you can use Google Cloud Pub/Sub to set up push notifications for Task status changes. This requires more setup in Google Cloud Console, but it’s fully real-time:

  • Enable the Tasks API and Pub/Sub API in your Google Cloud project.
  • Create a Pub/Sub topic and configure Tasks to send push notifications to this topic when tasks are marked complete.
  • Deploy a Google Apps Script Web App as a Pub/Sub subscription endpoint to handle the notification and update Gmail labels.

This method is better for power users who can’t wait for polling intervals, but the polling approach is more than sufficient for most use cases.

内容的提问来源于stack exchange,提问作者jkf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:08:18