メインコンテンツにスキップ

Realtime-Gmail-Listener

Realtime Gmail listener using push notifications via Pub/Sub. Cloud Run acts as a webhook proxy to Apps Script for processing new emails into Sheets. No polling. Apps Script quota-safe. Serverless. Fully automated with PowerShell deployment.

AI Summary

Realtime Gmail Listener

A wrapper library that enables Google Apps Script to receive new Gmail messages in real-time via Cloud Pub/Sub.

Target Users

Intermediate Apps Script developers building internal workflows or automations that must react instantly to incoming emails.

Problems Solved

Implementing Gmail push notifications requires complex watch API calls, Pub/Sub configuration and historyId tracking, making it hard to do directly from Apps Script.

Tags

Main Features

1
Instant detection via push

Leverages Gmail watch API and Cloud Pub/Sub under the hood to receive new message IDs within seconds of arrival.

2
One-line automated setup

`install()` handles topic creation, permission grants and historyId storage, eliminating tedious initial setup.

3
Reliable incremental fetching

Maintains and updates historyId to avoid missing or duplicating messages, even after script restarts.

Usage Examples

【Introduction】Start the listener in a few lines

function install() {
  // Automatically creates Gmail watch & Pub/Sub topic
  RealtimeGmailListener.install();
}

Running this once sets up everything; new mail now triggers onGmailPush in real time.

【Basic】Log subject & body of new mails

/**
 * Pub/Sub trigger handler
 * @param {Object} e Pub/Sub event payload
 */
function onGmailPush(e) {
  // Fetch GmailMessage objects without duplicates
  const messages = RealtimeGmailListener.getNewMessages(e);

  messages.forEach(msg => {
    const body = msg.getPlainBody();
    Logger.log(`Subject: ${msg.getSubject()}
Body: ${body}`);
  });
}

getNewMessages(e) calculates historyId for you and returns clean GmailMessage instances.

【Best Practice】Save attachments to Drive & notify Slack

function onGmailPush(e) {
  const messages = RealtimeGmailListener.getNewMessages(e);

  messages.forEach(msg => {
    const folder = DriveApp.getFolderById('YOUR_DRIVE_FOLDER_ID');

    msg.getAttachments().forEach(att => {
      const file = folder.createFile(att.copyBlob()).setName(att.getName());

      // Send Slack notification
      const payload = {
        text: `📧 Saved attachment from "${msg.getSubject()}" to Drive: ${file.getUrl()}`
      };
      UrlFetchApp.fetch('https://hooks.slack.com/services/XXXXX/XXXXX', {
        method: 'post',
        contentType: 'application/json',
        payload: JSON.stringify(payload)
      });
    });
  });
}

This real-world snippet shows how to react instantly, store files and alert a chat channel.