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

如何通过GScript查找Gmail中含日历项的邮件并提取其信息?

Absolutely! You can definitely use Google Apps Script (GScript) to locate emails with those calendar ICS attachments, and extract the event details from them. Let me walk you through the process step by step:

1. Locate Emails with ICS Attachments

First, use Gmail's search operators to target emails that have .ics attachments. You can use the GmailApp.search() method with the query has:attachment filename:ics to pull up relevant threads. Then iterate through the messages and filter out the actual ICS attachments.

Here's a sample script to get you started:

function findICSAttachedEmails() {
  // Search Gmail for emails containing .ics attachments
  const threads = GmailApp.search('has:attachment filename:ics');
  
  // Loop through each thread and its messages
  threads.forEach(thread => {
    const messages = thread.getMessages();
    messages.forEach(message => {
      const attachments = message.getAttachments();
      
      // Filter attachments to only include .ics files (check content type and filename)
      const icsFiles = attachments.filter(att => {
        const contentType = att.getContentType();
        const fileName = att.getName();
        return contentType === 'text/calendar' || fileName.toLowerCase().endsWith('.ics');
      });
      
      if (icsFiles.length > 0) {
        console.log(`Found ICS attachment in email: ${message.getSubject()}`);
        // Process each ICS file to extract event data
        icsFiles.forEach(icsFile => extractICSData(icsFile));
      }
    });
  });
}
2. Extract and Parse ICS Data

ICS files are plain-text files following the iCalendar specification, so you can read their content as a string and parse out key event fields like summary, start/end time, location, etc.

Add this helper function to parse the ICS content:

function extractICSData(icsAttachment) {
  // Convert the attachment to a plain text string
  const icsText = icsAttachment.getDataAsString();
  // Split the content into individual lines (handle line breaks)
  const lines = icsText.split(/\r?\n/);
  
  const eventDetails = {};
  let lastKey = '';
  
  lines.forEach(line => {
    // Handle "folded" lines (ICS uses leading spaces/tabs to continue a line)
    if (line.startsWith(' ') || line.startsWith('\t')) {
      if (lastKey) {
        eventDetails[lastKey] += line.trim();
      }
      return;
    }
    
    // Split line into key and value (split only on the first colon)
    const [rawKey, value] = line.split(':', 2);
    if (!rawKey || !value) return;
    
    // Clean the key (remove any parameters like ;VALUE=DATE)
    const cleanKey = rawKey.split(';')[0];
    eventDetails[cleanKey] = value.trim();
    lastKey = cleanKey;
  });
  
  // Log or use the extracted data as needed
  console.log('Extracted Calendar Event Details:');
  console.log(`Event Title: ${eventDetails.SUMMARY || 'No title'}`);
  console.log(`Start Time: ${formatICSDate(eventDetails.DTSTART)}`);
  console.log(`End Time: ${formatICSDate(eventDetails.DTEND)}`);
  console.log(`Location: ${eventDetails.LOCATION || 'No location specified'}`);
  console.log(`Event UID: ${eventDetails.UID}`);
}

// Helper function to format ICS date strings into readable dates
function formatICSDate(icsDateStr) {
  if (!icsDateStr) return 'N/A';
  // Handle different ICS date formats (UTC: YYYYMMDDTHHMMSSZ, local with timezone, etc.)
  try {
    // For UTC format (ends with Z)
    if (icsDateStr.endsWith('Z')) {
      const isoStr = icsDateStr.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/, '$1-$2-$3T$4:$5:$6Z');
      return new Date(isoStr).toLocaleString();
    }
    // For local date-only format (YYYYMMDD)
    else if (icsDateStr.length === 8) {
      const isoStr = `${icsDateStr.slice(0,4)}-${icsDateStr.slice(4,6)}-${icsDateStr.slice(6,8)}`;
      return new Date(isoStr).toLocaleDateString();
    }
    // Fallback to direct date parsing
    return new Date(icsDateStr).toLocaleString();
  } catch (e) {
    return `Invalid date format: ${icsDateStr}`;
  }
}
Notes to Keep in Mind
  • Permissions: When you first run the script, you'll need to grant it access to your Gmail account (this is standard for GScript interacting with Gmail).
  • Complex Events: The above script handles basic single events. For recurring events, attendees, or extended properties, you'll need to expand the parsing logic (e.g., look for RRULE fields or ATTENDEE lines).
  • Testing: Start with a small search scope (e.g., add in:inbox to the search query) to test the script before running it on all your emails.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:35:41