Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var fs = require('fs');
  2. var readline = require('readline');
  3. var google = require('googleapis');
  4. var googleAuth = require('google-auth-library');
  5.  
  6. // If modifying these scopes, delete your previously saved credentials
  7. // at ~/.credentials/gmail-nodejs-quickstart.json
  8. var SCOPES = ['https://mail.google.com/'];
  9. var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
  10.     process.env.USERPROFILE) + '/.credentials/';
  11. var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
  12.  
  13. // Load client secrets from a local file.
  14. fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  15.   if (err) {
  16.     console.log('Error loading client secret file: ' + err);
  17.     return;
  18.   }
  19.   // Authorize a client with the loaded credentials, then call the
  20.   // Gmail API.
  21.   authorize(JSON.parse(content), listMessages);
  22. });
  23.  
  24. /**
  25.  * Create an OAuth2 client with the given credentials, and then execute the
  26.  * given callback function.
  27.  *
  28.  * @param {Object} credentials The authorization client credentials.
  29.  * @param {function} callback The callback to call with the authorized client.
  30.  */
  31. function authorize(credentials, callback) {
  32.   var clientSecret = credentials.installed.client_secret;
  33.   var clientId = credentials.installed.client_id;
  34.   var redirectUrl = credentials.installed.redirect_uris[0];
  35.   var auth = new googleAuth();
  36.   var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
  37.  
  38.   // Check if we have previously stored a token.
  39.   fs.readFile(TOKEN_PATH, function(err, token) {
  40.     if (err) {
  41.       getNewToken(oauth2Client, callback);
  42.     } else {
  43.       oauth2Client.credentials = JSON.parse(token);
  44.       callback(oauth2Client);
  45.     }
  46.   });
  47. }
  48.  
  49. /**
  50.  * Get and store new token after prompting for user authorization, and then
  51.  * execute the given callback with the authorized OAuth2 client.
  52.  *
  53.  * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
  54.  * @param {getEventsCallback} callback The callback to call with the authorized
  55.  *     client.
  56.  */
  57. function getNewToken(oauth2Client, callback) {
  58.   var authUrl = oauth2Client.generateAuthUrl({
  59.     access_type: 'offline',
  60.     scope: SCOPES
  61.   });
  62.   console.log('Authorize this app by visiting this url: ', authUrl);
  63.   var rl = readline.createInterface({
  64.     input: process.stdin,
  65.     output: process.stdout
  66.   });
  67.   rl.question('Enter the code from that page here: ', function(code) {
  68.     rl.close();
  69.     oauth2Client.getToken(code, function(err, token) {
  70.       if (err) {
  71.         console.log('Error while trying to retrieve access token', err);
  72.         return;
  73.       }
  74.       oauth2Client.credentials = token;
  75.       storeToken(token);
  76.       callback(oauth2Client);
  77.     });
  78.   });
  79. }
  80.  
  81. /**
  82.  * Store token to disk be used in later program executions.
  83.  *
  84.  * @param {Object} token The token to store to disk.
  85.  */
  86. function storeToken(token) {
  87.   try {
  88.     fs.mkdirSync(TOKEN_DIR);
  89.   } catch (err) {
  90.     if (err.code != 'EEXIST') {
  91.       throw err;
  92.     }
  93.   }
  94.   fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  95.   console.log('Token stored to ' + TOKEN_PATH);
  96. }
  97.  
  98. /**
  99.  * Lists the messages content in the user's account.
  100.  *
  101.  * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
  102.  * @param {labelIds} messages only from this label are displayed
  103.  */
  104. function listMessages(auth) {
  105.   var gmail = google.gmail('v1');
  106.   gmail.users.messages.list({
  107.     auth: auth,
  108.     userId: 'me',
  109.     // labelIds: 'something'
  110.   }, function(err, response) {
  111.     if (err) {
  112.       console.log('The API returned an error: ' + err);
  113.       return;
  114.     }
  115.     var messages = response.messages;
  116.     if (messages.length == 0) {
  117.       console.log('Messages not found.');
  118.     } else {
  119.       for (var i = 0; i < messages.length; i++) {
  120.         var message = messages[i];
  121.         // Get messages content
  122.         gmail.users.messages.get({
  123.           auth: auth,
  124.           'userId': 'me',
  125.           'id': message.id
  126.         }, function(err, response) {
  127.           if (err) {
  128.             console.log('The API returned an error: ' + err);
  129.             return;
  130.           }
  131.           var snippet = response.snippet;
  132.           console.log('- [%s] %s',message.id, snippet);
  133.         }
  134.         );
  135.       }
  136.     }
  137.   });
  138. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement