Get all messages by label from gmail account - javascript

i want to create a reporting tool based on export from google gmail api.
so the main thing i want to do is to retrieve , get all inbox messages by labels from my account in gmail, and display it in custom structure in my custom ehtml document.
i want to do it with php or javascript.
I have made some researches in Google API, but couldn't understand how to start working, from where?
i think it would be nice if could get the JSON data from this urls
Labels
Messages
how can i do it with javascript, what js libs i need to include, how to work with google Api? I have never worked with it before, so can anybody show me some simple full example?

Here is a full example showing how to load the Google APIs Javascript client, load the gmail API, and call the two API methods to list labels and inbox messages. There are a lot of javascript code snippets in the Gmai lAPI docs for each API call, so you can combine the structure of the code below with whatever specific code snippet to achieve what you want.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<div id="content"></div>
<p>Test gmail API.</p>
<script type="text/javascript">
// Enter a client ID for a web application from the Google Developer Console.
// In your Developer Console project, add a JavaScript origin that corresponds to the domain
// where you will be running the script.
var clientId = 'YOUR_CLIENT_ID_HERE';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = 'https://www.googleapis.com/auth/gmail.readonly';
// Use a button to handle authentication the first time.
function handleClientLoad() {
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('gmail', 'v1', function() {
listLabels();
listMessages();
});
}
/**
* Get all the Labels in the authenticated user's mailbox.
*/
function listLabels() {
var userId = "me";
var request = gapi.client.gmail.users.labels.list({
'userId': userId
});
request.execute(function(resp) {
var labels = resp.labels;
var output = ("<br>Query returned " + labels.length + " labels:<br>");
for(var i = 0; i < labels.length; i++) {
output += labels[i].name + "<br>";
}
document.getElementById("content").innerHTML += output;
});
}
/**
* Get all the message IDs in the authenticated user's inbox.
*/
function listMessages() {
var userId = "me";
var request = gapi.client.gmail.users.messages.list({
'userId': userId
});
request.execute(function(resp) {
var messages = resp.messages;
var output = "<br>Query returned " + messages.length + " messages:<br>";
for(var i = 0; i < messages.length; i++) {
output += messages[i].id + "<br>";
}
document.getElementById("content").innerHTML += output;
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</body>
</html>

Related

Create google docs in google drive Javascript

I am creating an application using asp.net mvc and javascript in which I want to create a word document in my drive and view my created document in new tab,
I created a project in developer console and got my client Id and api key
I am unable to find any examples regarding this, below is my code of google docs api which is working fine,
<body>
<p>
Google Docs API Quickstart
</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '<YOUR_CLIENT_ID>'
var API_KEY = '<YOUR_API_KEY>';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ['https://docs.googleapis.com/$discovery/rest?version=v1'];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/documents.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;
});
}
/**
* 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';
printDocTitle();
} 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);
}
/**
* Prints the title of a sample doc:
* https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
*/
function printDocTitle() {
gapi.client.docs.documents.get({
documentId: '1Q0MGsSSqovVRiDadfnq9eCinoBnOuQn4hnh3-pOsbME'
}).then(function (response) {
var doc = response.result;
var title = doc.title;
appendPre('Document "' + title + '" successfully found.\n');
}, function (response) {
appendPre('Error: ' + response.result.error.message);
});
}
</script>
<script async="" defer="" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()" src="https://apis.google.com/js/api.js"></script>
I believe your goal is as follows.
You want to create a new Google Document using Google Docs API with Javascript.
You have already been able to use Google Docs API.
In this case, how about the following modification?
Modified script:
First, please modify your scope from https://www.googleapis.com/auth/documents.readonly to https://www.googleapis.com/auth/documents.
And, please modify your script as follows.
From:
function printDocTitle() {
gapi.client.docs.documents.get({
documentId: '1Q0MGsSSqovVRiDadfnq9eCinoBnOuQn4hnh3-pOsbME'
}).then(function (response) {
var doc = response.result;
var title = doc.title;
appendPre('Document "' + title + '" successfully found.\n');
}, function (response) {
appendPre('Error: ' + response.result.error.message);
});
}
To:
function printDocTitle() {
gapi.client.docs.documents.create({
resource: {title: "sampleTitle"}
}).then(function (response) {
var doc = response.result;
var title = doc.title;
appendPre('Document "' + title + '" successfully found.\n');
}, function (response) {
appendPre('Error: ' + response.result.error.message);
});
}
When this script is run, a new Google Document with the title of "sampleTitle" is created to the root folder.
Reference:
Method: documents.create

Google calendar api JS doesnt work

I use code from official tutorial:
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '930775442242-5dutsv4pa4ibr23c650rcs4upo3v7qad.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/calendar.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({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
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;
});
}
/**
* 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';
listUpcomingEvents();
} 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 the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function(response) {
var events = response.result.items;
appendPre('Upcoming events:');
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
appendPre(event.summary + ' (' + when + ')')
}
} else {
appendPre('No upcoming events found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Therea are two buttons for sign in and for sign out.
Problem: this code doesn't work in firefox (when I click auth button, choose google account then nothing happens) and in chrome (I cant logout).
Maybe there is any error in this code?
How can I solve this problem?
In my console there are not any errors.
Thanks,
For the signing-out process try using GoogleAuth.disconnect(); to revoke the token which was mentioned here.
The calendar API sample is working as intended on my end. Make sure it's enabled in your Google Dev console and the localhost ports are indicated in your clientID

google classroom api to create a course using js

i am new with google classroom api and i want to create a course on local machine. can i do it or not ?
if create then how using javascript ?
as i try ,got an error with code =>403, status="PERMISSION_DENIED" and message=> "Request had insufficient authentication scopes."
in my code i use function createCourse() to create a new course.
my code is below given
<!DOCTYPE html>
<html>
<body>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '782126680600-9kkg23inbnn9sv8ficcvjci2rgrnd648.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/classroom/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/classroom.courses.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({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
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;
});
}
/**
* 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';
createCourse();
listCourses();
} 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 the names of the first 10 courses the user has access to. If
* no courses are found an appropriate message is printed.
*/
function listCourses() {
gapi.client.classroom.courses.list({
pageSize: 10
}).then(function(response) {
console.info(response.result);
var courses = response.result.courses;
appendPre('Courses:');
if (courses.length > 0) {
for (i = 0; i < courses.length; i++) {
var course = courses[i];
appendPre(course.name)
}
} else {
appendPre('No courses found.');
}
});
}
function createCourse(){
var newCourse = {'name': '9th Math','ownerId' : 'me','courseState' : 'PROVISIONED'};
gapi.client.classroom.courses.create(newCourse).then(function(response) {
console.info(response);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
please reply me..........
You have to update your scope from https://www.googleapis.com/auth/classroom.courses.readonly to https://www.googleapis.com/auth/classroom.courses.
According to the document, courses.create requires the following OAuth scope:https://www.googleapis.com/auth/classroom.courses to work.
The scope https://www.googleapis.com/auth/classroom.courses.readonly is used for listing and getting data. If there is a need to create, update you have to use https://www.googleapis.com/auth/classroom.courses to gain full access to the API.
Hope this helps.

local file system access - solutions?

2nd question I've posted. still very new to web programming so excuse my ignorance.
I have a web based javascript which accesses a users Gmail account and downloads attachments to the local downloads folder as assigned in Chrome.
These files are then manually transferred to another directory and an Excel VBA script processes the files.
I'd like to be able to skip the manual transfer step and save the files directly to to the folder that Excel is looking at. I can get the Excel script to move the files but it only works if the user has not changed the Chrome default downloads folder location so it's not foolproof.
I believe this is impossible with javascript but is it possible with other languages or do I need a completely different approach? if it is possible with other languages which one and which methods do I need to be looking at?
This is the download section of the code as it stands at the minute at the request of a user OmegaStripes below:
<html>
<head>Google Drive File Download Process:
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<script type="text/javascript">
var CLIENT_ID = 'XXXXXXXXXXX';//removed for privacy
var SCOPES = 'https://www.googleapis.com/auth/drive';
/**
* 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.
*
*/
function handleAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
var filePicker = document.getElementById('filePicker');
authButton.style.display = 'none';
filePicker.style.display = 'none';
if (authResult && !authResult.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
filePicker.style.display = 'block';
filePicker.onclick = downloadFile; // to allow for manual start of downloads
window.setTimeout(downloadFile(), 5000);
} else {
// No access token could be retrieved, show the button to start the authorization flow.
authButton.style.display = 'block';
authButton.onclick = function() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': false
},
handleAuthResult);
};
}
}
/**
* Start the file download.
*
*
*/
function downloadFile() {
console.log("call drive api");
gapi.client.load('drive', 'v2', makeRequest);
}
function makeRequest() {
console.log("make request");
var request = gapi.client.drive.files.list();
request.execute(function(resp) {
var x = []; //array for revised list of files to only include those not in the trash and those which have a suffix #FHM#
for (i = 0; i < resp.items.length; i++) {
if (resp.items[i].labels.trashed != true && resp.items[i].title.substring(0, 5) == "#FHM#") {
x.push([resp.items[i].title, resp.items[i].webContentLink, resp.items[i].id]);
}
}
if (x.length == 0) {
document.getElementById("filePicker").value = "There are no files to download";
}
for (i = 0; i < x.length; i++) {
console.log(x.length);
var dlUrl = x[i][1];
fileIdentity = x[i][2];
downloadUrl(dlUrl);
trashFile(fileIdentity);
filePicker.style.display = 'none';
document.getElementById("bodyText").innerHTML = "<br>Download " + (i + 1) + " of " + x.length + " completed.";
}
});
//window.setTimeout(function() {
// self.close;
//}, 5000);
}
function downloadUrl(url) {
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function trashFile(id) {
var requestTrash = gapi.client.drive.files.trash({
'fileId': id
});
requestTrash.execute(function(resp) {});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<!--Add buttons for the user to start the process -->
<input type="button" id="filePicker" style="display: none" value="If download does not start after 5 seconds, click here" />
<input type="button" id="authorizeButton" style="display: none" value="Authorize" />
<b id="bodyText"></b>
</body>
thanks
Your code could try to copy the files and if unsuccessful, ask the user to provide the correct path to the extracted file(s). You are right it cannot be done by Javascript. If you want to avoid having to ask the user for the path, you can implement a module to search for the file.
Is there a way you could know whether a file was extracted? If so, you can use this knowledge to know whether the lack of successful copying should trigger a file search or file path requesting.

Access Multiple Google Calendars using Java Script - Google Calendar API

I have this code where I can get the event from my calendar.
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<button id="insert-button" style="visibility: hidden">Insert</button>
<script type="text/javascript">
// Enter a client ID for a web application from the Google Developer Console.
// The provided clientId will only work if the sample is run directly from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// In your Developer Console project, add a JavaScript origin that corresponds to the domain
// where you will be running the script.
var clientId = '823958590548-s5b4d4ngoj6tj2misdvrcdm3rt27jolr.apps.googleusercontent.com';
// Enter the API key from the Google Developer Console - to handle any unauthenticated
// requests in the code.
// The provided key works for this sample only when run from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// To use in your own application, replace this API key with your own.
var apiKey = 'AIzaSyDTqOkVPgBv5kCIqp5NXp7UwE0MKTjLmrU';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = 'https://www.googleapis.com/auth/calendar';
// Use a button to handle authentication the first time.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
var insertButton = document.getElementById('insert-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
insertButton.style.visibility = '';
insertButton.onclick = handleInsertClick;
} else {
authorizeButton.style.visibility = '';
insertButton.style.visibility = 'hidden';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function handleInsertClick(event) {
makeInsertApiCall();
}
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'ashishpandit2312#gmail.com'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
function makeInsertApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.insert({
"calendarId": "primary",
resource:{
"summary": "Meeting",
"location": "Somewhere",
"start": {
"dateTime": "2015-02-21T01:00:00.000-07:00"
},
"end": {
"dateTime": "2015-02-21T04:25:00.000-08:00"
}
}
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
console.dir(resp);
}
});
});
}
</script>
<script
src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<div id='content'>
<h1>Events</h1>
<ul id='events'></ul>
</div>
<p>Connecting to Google Calendar with the Javascript Library.</p>
</body>
</html>
I want to get the events from multiple Google Calendars. What changes should I make to make it work and access multiple calendars of different people?
If you want to access multiple calendars of different people, the best way is to create a service account (which will do all requests to API's on behalf of users). So, users are not prompted with consent screen for authentication for accessing their calendar. Here are the steps:
Create a service account and you as the admin for the domain.
Share all the calendars to this service account.
For the service account to access users data, follow this link for domain wide delegation.
Check this link for service account sample code in java.

Categories