【问题标题】:search messages with Gmail API in Google Apps Script在 Google Apps 脚本中使用 Gmail API 搜索邮件
【发布时间】:2016-06-06 22:05:03
【问题描述】:

我已经通过 StackOverflow 进行了(小)成功搜索,因此我向比我更专业的编码人员寻求帮助。

我在 SO gmailapp-add-label-to-specific-message-not-the-thread 上阅读了这个主题,这让我看到了这个 GIST,我在其中获取了标记单个消息(而不是整个线程)的代码。

现在我需要在 Google Apps Script 中使用 Gmail API 的搜索功能;我在 Google Developer's Site here 上找到了一个 Javascript sn-p。我正在尝试使用 GIST 中的代码作为示例来调整此代码,但没有成功。

我需要搜索函数来获取消息 ID 的数组以传递给另一个函数(目前可行;))。

这是我写的代码:

/**
 * Retrieve Messages in user's mailbox matching query.
 *
 * @param  {String} userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  {String} query String used to filter the Messages listed.
 * @param  {Function} callback Function to call when the request is complete.
 */
function GAPIlistMessages(userId, query) { //callback option removed from original code

 // GET https://www.googleapis.com/gmail/v1/users/userId/messages
  var url = 'https://www.googleapis.com/gmail/v1/users/${userId}/messages'
  .replace("${userId}","me")
            var headers = {
    Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
  };

    var request = {
      'userId': userId,
      'q': query
  };

  var params = {
    method: "GET",
    contentType: "application/json",
    headers: headers,
    muteHttpExceptions: true, // for debugging
    payload: JSON.stringify(request)
    };

  var check = UrlFetchApp.getRequest(url, params); // for debugging
  var response = UrlFetchApp.fetch(url, params);

  var result = response.getResponseCode();
  if (result == '200') {  // OK
    var msgIds = JSON.parse(response.getContentText()).msgIds;
  Logger.log(msgIds)
  }
  else {
    // This is only needed when muteHttpExceptions == true
    var err = JSON.parse(response.getContentText());
    throw new Error( 'Error (' + result + ") " + err.error.message );
  } 
}

当我启动函数时,传递这个参数: 用户 ID = '我' query = 'deliveredto:myemail+test@mydomain.com'

我收到此错误

[16-02-24 06:37:29:218 PST] Avvio dell'esecuzione
[16-02-24 06:37:29:236 PST] ScriptApp.getOAuthToken() [0 secondi]
[16-02-24 06:37:29:237 PST] UrlFetchApp.getRequest([https://www.googleapis.com/gmail/v1/users/me/messages, {headers={Authorization=Bearer <<<token removed>>>}, method=GET, payload={"userId":"me",...) [0 secondi]
[16-02-24 06:37:29:308 PST] UrlFetchApp.fetch([https://www.googleapis.com/gmail/v1/users/me/messages, {headers={Authorization=Bearer <<<token removed>>>}, method=GET, payload={"userId":"me",...) [0,07 secondi]
[16-02-24 06:37:29:308 PST] HTTPResponse.getResponseCode() [0 secondi]
[16-02-24 06:37:29:308 PST] HTTPResponse.getContentText() [0 secondi]
[16-02-24 06:37:29:311 PST] Esecuzione non riuscita: Error: Error (400) 'raw' RFC822 payload message string or uploading message via /upload/* URL required (riga 212, file "Test Tools") [0,075 secondi di esecuzione totale]

我觉得我已经接近解决方案,但我无法弄清楚问题出在哪里。 任何帮助都会非常感激

曼努埃尔

【问题讨论】:

  • 仅供参考,有一项 Gmail 高级服务可以消除处理 URL 和身份验证的麻烦:developers.google.com/apps-script/advanced/gmail
  • 我正在清理代码,我发现你是对的。现在我必须了解如何以正确的方式使用高级服务。谢谢

标签: google-apps-script gmail-api


【解决方案1】:

如果您查看documentation,它会说payload 是请求的正文。您的查询不应在正文中,而应在查询字符串参数中:

function GAPIlistMessages(query) { 
  var url = 'https://www.googleapis.com/gmail/v1/users/me/messages?q=' + 
    encodeURIComponent(query)

  var response = UrlFetchApp.getRequest(url, {
    headers: {
      Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
    }
  });
}

【讨论】:

    【解决方案2】:

    感谢cmets,我已经找到解决方案并重写代码:

    function GAPIlistMessages(userId, query) {
      var url = 'https://www.googleapis.com/gmail/v1/users/'+userId+'/messages'+'?q='+query+'&fields=messages%2Fid' // JSON array of message ID
      var headers = {
        Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
      };
    
      var params = {
        method: "GET",
        contentType: "application/json",
        headers: headers,
        muteHttpExceptions: true, // for debugging 
        };
    
      var check = UrlFetchApp.getRequest(url, params); // for debugging
      var response = UrlFetchApp.fetch(url, params);
    
      var result = response.getResponseCode();
      if (result == '200') {  // OK
        var msgIds = JSON.parse(response.getContentText());
        //Logger.log(response.getContentText())
      return msgIds;
    
      }
      else {
        // This is only needed when muteHttpExceptions == true
        var err = JSON.parse(response.getContentText());
        throw new Error( 'Error (' + result + ") " + err.error.message );
      }
    }
    

    现在我可以检索给定查询的所有消息 ID,并将该列表传递给另一个函数以提取附件 + 其他任务。 这种方法的真正优势是我可以处理单个消息,而不是使用简单的 GAS 命令处理整个线程。

    【讨论】:

      猜你喜欢
      • 2016-05-05
      • 2012-07-25
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 2017-07-27
      • 1970-01-01
      相关资源
      最近更新 更多