How to Use GMAIL-API with Node.js Part-3
Congratulations on making it to the final article!
In this article, we will check for mails and open all relevant links in our browser.
To begin with install the following dependencies:
npm install js-base64 cheerio open mailparser --saveNow create a new file Check.js and add the below code:
const {google} = require('googleapis');
var base64 = require('js-base64').Base64;
const cheerio = require('cheerio');
var open = require('open');
var Mailparser = require('mailparser').MailParser;
class Check{
//auth is the constructor parameter.
constructor(auth){
this.me = 'Enter your email id.';
this.gmail = google.gmail({version: 'v1', auth});
this.auth = auth;
}
//Returns the mails in the user's inbox.
checkInbox(){
this.gmail.users.messages.list({
userId: this.me
}, (err, res) => {
if(!err){
console.log(res.data);
}
else{
console.log(err);
}
})
}
}The checkInbox function will check user’s inbox.
Now in the same class, we create a checkForMediumMails function, which will retrieve all medium mails.
//THis function checks for mails sent by medium.
//We attatch a query parameter to the request body.
checkForMediumMails(){
var query = "from:noreply@medium.com is:unread";
this.gmail.users.messages.list({
userId: this.me,
q: query
}, (err, res) => {
if(!err){
//mail array stores the mails.
var mails = res.data.messages;
//We call the getMail function passing the id of first mail as parameter.
this.getMail(mails[0].id);
}
else{
console.log(err);
}
});
}
Google API has a custom query method in which the query is passed in the request object as a string.
from: sender_mail_id is: unread (Retrieve only unread mails)We then store the response in mail array.
If we open all the mails, chrome would crash, so we will only open the first mail in our mail array.
We will now create a getMail function which will parse the mail body and store the links. It takes in the message id as the parameter.
//getMail function retrieves the mail body and parses it for useful content.
//In our case it will parse for all the links in the mail.
getMail(msgId){
//This api call will fetch the mailbody.
this.gmail.users.messages.get({
'userId': this.me,
'id': msgId
}, (err, res) => {
if(!err){
var body = res.data.payload.parts[0].body.data;
var htmlBody = base64.decode(body.replace(/-/g, '+').replace(/_/g, '/'));
var mailparser = new Mailparser();
mailparser.on("end", (err,res) => {
console.log(res);
})
mailparser.on('data', (dat) => {
if(dat.type === 'text'){
const $ = cheerio.load(dat.textAsHtml);
var links = [];
var modLinks = [];
$('a').each(function(i) {
links[i] = $(this).attr('href');
});
//Regular Expression to filter out an array of urls.
var pat = /------[0-9]-[0-9][0-9]/;
//A new array modLinks is created which stores the urls.
modLinks = links.filter(li => {
if(li.match(pat) !== null){
return true;
}
else{
return false;
}
});
console.log(modLinks);
//This function is called to open all links in the array.
this.openAllLinks(modLinks);
}
})
mailparser.write(htmlBody);
mailparser.end();
}
});
}
openAllLinks(arr){
arr.forEach(e => {
open(e);
});
}The response object has many properties, but we are concerned with only the mail body. Hence, we store the body in the variable body.
The base64 module, which we installed earlier, will decode the mail body and store it in htmlBody.
Also we will now use cheerio which is a great module for traversing the DOM Tree. Here we search for all the anchor tags in the mail body and store it in the links array.
Now, if you print the links array, you will see that there are various links- some lead to the articles, some lead to the author’s profile and others to the standard links of various social media platforms. But we only need the links that point to the article. So how do we filter them?
This is where Regular expression comes in.
let pat = /———[0-9]-[0-9]/;
We always define a regular expression within / / . Each link that leads to articles has six consecutive hyphens followed by a digit, a single hyphen and a digit again.
Now we filter the links array and store the result in modLinks array.
Now pass this array in openAllLinks function which uses the open module we installed earlier to open the links in the browser.
To test our code we import the Check.js module into our index.js file
function getAuth(auth){
var Check = require('./Check');
var obj = new Check(auth);
obj.checkForMediumMail();
}And now we execute the command below:
node index.jsWe did it! You can now create a script to parse your emails. 😎
You should now have a good understanding of how to work with Gmail-API. To dive deeper into GMAIL-API, go through the official documentation.