简体   繁体   English

在用户的GMail收件箱中获取邮件

[英]Get messages in users' GMail inbox

In the code below I am signing in, authorising the app, and getting console output via the GMail API. 在下面的代码中,我正在登录,授权应用程序,并通过GMail API获取控制台输出。 I believe I am getting the threads and thread IDs, but I am not seeing the messages in the console. 我相信我正在获取线程和线程ID,但我没有在控制台中看到这些消息。

I am not getting any errors and I am getting output, just what seems like keys with no values. 我没有得到任何错误,我得到输出,只是看起来像没有值的键。

Here is what the console output looks like: 这是控制台输出的样子: 在此输入图像描述

Here is the code: 这是代码:

var CLIENT_ID = 'YOUR_CLIENT_ID';
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
var USER = 'me';

  /**
   * Called when the client library is loaded to start the auth flow.
   */
  function handleClientLoad() {
    window.setTimeout(checkAuth, 1);
  }

  /**
   * Check if the current user has authorized the application.
   */
  function checkAuth() {
    gapi.auth.authorize(
        {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},
        handleAuthResult);
  }

  /**
   * Called when authorization server replies.
   *
   * @param {Object} authResult Authorization result.
   */
  function handleAuthResult(authResult) {
    var authButton = document.getElementById('authorizeButton');
    var outputNotice = document.getElementById('notice');
    authButton.style.display = 'none';
    outputNotice.style.display = 'block';
    if (authResult && !authResult.error) {
      // Access token has been successfully retrieved, requests can be sent to the API.
      gapi.client.load('gmail', 'v1', function() {
        listThreads(USER, function(resp) {
          var threads = resp.threads;
          for (var i = 0; i < threads.length; i++) {
            var thread = threads[i];
            console.log(thread);
            console.log(thread['id']);
          }
        });
      });
    } else {
      // No access token could be retrieved, show the button to start the authorization flow.
      authButton.style.display = 'block';
      outputNotice.style.display = 'none';
      authButton.onclick = function() {
          gapi.auth.authorize(
              {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false},
              handleAuthResult);
      };
    }
  }


  /**
   * Get a page of Threads.
   *
   * @param  {String} userId User's email address. The special value 'me'
   * can be used to indicate the authenticated user.
   * @param  {Function} callback Function called when request is complete.
   */
  function listThreads(userId, callback) {
    var request = gapi.client.gmail.users.threads.list({
      'userId': userId
    });
    request.execute(callback);
  }

How can I retrieve the from address, subject, and body of the messages? 如何检索邮件的发件人地址,主题和正文? with the GMAIL API in js 使用js中的GMAIL API

**Update: What I am currently working with: ** **更新:我目前正在与之合作:**

listThreads('me', function(dataResult){
    $.each(dataResult, function(i, item){
        getThread('me', item.id, function(dataMessage){
            console.log(dataMessage);
            var temp = dataMessage.messages[0].payload.headers;
            $.each(temp, function(j, dataItem){
                if(dataItem.name == 'From'){
                    console.log(dataItem.value);
                }
            });
         });
      });
   });

When I log dataMessage, I get a 400 error, ' id required '. 当我记录dataMessage时,我收到400错误,'id required'。 When I log dataItem.value, I get a dataMessage.messages is undefined and can not have an index of 0. 当我记录dataItem.value时,我得到一个dataMessage.messages是未定义的,并且索引不能为0。

I'd greatly appreciate help in getting this working! 我非常感谢帮助你完成这项工作!

GMail api in Javascript does not explicit methods to access particular email part - to/from/etc. Javascript中的GMail api没有明确的方法来访问特定的电子邮件部分 - 来自/来自/等。 GMail api in Java has this feature. Java中的GMail api具有此功能。 Gmail api in Javascript are still in Beta. Javascript中的Gmail API仍处于测试阶段。 api list api列表

You still wanna do it: Here is outline: 你仍然想要这样做:这是概述:

Instead of getting list of threads get list of messages: message list 而不是获取线程列表获取消息列表消息列表

Parse message id from json retrieved from previous call, use it with following: message get 从先前调用中检索的json中解析消息id,使用以下命令: message get

Get raw message in URL encoded base64 format. 以URL编码的base64格式获取原始消息。 Decode and parse. 解码和解析。 safe encoding encoding 安全编码 编码

Difficult... You bet... :) 困难......你打赌...... :)

Here's what i did to get the from email id from message 这是我从消息中获取来自电子邮件ID的所做的事情
After calling the listThread() method, i called getThread() method to fetch the from email ID from that thread as following. 在调用listThread()方法之后,我调用了getThread()方法从该线程中获取来自电子邮件ID,如下所示。

listThreads("me", "", function (dataResult) {
         $.each(dataResult, function (i, item) {
           getThread("me", item.id, function (dataMessage) {
             var temp = dataMessage.messages[0].payload.headers;
             $.each(temp, function (j, dataItem) {
                   if (dataItem.name == "From") {
                       Console.log(dataItem.value);
                    }
             });
        });
    });
});

Similarly you can fetch other details from the message. 同样,您可以从邮件中获取其他详细信息。

Reference : JSON Format for the message 参考消息的JSON格式

Like Amit says above you can use messages.list() to get a list of message ids. 像上面的Amit所说,你可以使用messages.list()来获取消息ID列表。 With those you can simply call messages.get() and that will return an email in parsed form and you can get to the headers via message.payload.headers. 有了这些,你可以简单地调用messages.get(),它将以解析的形式返回一个电子邮件,你可以通过message.payload.headers访问标题。 You don't need to get the 'raw' message base64 encoded. 您不需要获取base64编码的'raw'消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM