使用Google API脚本中的Gmail API搜索邮件

时间:2016-02-24 14:41:37

标签: google-apps-script gmail-api

我已经通过StackOverflow搜索了(小)成功,所以我向比我更专业的编码人员提供帮助。

我已经在SO gmailapp-add-label-to-specific-message-not-the-thread上阅读了这个主题,这引出了我GIST,我在那里采用了标记单个邮件的代码(而不是整个帖子)

现在我需要在Google Apps脚本中使用Gmail API的搜索功能;我在Google Developer的网站here上找到了一个Javascript代码段。我尝试使用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 );
  } 
}

当我启动该函数时,传递此参数: userId =' me' query =' deliverto: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]

我觉得我接近解决方案,但我无法弄清楚问题出在哪里。 任何帮助都将非常赞赏

曼努埃尔

2 个答案:

答案 0 :(得分:2)

如果查看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()
    }
  });
}

答案 1 :(得分:1)

感谢您的评论,我找到了解决方案并重写了代码:

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命令处理整个线程。