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

JavaScript实现Gmail登录并获取含'match'的最新10封邮件的代码问题求助

我来帮你解决这个问题,你的代码主要有几个关键点需要调整,我会一步步说明并给出完整的修正代码:

问题分析

  • 首先,users.messages.list接口返回的messages数组里没有title字段,它只包含邮件的id和threadId,所以你直接访问messages[i].title会得到undefined,自然无法判断子字符串。
  • 你的if语句里多了一个多余的分号;,这是语法错误,会导致代码无法运行。
  • 要获取邮件的主题和内容,必须调用users.messages.get接口,传入邮件ID来获取完整的邮件详情。

修正后的完整代码

function listMessages() {
  var userId = "me";
  var request = gapi.client.gmail.users.messages.list({
    'userId': userId,
    'maxResults': 10 // 只获取最新10封邮件,符合需求
  });

  request.execute(function(resp) {
    var messages = resp.messages;
    var output = "<br>Query returned " + messages.length + " messages:<br>";
    var matchedCount = 0;

    // 遍历每封邮件ID,调用get接口获取完整详情
    messages.forEach(function(msg) {
      var getRequest = gapi.client.gmail.users.messages.get({
        'userId': userId,
        'id': msg.id,
        'format': 'full' // 获取完整邮件内容,包括headers和body
      });

      getRequest.execute(function(email) {
        // 1. 提取邮件主题(Subject)
        var subject = '';
        email.payload.headers.forEach(function(header) {
          if (header.name === 'Subject') {
            subject = header.value;
          }
        });

        // 2. 判断主题是否包含"match"(不区分大小写可加toLowerCase())
        if (subject.includes('match')) {
          matchedCount++;
          output += `<h3>第${matchedCount}封匹配邮件</h3>`;
          output += `<p><strong>主题:</strong> ${subject}</p>`;

          // 3. 提取邮件文本内容
          var emailContent = '';
          // 处理纯文本邮件
          if (email.payload.mimeType === 'text/plain') {
            // 解码Base64编码的内容(先修复URL安全转换的字符)
            emailContent = atob(email.payload.body.data.replace(/-/g, '+').replace(/_/g, '/'));
          } 
          // 处理多部分邮件(包含HTML和纯文本)
          else if (email.payload.parts) {
            // 遍历找到纯文本部分
            email.payload.parts.forEach(function(part) {
              if (part.mimeType === 'text/plain') {
                emailContent = atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));
              }
            });
          }

          output += `<p><strong>内容:</strong><br>${emailContent.replace(/\n/g, '<br>')}</p>`;
          output += '<hr>';

          // 更新页面显示内容
          document.getElementById("content").innerHTML = output;
        }
      });
    });
  });
}

关键说明

  • 获取邮件主题:邮件主题存在payload.headers数组中,需要遍历找到name为Subject的项,它的value就是主题内容。
  • 搜索子字符串:用ES6的includes()方法比indexOf()更直观,若需要不区分大小写的匹配,可以改成subject.toLowerCase().includes('match')。
  • 解析邮件内容:Gmail API返回的内容是经过URL安全转换的Base64编码,需要先把-转回+、_转回/,再用atob()解码。同时要兼容纯文本和多部分邮件的情况,确保能正确提取文本内容。
  • 限制最新10封:在list请求中添加maxResults: 10参数,直接获取最新的10封邮件,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:00:45