2017-04-19 21 views
0

我必須專門使用請求模塊。 我有刷新令牌以及訪問令牌。我如何使用nodejs「request」庫訪問gmail帳戶中的線程

request({ 
      method: "GET", 
      uri:"https://www.googleapis.com/gmail/v1/users/me/threads", 
      headers: { 
       "access_token": 'access_token', 
       "refresh_token": 'refresh_token', 
       "token_type": 'Bearer', 
       "Content-Type": "application/json" 
      }, 
     }, 
     function(err, response, body) { 
      if(err){ 
       console.log(err); // Failure 
      } else { 
       console.log(response); 
       // done(null);// Success! 
      } 
     }); 

每當我運行這個有一個401錯誤說,需要登錄。 另外我怎樣才能使用特定的查詢「q」,並與請求發送。

回答

0

下面的示例如何?

要使用此功能,請將https://mail.google.com/添加到範圍中,然後在Google API控制檯上啓用Gmail API。如果你已經完成了,請忽略它們。

另外我在腳本中包含「q」。詳細信息是https://developers.google.com/gmail/api/v1/reference/users/threads/list。請檢查它。

腳本:

var request = require('request'); 
request({ 
     url: 'https://www.googleapis.com/gmail/v1/users/me/threads', 
     method: 'GET', 
     headers: { 
      "Content-Type": "application/json", 
      "Authorization": "Bearer ### your access token ###" 
     }, 
     qs: { 
      "q": "from:### mail address ###", // For example, a filter is added by ``from``. 
      "fields": "threads" 
     } 
    }, 
    function (err, response, body) { 
     if(err){ 
      console.log(err); // Failure 
     } else { 
      console.log(body); 
      // done(null);// Success! 
    } 
}); 
+0

感謝它爲我工作 – Avy

+0

歡迎。也謝謝你。 – Tanaike

0

按照NodeJS Quickstart for Gmail。它已經包含了登錄的實現:

function authorize(credentials, callback) { 
    var clientSecret = credentials.installed.client_secret; 
    var clientId = credentials.installed.client_id; 
    var redirectUrl = credentials.installed.redirect_uris[0]; 
    var auth = new googleAuth(); 
    var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl); 

    // Check if we have previously stored a token. 
    fs.readFile(TOKEN_PATH, function(err, token) { 
    if (err) { 
     getNewToken(oauth2Client, callback); 
    } else { 
     oauth2Client.credentials = JSON.parse(token); 
     callback(oauth2Client); 
    } 
    }); 
} 

當您對Users.messages.list Users.threads.list呼叫您可以使用「Q」。它包括JS樣品供您參考:

request = gapi.client.gmail.users.messages.list({ 
      'userId': userId, 
      'pageToken': nextPageToken, 
      'q': query 
     }); 

「Q」只返回匹配指定的查詢信息。支持與Gmail搜索框相同的查詢格式 。例如, 「from:[email protected] rfc822msgid:is:unread」。

相關問題