Skip to content

Instantly share code, notes, and snippets.

@laxyapahuja
Created July 3, 2019 12:06
Show Gist options
  • Save laxyapahuja/cbd967d9b1ff560326085df2a71bbf0f to your computer and use it in GitHub Desktop.
Save laxyapahuja/cbd967d9b1ff560326085df2a71bbf0f to your computer and use it in GitHub Desktop.
GMail API Usage (doc needed)
// Client ID and API key from the Developer Console
var CLIENT_ID = '668438714568-cd8dit8kvrd14tqdl49e3hlmlnlgmdn7.apps.googleusercontent.com';
var API_KEY = 'AIzaSyCL2XxiaMpu6D3z5MqxBLO2cOvdIyDAhiE';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listLabels();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print all Labels in the authorized user's inbox. If no labels
* are found an appropriate message is printed.
*/
function listLabels() {
gapi.client.gmail.users.labels.list({
'userId': 'me'
}).then(function(response) {
var labels = response.result.labels;
appendPre('Labels:');
if (labels && labels.length > 0) {
for (i = 0; i < labels.length; i++) {
var label = labels[i];
appendPre(label.name)
}
} else {
appendPre('No Labels found.');
}
});
}
/**
* 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 listMessages(userId, query) {
var getPageOfMessages = function(request, result) {
request.execute(function(resp) {
// console.log(resp.messages.id);
// console.log(resp.messages.length);
var table = document.getElementById('emails');
table.innerHTML= '<tr><th>From</th><th>To</th><th>Content</th></tr>';
for (var i=0; i<resp.messages.length; i++){
var request = gapi.client.gmail.users.messages.get({
'userId': userId,
'id': resp.messages[i].id
}).then(function(response){
table.innerHTML=table.innerHTML+ "<tr><td>" + response.result.payload.headers[22].value + "</td><td>" + response.result.payload.headers[23].value + "</td><td>" + response.result.snippet +"</td></tr>";
});
}
result = result.concat(resp.messages);
// console.log(result);
var nextPageToken = resp.nextPageToken;
if (nextPageToken) {
request = gapi.client.gmail.users.messages.list({
'userId': userId,
'pageToken': nextPageToken,
'q': query
});
getPageOfMessages(request, result);
} else {
console.log("esle");
}
});
};
var initialRequest = gapi.client.gmail.users.messages.list({
'userId': userId,
'q': query
});
getPageOfMessages(initialRequest, []);
}
/**
* Get Message with given ID.
*
* @param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param {String} messageId ID of Message to get.
* @param {Function} callback Function to call when the request is complete.
*/
function getMessage(userId, messageId) {
var request = gapi.client.gmail.users.messages.get({
'userId': userId,
'id': messageId
}).then(function(response){
console.log(response.result.payload.headers[22].value);
console.log(response.result.snippet);
console.log(response.result.payload.headers[23].value)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment