【发布时间】:2016-08-04 03:18:01
【问题描述】:
我正在尝试使用 gmail api 从 gmail 获取消息列表。在获取消息 ID 列表后,我试图通过传递我在第一步中获得的消息 ID 来获取消息内容。但我无法成功从消息 ID 获取消息。
<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>
【问题讨论】:
标签: javascript gmail-api