Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var fs = require('fs');
- var readline = require('readline');
- var googleApi = require('googleapis');
- var googleAuth = require('google-auth-library');
- var email;
- var verLink;
- // If modifying these scopes, delete your previously saved credentials
- // at ~/.credentials/gmail-nodejs-quickstart.json
- var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
- var TOKEN_DIR = './token/';
- var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
- // Load client secrets from a local file.
- module.exports = {
- verificationLink: function (forEmail, cb)
- {
- fs.readFileSync('./token/client_secret.json', function processClientSecrets(err, content) {
- if (err) {
- console.log('Error loading client secret file: ' + err);
- return;
- }
- // Authorize a client with the loaded credentials, then call the
- // Gmail API.
- var secret = JSON.parse(content);
- email = forEmail;
- authorize(secret, function (auth) {
- getVerificationLink(auth, cb);
- });
- });
- }
- };
- /**
- * Create an OAuth2 client with the given credentials, and then execute the
- * given callback function.
- *
- * @param {Object} credentials The authorization client credentials.
- * @param {function} callback The callback to call with the authorized client.
- */
- function authorize(credentials, callback) {
- var clientSecret = credentials.installed.client_secret;
- var clientId = credentials.installed.client_id;
- var redirectUrl = credentials.installed.redirect_uris[0];
- var auth = new googleAuth();
- var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
- // Check if we have previously stored a token.
- fs.readFile(TOKEN_PATH, function(err, token) {
- if (err) {
- getNewToken(oauth2Client, callback);
- } else {
- oauth2Client.credentials = JSON.parse(token);
- callback(oauth2Client);
- }
- });
- }
- /**
- * Get and store new token after prompting for user authorization, and then
- * execute the given callback with the authorized OAuth2 client.
- *
- * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
- * @param {getEventsCallback} callback The callback to call with the authorized
- * client.
- */
- function getNewToken(oauth2Client, callback) {
- var authUrl = oauth2Client.generateAuthUrl({
- access_type: 'offline',
- scope: SCOPES
- });
- console.log('Authorize this app by visiting this url: ', authUrl);
- var rl = readline.createInterface({
- input: process.stdin,
- output: process.stdout
- });
- rl.question('Enter the code from that page here: ', function(code) {
- rl.close();
- oauth2Client.getToken(code, function(err, token) {
- if (err) {
- console.log('Error while trying to retrieve access token', err);
- return;
- }
- oauth2Client.credentials = token;
- storeToken(token);
- callback(oauth2Client);
- });
- });
- }
- /**
- * Store token to disk be used in later program executions.
- *
- * @param {Object} token The token to store to disk.
- */
- function storeToken(token) {
- try {
- fs.mkdirSync(TOKEN_DIR);
- } catch (err) {
- if (err.code != 'EEXIST') {
- throw err;
- }
- }
- fs.writeFile(TOKEN_PATH, JSON.stringify(token));
- console.log('Token stored to ' + TOKEN_PATH);
- }
- /**
- * Gets the verification link
- * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
- */
- function getVerificationLink(auth, cb) {
- var gmail = googleApi.gmail('v1');
- //call list of emails
- gmail.users.messages.list({
- auth: auth,
- userId: 'me'
- }, function(err, response) {
- if (err) {
- console.log('The API returned an error: ' + err);
- return;
- }
- var messages = response.messages;
- if (response == null) {
- console.log('No messages found.');
- } else {
- //iterates over list of messages
- for (var i = 0; i < messages.length; i++) {
- var msg = messages[i];
- //for each message from the list gets details
- var a = gmail.users.messages.get({
- format: 'full',
- id: msg.id,
- auth: auth,
- userId: 'me'
- }, function(err, response) {
- if (err) {
- console.log('The API returned an error: ' + err);
- return;
- } else {
- //find target email by delivery adress
- if(getHeader(response.payload.headers, 'Delivered-To') == email){
- cb(getBody(response.payload).match('[^<a]* href="([^"]*)"')[1]);
- }
- }
- });
- }
- }
- });
- }
- /**
- * Message parsing helpers
- */
- function getHeader(headers, index) {
- var header = '';
- headers.forEach(function(singleHeader) {
- if(singleHeader.name === index){
- header = singleHeader.value;
- }
- });
- return header;
- }
- function getBody(message) {
- var encodedBody = '';
- if(typeof message.parts === 'undefined')
- {
- encodedBody = message.body.data;
- }
- else
- {
- encodedBody = getHTMLPart(message.parts);
- }
- encodedBody = encodedBody.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
- var res = new Buffer(encodedBody, 'base64').toString('ascii');
- return res;
- }
- function getHTMLPart(arr) {
- for(var x = 0; x <= arr.length; x++)
- {
- if(typeof arr[x].parts === 'undefined')
- {
- if(arr[x].mimeType === 'text/html')
- {
- return arr[x].body.data;
- }
- }
- else
- {
- return getHTMLPart(arr[x].parts);
- }
- }
- return '';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement