javascript - 在 gmail api 中从 'message id' 获取消息

标签 javascript gmail-api

我正在尝试使用 gmail api 从 gmail 获取消息列表。获取消息 ID 列表后,我尝试通过传递我在第一步中获得的消息 ID 来获取消息内容。但我无法成功从消息 ID 获取消息。

<p></p>

<p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <script type="text/javascript">
      // Your Client ID can be retrieved from your project in the Google
      // Developer Console, https://console.developers.google.com
      var CLIENT_ID = 'myclientId';

      var SCOPES = ['https://mail.google.com/'];

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

      /**
       * Handle response from authorization server.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.
          authorizeDiv.style.display = 'none';
          loadGmailApi();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
        }
      }

      /**
       * Initiate auth flow in response to user clicking authorize button.
       *
       * @param {Event} event Button click event.
       */
      function handleAuthClick(event) {
        gapi.auth.authorize(
          {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
          handleAuthResult);
        return false;
      }

      /**
       * Load Gmail API client library. List labels once client library
       * is loaded.
       */
      function loadGmailApi() {
        gapi.client.load('gmail', 'v1', function(){
            listMessages();
            getMessage();
        });
      }

      /**
       * Print all Labels in the authorized user's inbox. If no labels
       * are found an appropriate message is printed.
       */


        var msgIds = [];
        function listMessages() {
  
       var request = gapi.client.gmail.users.messages.list({
          'userId': 'me',
          'q': 'from:xxxxx@xxxx.com'
        });
            request.execute(function(resp){
                var msg = resp.messages;
                if(msg.length>0){
                    for(i = 0; i < msg.length; i++){
                        
                        var msgid = msg[i];
                        msgIds.push(msg[i].id);
                        appendPre(msgid.id);
                    }
                    
                }
                }); 
            }
     
 function getMessage() {
    
  var request = gapi.client.gmail.users.messages.get({
    'userId': 'me',
    'id': msgIds[1];
  });
  request.execute(function(resp){
  var msgSnippet = resp.messages;
      
      if(msgSnippet.length>0){
          appendPre(msgSnippet.snippet);
      }
      else{
          appendPre('no message found');
      }
  
  });
}
  
   

        
        
      /**
       * Append a pre element to the body containing the given message
       * as its text node.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

    </script>
    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to Gmail API</span>
      <!--Button for the user to click to initiate auth sequence -->
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html></code></pre>
</div>
</div>
<p></p>

最佳答案

snippet 仅是消息的前 100 个字符。要获取 text/plaintext/html 部分,您需要遍历 payload 并查找具有正确 的部分mime类型:

var response = {
 "payload": {
  "parts": [
   {
    "mimeType": "multipart/alternative",
    "filename": "",
    "headers": [
     {
      "name": "Content-Type",
      "value": "multipart/alternative; boundary=001a1142e23c551e8e05200b4be0"
     }
    ],
    "body": {
     "size": 0
    },
    "parts": [
     {
      "partId": "0.0",
      "mimeType": "text/plain",
      "filename": "",
      "headers": [
       {
        "name": "Content-Type",
        "value": "text/plain; charset=UTF-8"
       }
      ],
      "body": {
       "size": 9,
       "data": "V293IG1hbg0K"
      }
     },
     {
      "partId": "0.1",
      "mimeType": "text/html",
      "filename": "",
      "headers": [
       {
        "name": "Content-Type",
        "value": "text/html; charset=UTF-8"
       }
      ],
      "body": {
       "size": 30,
       "data": "PGRpdiBkaXI9Imx0ciI-V293IG1hbjwvZGl2Pg0K"
      }
     }
    ]
   },
   {
    "partId": "1",
    "mimeType": "image/jpeg",
    "filename": "feelthebern.jpg",
    "headers": [
     {
      "name": "Content-Type",
      "value": "image/jpeg; name=\"feelthebern.jpg\""
     },
     {
      "name": "Content-Disposition",
      "value": "attachment; filename=\"feelthebern.jpg\""
     },
     {
      "name": "Content-Transfer-Encoding",
      "value": "base64"
     },
     {
      "name": "X-Attachment-Id",
      "value": "f_ieq3ev0i0"
     }
    ],
    "body": {
     "attachmentId": "ANGjdJ_2xG3WOiLh6MbUdYy4vo2VhV2kOso5AyuJW3333rbmk8BIE1GJHIOXkNIVGiphP3fGe7iuIl_MGzXBGNGvNslwlz8hOkvJZg2DaasVZsdVFT_5JGvJOLefgaSL4hqKJgtzOZG9K1XSMrRQAtz2V0NX7puPdXDU4gvalSuMRGwBhr_oDSfx2xljHEbGG6I4VLeLZfrzGGKW7BF-GO_FUxzJR8SizRYqIhgZNA6PfRGyOhf1s7bAPNW3M9KqWRgaK07WTOYl7DzW4hpNBPA4jrl7tgsssExHpfviFL7yL52lxsmbsiLe81Z5UoM",
     "size": 100446
    }
   }
  ]
 }
};

// In e.g. a plain text message, the payload is the only part.
var parts = [response.payload];

while (parts.length) {
  var part = parts.shift();
  if (part.parts) {
    parts = parts.concat(part.parts);
  }

  if(part.mimeType === 'text/html') {
    var decodedPart = decodeURIComponent(escape(atob(part.body.data.replace(/\-/g, '+').replace(/\_/g, '/'))));
    console.log(decodedPart);
  }
}

关于javascript - 在 gmail api 中从 'message id' 获取消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38751852/

相关文章:

JavaScript - 如何使用 EXIF 数据在网络摄像头中拍照?

javascript - HTMLSpanElement 与 HTMLUnknownElement

javascript - ImmutableJS 会跳过未使用的代码块吗?

hyperlink - 在浏览器窗口中打开在 Gmail API 中创建的 Gmail 草稿

javascript - 显示一个隐藏的元素 jquery

javascript - 如何抑制 SonarQube JavaScript 问题

google-api - user.messages.get 响应无效 ID

curl - 400 错误。需要收件人地址。 curl

javascript - gmail api使用html中的内容发送电子邮件

android - 在 logcat 中显示额外的 Intent