Gmail Api With Node Js: Sending, Reading & More!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone welcome to another session of cod with krishnendu so in this session we will learn how we can perform couple of functionality with Gmail API along with nodejs so let's get started so the very first in terms of accessing the Google apis we need to set up few configurations so that we can get the access on the Google apis in our case that is Gmail API and uh then we can perform the operations whatever we wanted to do so let's first document those steps and gradually we will proceed so first the step one can be we need to create uh Google Cloud project first second step going to be we need to enable the API so obviously for our case it can be a Gmail API right so similarly say say for example I wanted to access any other Google cloudbased API say Google sheet or any other API so whatever the apis we need we need to enable that right then step three going to be we need to configure o consent okay so as we know that O is a type of authentic ation so obviously those apis are not going to be a public API so we need to uh create or the O first and finally the step four is we need to create the access credentials okay so these are the like four like basic and major steps which you need to follow in terms of accessing the Gmail API right so let's uh further let's move further ahead and let's see that how exactly this Gmail API is going to work on okay sorry for that so just let me remove it or yeah so yes so see say for example this is an user so just okay my drawing is not at all good just bear with me so say for example this is one of the user I'm just trying to draw it very quickly right and that user is actually wants to access it Gia so let me create one box here and say for example this is the project that we are going to create on Google Cloud okay so let's say I'm just writing uh identifying for identifier I'm writing that this is my uh Google workspace right this is my Google workspace on which Google workspace means where we going to have our specific project to be created okay let's say under the workxpress I have or I have a project called Gmail playground right so this is the playground now folks what we can understand is like this project can be treat as an interface okay or more often it also been called as like app right so say for example whenever we are trying to handle such kind of operations especially this type of apis which are actually hosted or uh with Google cloud or on Google Cloud so there one interface is required which can actually made a bridge between the client and actual the apis like actual the uh server and the other things like how it can be communicated okay so this project is something which can act as an interface between your code base or let's say your code base or logic whatever you going to write and with the Gmail API for our case it's a Gmail apod Google Cloud okay and to authenticate that so obviously these things are not like anyone can come and access it right it shouldn't be the case so that's the reason we may require this authentications so let's say I'm just writing here that we need uh credentials credentials and moreover that a token also we may require so I'm just uh making it it a bit larger yeah so what it going to do is like first it will try to authenticate that okay whatever the user that uh wanted to access the specific Google apis or Google Cloud apis that user should have a proper authentication already been generated and created right and based on that finally we'll be able to uh connect with our specific applications or the project whatever we going to create on our Google workspace or Google cloud and finally whatever the apis we have been mapped right say for example for our case it would be like Gmail API right so if I just try to write here so for our case it can be like Gmail API okay so this Gmail API which basically going to link through our Gmail playground project or app app with that specific interface we can make a Communications and finally whatever the operations we wanted to perform we can do it right like get the list of emails or probably the sending some emails right or probably if you see the Google Gmail inbox so there are couple of levels are there right like your inbox is a lbel then update is a level promotions is a level social is a level so those list of levels also we can we can actually fetch right so these kind of operations we can actually perform so this is the whole picture a very basic and very straightforward picture that what exactly we need to configure in terms of accessing the Gmail API right now if I just go back to this specific documentation if you see so this is the if you see this specific URL right so this is the very in uh like informative page that Google is already been created that's the workspace guide and Google Cloud console and it's already saying like how exactly we can create a Google project it's a step by step U steps are already been mentioned over here right so at the very first step we will go with this that Google Cloud console and here it is saying like go to create project so I'm just launching it in another tab so once I have clicked on this button then you can see that this specific Google signin page actually appeared and here I need to enter the specific email address on which I I wanted to create the project so this is my email address and the password I'm just entering right so once the login has been successful you can see that finally I'm here finally I'm in the Google Cloud right and it is basically asking me to create a project okay so here you need to define the project so I'm just writing like uh Gmail playground is my is my project so while specifying the project name just be sure that you are not providing or not putting any underscore or something like this because if you do so this kind of eror could come so just uh just be simple like you can just me like maintain this type of format okay and here organizations as this is kind of a learning purpose currently we are using so it's not required no such organization can be selected we can directly click on create right so once we have clicked on the create project you can see that our project is started creating and once the project is created this is the drop down that currently you can see that Gmail playground whatever project we have created that is already been displayed and uh and this type of page we can see okay now get back to the same page let's see what is the other steps are basically same so project name so this step we already have done now in the location click on the browse display potential location of your Bridge yeah so these steps are already been done now second step if you remember so first step whatever we have written that is already done so this is done correct the Second Step that we need to follow that is enable that API so for our case it will be Gmail API so again I'm going back to here in this documentation and if you go come to this part that is the enable Google workspace API right so this is the URL so if you come to this specific page so this page basically talks about like how we can select search API which you wanted to link with your specific project and then gradually we can enable the specific API with our project or interface or app right so it is saying like go to Google Cloud console then menu click on these three lines more products and Google workspace product Library okay so I'm coming to this part and then more products if you see at the below right and if you scroll down so here you have the options called API service [Music] and more options are there right so from this what is the option we need to select let's find it one more time product Library okay so if I just try to find it out why is my product liability so building and then uh this this is the store data storage and if I keep scroll [Music] down yeah so if you see this right so this is the option called Google workspace so first we we clicked on the mode products then Google workpace I'm just clicking on this pin button so it can be like pinned option and finally for from here you need to select the option called Product Library so once you clicked on this product Library so product library is nothing but a specific area where it can show you that what are the products of Google that is being hosted on the Google floud and we can take the access of it so if I just scroll down if you see that Gmail uh is already been populated and all the Google other products are also been displaying here moreover you can also search from here like Gmail if I just type and press enter so it can show you that whatever the Gmail API and API or other things that we looking for right so this is another options anyways I'm just going to the same page and clicking on the Gmail API tiles and now if you see that this screen appeared and finally we can actually click on this enabled button so once once you click on this enabl button if you see that my project is selected as a Gmail playground and what is now now it is doing is like it is basically map mapping the Gmail API with my specific project whatever I have created that is the Gmail playground so right now under this Gmail playground whatever the project we have created you can see this is the option that we can see right now so Gmail API is already mapped but but as we as we have said like So currently the second step is also been completed right so this is the second step now we need to go with configure of O consent and finally we need to create the access credential because that is important so again if I come back to here and let me open one more tab which is called configure o consent so this is the URL again you can see that so for this all the pages are already been documented and provided by Google developers guide itself so now it is saying like configure o consent so in Google Cloud console we need to click on apis and services and need to go to the O consent screen all right so let's get back to our page click on here API and Services I can see and I can see this option called what consent screen so let's click on [Music] this so once I have clicked on this I can see that this type of you like options that you need to specify that what would be my user type whether it's an internal or external so internally is saying only available to users within your organization do not need to submit your app for verification so what is the difference here folks like if we go with internal so what can happen like uh whatever the organization we probably selected at the first right because we haven't select for our case but if we select then what we can do is we can select the internal so for that case what will happen like if we go ahead with the or consent and finally ask uh like Google that okay we wanted to access the specific app for our own purpose right so we do not need to submit the specific application for verification or testing right uh for approval like final final phase of approval but if it is an external then we need to go ahead and we need to submit the app uh for the further test right so that information is already been written over here so if you try to click on this internal we cannot select it because this is disabled I can say and the information showing is like because you are not a Google U workspace user so what we need to do is we can select on the external and click on the create now once you uh once you clicked on the create button so these are the steps you need to complete finally so finally we need to write the app information so some app name then user support email so app name we can just write like Gmail uh Gmail playground app let's say this is my app name g Gmail playground app okay and now we need to provide one user support email so I'm just keeping the same email ID whatever I already had right the same user through which I have logged in here now here that app logo so whatever say for example we are trying to create any mobile app or something so that logo we can add it here if we have any app domain so that thing we can actually specify here right and find developer contact information so this email address are for Google to notify any so let's say the developer contact information also I just wanted to uh keep the same email which is this one okay and finally I'm clicking on the save and continue so once I have clicked on the save and continue now here you can see that Scopes are express permission so if I just click on it so here what you can see like it is basically asking for multiple scope right that what type of scope that you wanted to add with your specific Google um like Google API or Google workspace whatever the uh project that we have created So currently we can just keep it as it is because going forward when we try to link this app with our specific project there we can also Define the SC so I'm just going ahead and clicking on the save and continue now here uh folks we need to add one user for test so what is this if you remember like we have selected external so as we have selected external so that's the reason we need to specify the test user the purpose of test user is while publishing the status is set to testing only test user able to access the app okay so that's the reason we need to add one user over here so for the purpose I'm just adding the same user whatever I have and right now you can see that the user is already been added clicking on the save and continue and finally here is my uh specific summary that you can see right so all those things are already been uh linked up right and finally I'm going back to the dashboard so now my Gmail app is done and all the users and all those things is already been created so our this step is already been done which is configure the oath consent now the final step that is called create the access credential this is also important so to do that I'm coming to this page which is this specific URL and what it is saying that we can actually generate this credential like this so we need to again uh click on these three lines apis and service and credentials if I go back click on here then here API and services then credentials if I do so then this page finally appeared right where I can see that create credential one button is there right so let's follow the steps so next we need to do is like uh click on the create credentials and API key all right so let's create click on the create credentials and go for the API key so once you click on the API key folks what it will do is it will try to generate the API key for for your specific account spe project and it is the recommended that you can actually take it as a copy for the time being you can get it later on as well but I'm just copied it and just keeping it in some other place for forther reference right so now this is done and let's see what else so now we can copy that is done click restricted key update Advanced and for your API key all right and web application okay all right so here you can see that couple of things right click on create so one is like API key that we have already generated right but as we already set up this o consent so what we can do is we can go for the O client ID creational as well so to do that we can create on this here and now we are going to create the O client ID as well because finally once we try to communicate through our specific code base that is the nodejs based scripting then this type of O client ID can help us right so if I click on this so it is asking for what type of application so I'm just selecting web application and the name is like it's it can be like as it is no problem and uh authorized AOSP origin that is fine red URLs so here what I can do is uh I have one redirect water so let's say okay so here author JavaScript origin that is fine for use with request from web server so that is also for the timing let's keep it as it is click on the create so you can see that these are the information that we have got right right so that is this is my client ID this is my client secret and this is the Deb and uh this is recommended that we can actually click on the download G so what it will do is it will basically download a specific G which can contain all the details whatever you can see here so because this St is very much required um going forward it it can help us okay so just keep this information uh with you and and just click on the okay and finally our actual all the steps are actually done now here one thing is like publishing status So currently it is saying is like testing so folks what will happen like going forward if you try to communicate with your specific project from some external Source let's say some script language or like any app that you are building and your if you if your publish status is keep on testing then you won't be able to communicate so for that you need to click on the publish and then finally confirm and if your projects or publishing status turns into in production that means your app is now ready to use right so these are the our we already achieved the final step as well right so this is how we can actually create the Google project we can link a specific API with our created project and finally we can generate the access token right so now the next step going to be write the specific quote with the help of certain nodejs based libraries and try to communicate with our Gmail right okay so now we are going to create the specific logic through which we can and communicate with our Gmail API whatever we have already been created in the Google workspace Cloud so uh to do that first I have already created one project folder called demo and we need to initialize the dependency file that is the package.json file right so that we can install all the required dependen to do that I'm writing command like npm in it and it will start initializing the project so it is saying like the package name is demo so I'm keeping it as it is version as it is description is nothing entry part is all right test command repository author can be the name of my license is as it is and finally I'm just saying is this okay yes right so currently you can see that one package. file is already been created and now we need to add the dependencies uh so in terms of adding the dependencies we actually need the at least two major dependencies uh in terms of um like communicate between the Google apis one is Google API so first dependen we can go to the npm site and here we can just search for the Google API and hit enter so you can see that this is the specific API that we need so we can just just uh copy the specific command and we can go back to our specific uh workspace right here I'm just clearing this up and just hit enter so it will download the required dependency with the latest version whatever it is and the second uh dependency we also need that is Google cloud/ loal that is also here going to be downloaded right so this is already been added as we can see that this is the dependency that is added and second one the dependency that we are looking for that is something called Google Cloud slash uh yeah local Earth this is the one I'm also taking this one so this is actually helping us to communicate with the Google Cloud especially for the authentication so I'm also adding this specific dependency with my project all right so we are all set as part of the dependencies that we can see and now we can see that right now we have two folder that is already been created one is note modules package loation right so here uh just to be segregated probably we can create one folder called services and also if you remember right so whatever the credential file we have downloaded right the G file that is required in terms of accessing or writing the specific code and accessing the specific Google a right so just to manage that also I'm going to create one more not here probably and the root folder itself so let me just relapse this one more package and this name I can see like cred Shield something like this right so here we going to put our specific credential file right so here I'm just creating one file called credentials do Jon right that is the file that we we are having so we're going to put the credential details over here and within this within this specific Service uh we can create a specific Javascript file and the name that we can put is like uh Google API Google API o service do JS okay so here uh we are going to write the specific code which can actually help us to communicate or generate the authentications like author of the token basically whatever we we are going to be required for that so at the very first steps we need to uh we need to call out couple of things which we may required going forward so first we are going to call out the file system because we are going to uh like handle a couple of files and all from the workspace so fs and we are going to write this like require and we need the module called file system that is this fs and the specific promise version we we just wanted to call so that our code can be like synchronized to handle the asynchronized behavior okay second thing that we need that is something called path and here also we are going to call the path Library which is again the native one third thing that we may require that is like const process because we are going to uh handle or we are going to call couple of files and all so that's the reason so again it is also a a native one so process and then we required the specific authentication authenticate authenticate uh authenticate Library from our Google Cloud local art okay so from the Google Cloud local o we we just need to need to have this we need to import this authenticate okay so authenticate as a function which is return going to return wor client as a promise so this is something we are going to be required and finally we need to have Google package as well and that can be imported from Google apis and saving it okay so these are the like major things that we may require so that going forward we can with the help of this we can actually def like generate the token with the help of our specified credentials and finally we can also communicate with the Gmail apis the cloud API okay so now the first thing like once our import part is done now the first thing that we need to Define our scope if you remember while creating the specific project we had a area or segment where we need to define the specify the scope scope means whatever the project that we have created like what exactly the access that we are giving to it right so currently say for example our requirement is to get the email list labels and send send the email right so to to achieve these two things we need to Define two Scopes now if we are getting confused that okay uh from where we can actually identify that what are the scope that we can actually have as part of the Google Gmail API so to to know about more about it so this is the link we can check out and here if you scroll down so here if you see that these are the scope code has been provided and descriptions have already been provided let's take an example let's say this is one of the scope which is ends with gmail. send so it is saying send message only no read or modify privilege on mailbox it's a sensitive sensitive means it's obviously it's reader proper authentication otherwise like we won't be able to uh perform this activity right so this is something we we are going to be uh like we are going to be map as part of part of the scope because we are going to trigger one email and if you see the second scope that is called gmail. readon it is saying read all resources and their metata notion so here we can actually write certain emails we can compose email and send it and here we can read the resources but we cannot like write or compose something okay so very clearly specify the description iions so this two thing we we may reir okay so first I'm just copying this from here going back to our code base I'm just writing the step like Define Scopes okay and here what we need to do is we just need to create a constant maybe like this and here what we can do is we can create an array because it's a multiple scope we are going to Define so first scope can be this and second scope can be gmail. send and Terminator Okay so we are fine with this until this part we defining the scope now the next step going to be right to handle our token and credential right so what we can do what we can do is like Fage and store token from files okay so first we need to so here we can just Define the path of the token file because what is the plan is here we have created one file called credential right and here we going to put whatever the credential that we have got from our specific workspace the Google workspace that we will paste after some time but the thing is like the idea is like once we are going to um generate a specific authentication right so one token going to be generated and token is like dynamic in nature it it's going to have some Lifetime right so one token it's not like always lifetime like it can be exist so it it should be have some lifespan timing so once it is expired so what our expectation is like token file can be generated by itself we do not just need to always generate the token in terms of running our project okay okay so that is why we need to specify the path to tell the code that hey if token change and we are going to generate the token one more time then this is the path you can put the token file token. file and this is the path from where you can read out the credential file because to generate the token we need the credentials okay so that is the reason what we can do is we can write something like token path okay and here we need to take the help of path and then join because we are just trying to read out our specific workspace folder process process do CWD okay and then comma we just wanted to specify our specific location of this credential do so this is basically a credential do and as well as a token so currently we do not have any file called token to J but it going to be generated so where it should generated that path we are going to provide here okay so we can say that that folder we have that is called credentials slash uh in the name of token. J our J file should be generated and stored then the next thing that we need to identify that is called credentials underscore path right similarly we can write path dot sorry it should be like join and then process. CWD and the similar way we can just probably copy this and paste it over here because the location is same only the name going to be changed that is credentials credentials. G saving it okay so we're fing the path of credential file and store path of token file is also been defined now okay the the next part is like to Define certain methods so at the very first what we what method we can write is like the first we will check if our token or uh saved credentials whatever the credentials we are going to save and whatever the token we are going to uh fetch to access the other app right if the token file is already available then we do not need to generate the token file one more time right so the thing is like if my token file is token. is already available that means my token is already there so we do not need to just again and again make the call through the API and generate the token we can reuse the token so that checkpoint to check that we can write one function so we can write one so here I'm in this step I'm defining that um read previously authorized credentials shs from saved file that means if it is already exist then read the specific credential from there okay so to do that we can we are going to create one Asing function okay and the name can be we can put like something like load saved credentials if if exists okay so this is something one method that we are going to write that load the credentials if it is already exist okay we can Define one TR catch over here just to handle any specific error we have okay and if it is error found then we can simply return a null and if there is no such thing happened then we can say that const content equal to a file system dot read file which file we are going to read that is the token that is the token path file right if if it is already exist then here it will come right the concept is like I hope like it is clear right so concept is like if token is is there if token is already present then this block going to be executed or obviously if it is not been found then it will come to the catch block and it will return the null value then we need to handle it like then obviously need to generate a new token file and all we will we will see that gradually right so first content we we going to fish say for example token file is already present now the next part is like credentials okay so credentials also as we need that so credentials means okay say for example we have the already token generated now we need to uh like read that like we already read that file as well now now we need to have the content of the file we need to pass it so that whatever the value the token file going to consider we can access it right so say if that is already been stored in the form of like string then that needs to be converted into the D so to do that we can pass the content into d right so that it it would be easier for us to fetch the values now finally if this operation is succeeded then we can do google. do fromjson and here we to pass the credentials okay so this is the predefined library like whatever we have already been imported so what what this will do is it will automatically take care of this part like whatever the token that we have been uh fetched and then converted into J object and then we are passing it can read it out it can actually map the specified or required uh API and finally perform the authentication right this is one of the useful method that we have already written now we need to go for the second uh type of method so this method is like safe credentials right so now the next set the next method that or next function that we need to create that is like say for example um our uh whatever the credential file that we have created credentials. de so that is also required correct because without having the credential ultimately we cannot just generate the token file right first method is going to handle if our token file is already present then convert it to G object and then finally perform these specific operations with the help of google. but if our credential is not going to be do that then how we can how we can access it right so next method whatever we are going to create that is something uh when we need to again create one assing function and this time the specific method we can say like save credentials okay save credentials now that means like say for example our token file is not there so we need to perform we need to like regenerate the token file right so for that we need to call the specific API which can authenticate and and then finally return the token so that operation we are going to do it okay so here also first again the same type of things so here also we can create a Content which can give us the specific reference of our uh credential path right credential path so that is this file whatever the details we are going to save from save it here and after that what we can do is we can actually F the values from here okay so we can say say for example key is one of the con constant that we have created and again we are basically converting the specific content into CH object so it can be like content and now here to go ahead with the further step folks we need to check out our specific credential file now this is important okay so if you see that whatever the credential file that I had I already take it in the postman body so that it can be like formatted and beautified and we can understand so now if you see carefully and you can also open the specific credential file whatever you probably have downloaded so this is the D file that we are going to get okay and here if you see that that that this specific details is actually uh like referred by one g of object which is called Web okay so if we converted this specific content into J now we need to call out we need to Parts the J with the help of weave object right so that is something we need to keep it our mind right so now if I go back to the code [Music] base right and here so Keys means Keys is nothing but we already part the and save it in in the in the one type of constant variable or constant that is called keys now key say for example one more constant we have created and we are writing that Keys whatever the converted or D object that we have stored within this and we already have seen from our Postman that that can be referred within parent dis of object called Web so that value we are trying to get so it can be like web right so through this parent dis object wave we are trying to call out all the values and trying to save within the key so while I was referring the Google Doc so there one more condition that they have provided that it it may be possible that other than the web as a des primary or parent object it can be like installed okay so I either you can get the all the details of your credentials with the refence of web or it can also be installed it probably for some cases right so we are not taking the chance that's the reason we are also referring that I either or or if wave is found then fine we we going to store all the credential dat details with the help with the Deford of wave itself if if not then we are look going to look for the install these two are the probable kees like probable parent D object that we can expect okay so now as this part is done now we need to create a payload so that we can perform an API operation in terms of generate the new token okay so here the specific payload we need to convert it into the string so d. stringify is the specific method and here we are going to form the payload so what are the details we need to perform what like need to pass as a payload so first we need to write like type like what type of credential type what is the credential type so credential type can be authorized underscore user authorized underscore user second attribute is like what is our client type ID so client ID actually okay this is something we will we will fish with the help of our key so what I can do is so again I'm going back to the postman so this is the client ID our reference object I can also copy it so I can write dot client ID similarly we just also need the client underscore secret okay so just give me some space over here so again going back to here and here is your client secret so do c secret and also one more attribute that is called refresh underscore token and this time we need to pass the refresh token part okay refresh token refresh token we need to pass so it can be like client dot credentials dot refresh token okay so these are the values that we need to pass as part of the payload type client ID client secret and refresh token right because refresh token we need to pass uh in terms of get the token the specific token and finally once we get this once we generate the token right we generate the token what we can do is we can perform and write operation WR file operation why to write the token the same file whatever we already defined right that is the token path correct so token path we just wanted to write what which value we wanted to write that is the payload okay so this is the specific um like safe credential function that we have created where we are just trying to access like if our token is not already there then what we can do is we can generate and finally uh like fet the specific details from our generated uh like authorization client and finally we can capture and store it on the payload and whatever the details we going to get that is our type client ID client secret and refresh token those details we can write into the file called token path which is going to be created automatically in the name like with the name called token d right so this is one like this method is something like if our credential is or token is not already present then this method going to help us to generate the token file now the last and final method which is actually help us to generate the token okay so save credential is not the method which can generate the token it can write the token write and generate the token file to generate the token file token has to be all like has to be like already generated and then it can be write into the file right so finally one more method that we can actually create and this method can the name of this method can be like authorize this is the main method okay and this method is going to help to actually tiet the specific API and then generate the token and Supply it okay so here we going to create one variable called Cent okay client and what it it can do is so client is going to check if our uh specific token is already present or not so if you remember like we already have a method called here which is load SE credentials if exist this is something we going to call out from here and if like token is already present then we do not need to regenerate it again it will simply assign it to client as a variable and to check that we can actually put an condition over here that if client found then what we can do is we can simply return the client right and if it is not found let's say token is not at all generated or probably it is a long long day back we have generated the token or maybe our scope whatever we have defined that is probably change and we we we need to generate a new token then for that case we need to perform this operation so I can say client equal to AET authen authenticate so authenticate is a is a is a function which basically comes from the uh or to client and this is something folks which is basically comes from this specific if you see that this is the authenticate function right we have already imported so here is the actual use okay so now we need to Define that what exactly the things we need to do because here now we are trying to actual access and generate the token because that is not already present or we need it in a fresh fresh token we we requir so now we need to write the Scopes Scopes we need to specify whatever the scope that we already have defined on top of this and also we need to write key one more attribute these are the like standard attribute which is already there as part of the authenticate method that is called Scopes and key file path and here we need to pass credential path okay because without help with the help of credential how we can generate the token okay Terminator and finally we will check if client has the credential because what will happen happen that if client is going to have the like generate the credentials no so credentials going to be an object that client going to going to be stored if it is there then what we can do is we can simply pass this client to our safe credential method so that it can write it so one thing we need to just write it here so if we do so right because if you see that this client we we have been using this client also right so from where it could come so it could come as a parameter so we can write the client over here okay so what will happen that if my authoriz is succeeded and like uh there is no pregenerated token file present then with the help of credential file and with the help of authenticate method it can generate a new token and it can pass it to save credential method and this method can generate a new token file token. file with this specifi details okay and if it is already present and that is something like not required to generate newly so then it is very easy it will check and return the similar client whatever you already have we are not going to write it again and again right and finally we can return client and save okay so this is what we have so far the method and this three methods can perform all the jobs starting from the like all the job in the sense your authentication related jobs okay so now what I can do is we can just try to uh make the call of it so we can say authorize this is the method that we have and Dot then console do log and we can just say that client and we can say maybe this one if we have so something like this okay trying to call it up and now what I can do is I can just copy this whatever I have my credentials and I can open this file and I can put it over here right and now if I go to the terminal and just clearing the screen and try to get into the surfaces folder right so surfaces folder and I can try I I I can just try to run this file let's see how it works so it is saying client is not defined okay okay let's see is not okay fine I can say that uh token generated something like this again creting up and try to enter so let's try to redun this project so we can write like uh note Google service. JS and pressing the enter So currently okay so let's uh try to execute this program and see so we can execute like node and then Google service or o service for JS and once we press enter you can see that our browser is actually launched and it should give me the specific um area where I can actually allow my app but it is saying that 400 mismatch could the problem okay so it is saying that you can't sign in into the app because it doesn't comply with this policy okay okay all right so folks actually we need to make a small change over here so if you remember like while generating the access token there is a portion where we need to add the redirect right and I remember like somehow we missed it right so let's add this so this is the call back URL that I have actually added so I'm going back to my browser and here so here we we have this o client already created right so here if you come click on this ad icon and here this is the option that we actually need to add which uh somehow we skipped it initially so add URI and now if I click on the save so it is already been saved and let me just close it try to reexecute our program so I'm just clearing up and trying to re execute so this time again I could see the browser loaded and this is the user uh account so if I click on it and it is I need to click on the anuns in terms of giving the access so go to Gmail prown app click on it and need to select all this option click on continue so once you click on continue folks if you if you get this screen that authentication successful that means our connection with g Gmail API through our specified account is now succeeded right and if you come back to the specific code base so our code execution completed moreover you can see that one new file called token. is already generated it was not there initially isn't it so if you open that so whatever the payload that we have set right that type client ID client secret and this refresh token going to be there that means our connection is succeeded our authentication is succeeded and we all set to communicate with our further Gmail apis in terms of getting all the details and sending emails right and one more thing is like this token. J whatever the token we have got cor that is a refresh token and all it will be like there it will be there for certain time and if we make some changes in this scope or probably we just wanted to uh in between you just wanted to generate the new token you can delete this token. J file and reexecute your code all you need to do is one new browser window will open and we need to reauthenticate there okay and like that finally we'll be able to generate a new token file okay so now we need to uh write the specific code base through where through which we can actually communicate with the actual Gmail account and get the details okay so now uh so far we have already generated the O token we have generated the token. and that is sorted right so going forward we're going to create one more file over here under this surface folder and this time the service name can be like it is going to be a specific Gmail API so the name can be like Gmail API Services let's say do JS right okay so now uh what what is the plan is like the this time we are going to talk with the Gmail apis okay so to do that first we need this Google to be imported and we can write like this should come from theal apis right right so this would come from the Google apis as an import so that we can actually perform uh the specific gmail apis which comes within this Google apis itself right now first what we can do is we can create a Asing function which can help us to get the labels okay so let's say this is my email account that currently we are targeting to communicate with and you can see that we have couple of labels over here right this is the labels then chat is the level important R and those are the levels So currently what we are trying to do is we going to create one function like programmatically we're going to fetch what about the levels that currently showing within this uh account called demo user 2306 right so to handle this we need to write certain code so let's start so first we will start with like Asing function and the and the method name that we will give that is called let's say list of levels okay and here we going to expect the authentication because without having the authentication we cannot proceed ahead right now we will supply it later on so first we're going to create one constant called let's say Gmail and here uh how we can assign the specific Gmail attribute here so Google UT can help us to Google dot Gmail can come and within this we need to specify the version so version can be V1 and we also need to specify the authentication whatever we going to get as part of the parameter or argument of this method or function okay so this is done second thing that we need to capture the rest response so let's say we have created one constant called res and one a uh Gmail dot users do labels dot we are trying to Fitch the list of levels and what exactly we are doing going to do so here we need to pass the user ID and there is a by default keyword called me so if you write the me keyword so Gmail will will automatically understand that currently with which account we are uh like making the connection with our o it will automatically take this part so we do not need to specify any other user ID it can be only me okay it's a default thing standard behavior of this API now as we got the response finally the list of levels whatever the levels we have got the list response we have saved within the constant called response now it is the time to check the data and F the data of the list because that's actually saved in the uh object and now we need to fetch the data out of it okay so to do that we can create one more constant called levels and here we what we can do is rest. data do labels this is something we can write it here and now we can check if my labels if if label is not generated or if the labels length is equal equal to zero then what we can do is we can say that console do log some message we can print okay so if something happen that my label is not at all generated or probably the level whatever we have got the length is zero then we can say that no labels are found right and we can simply return like nothing we can simply exit from this condition so we can say that return and if and else if something happens that okay we actually get the actual all the labels and our function is work as expected so we can just pin some message over here so console. log we can write labels sorry labels and after that we can run a for each loop on top of the levels so labels do for each right for each and for each on which we need to perform the forage so that can be refer with the label and now one Arrow function we can start and here we can actually print this console. log and the labels and finally we can just write so labels and we just say for example we just wanted to print a specific level name so name name of the levels right and if we just wanted to format it a bit more so we can just pass it like this so I just wanted to pass it concatenate one hyphen and I just wanted to say that whatever the level I going to get each and every level should start with one hyphen okay one hyphen it should start and finally I just wanted to return these levels okay makes sense that how exactly we are calling up this uh like uh we are creating the list of level function Asing function and we are trying to print through this function right so now as this function can be like a reusable function so we just wanted to export it so for that we can write module. export right equal to we can say that list of levels and similarly Google uh API O So this service from this also we need this authenticate or authorized method to be exported so we can write like module. export authorize this is the method that we can export it right and finally in the in the root folder if we just wanted to create one file just to check it maybe [Music] index.js and from here what we can do is like we can simply call out the specific uh methods whatever we have so we can say that const authoriz equal to require and we to all out the file so it's it is there in My Demo slash Services slash this is the off service and similarly I have list of labels and similar way I can simply import this file but this [Music] time it could be like something else so it should be under the services and the Gmail APS Serv okay and once we have this uh what we can do is like we can simply uh call out the methods right so what I can do is I can simply create an Asing function and function and function name I can write like test or testing something like this should be like function and here we can call out with let's say let o equal to AET because we have already defined the Asin so we can call out the AET and it can be like author right authorize and Dot then and if something happen then we would like to catch the error also so console do error right and once we get this finally we wanted to call the list of labels and we need this all as a parameter and then if something happen some so we just wanted to uh catch the error okay this is something we have got and finally we can just call out this method called testing and something happens like so okay so this is something we have all out and now if if we just open a new terminal and we are under this demo just checking so we have this index outside itself sorry clear now we can write node and index.js okay it is saying I'm not red so we are currently getting this error that is called 41 unauthorized so what could be the reason let's try to find it out so if you scroll up we can see that login required and it is saying something like cannot find the module called credential doj so it looks like that whatever the path we have provided uh in the Google API or service somehow um our code unable to find this file and that's the reason credentials won't be able to generate right so let's see what is the problem okay so I have put two dots over here and if I try to travles shoot then it is referring content SL credentials but if you see that after content it should comes under the demo that is the pent folder and then so this is the problem so what I can do is I can simply remove this two dots saving it again coming back to the terminal trying to clear and again executing this awesome so now I can see that I'm actually able to get all the labels of my email box right so if I go back so these are the labels that that is there and similarly we have got chat send inbox important under started category social so all these things we are actually getting right so this is how we can actually fetch the labels or list of levels of your specified Gmail account okay now the second or the other things also we can actually perform we can actually see we can actually now try to send an email okay with the help of the same configur so now we can write uh one more function so which which can help us to send and new email okay so in the current situation we can see that currently we do not have anything in our inbox okay and the expectation is like once we try to uh once we have developed the specific uh method or function and once we execute that if it works as expected so we we should be able to see some sort of message over here okay so let's see how we can do it so again we can create an Asing function and Asing function name can be like send email again Au is common this is required okay send email Au is common similar type of configuration again like Gmail equal to the same type of thing that is Google do Gmail and within this we need to pass version version can be like V1 comma or this is important after that once we get this now folks uh we need to configure the uh message body okay because obviously uh if we try to compose something then that needs to be passed as part of the the uh request body right so what we can do is we can actually provide one more parameter over here and that can be like content so content in the sense what exactly user wanted to send as part of the email okay so here and one more thing is like our Gmail right that is something like if you just pass this normal string or something it may not be able to understand so we need to convert it into base 64 encoded version right so to do that what we can do is we can write const encoded message maybe one constant we have created and here we need to call out buffer Dot from to format that whatever the content we want to get do two string because that needs to be converted into base 64 encoded version and now we are just write some replace mechanism so I'm just copying from my other place because I'm unable to just remember it properly so I can simply say that this is the replace format let's say if we have because we are going to we are going to pass the content in the form of string okay so if the string is content in is like like slash back slash or something like this or any hyphen which which may not be required additionally so we just wanted to make sure that we are replacing all those characters right so now once it is done so now it is very uh simple so cons one more time and rest again we're going to save the response right as we have done in our previous uh previous code also so here we need to write AIT again gmail. user. send do users do sorry do user. messages do send and then we need to pass what user ID again common M so it will automatically understand and request body because we need to compose the email and that type the attribute under this request body should be draw and what we need to pass is like we need to pass our encoded message over here okay encoded message we need to pass once this is done we can simply just to check whether our uh message is actually sent or not we can say that rest whatever the rest we have stored dot data and we can also return it for further use so rest do data okay very simple send email is the method and it expect um two parameters one is authentication one is content this is the uh method implementation so with the help of Google and Gmail part we are convert we are processing it we are mentioning the version we are passing the o we are forming the content converting into base 64 and finally as a response we are segregating it and then if the call has been made through this successfully then we could we are expecting some data right as part of this and then we are returning so as the method count is now increasing sorry what we can do is we can just simply say that you can start a body over here you can say list of labels and then list of labels and send email sorry send email can contain send email okay and now if I go back to this as we have the multiple methods to be exported so we can put like this and say that send email over here right so now one thing that we need to uh configure that is the message body so that is something uh very important okay so here what you can do is after this o you can say that let message and this is the thing folks which is like completely a string body so just just for the purpose what I can do is like I can simply copy and paste this one okay so I'm just changing this email address to my email address that is demo user 236 gmail.com let me rify my email address yes and the test email is something that I just wanted to send email content type can be / HTML and it should be C set is UTF 5 and 8 then some new line and the message is like Hello World right and once we are done with it we can actually call out our send email method or function we can pass the O as well as the message and finally we can say that if we got something then we just wanted to print okay so right now I'm just uh commenting out this list of level uh method or function because we just wanted to check whether our send email uh function is actually working as expected or not so I'm clearing it and Hing up this one so as you can see I have got this message ID and the labels also that means we can expect that our message is actually sent successfully so let's uh verify by navigating our Gmail account so if I come back here try to refresh it yes awesome so we have got the specific email this is the uh subject line This is the user that we have actually configured and this is the body that we are getting right so with this we actually learn that how can how we can actually send the email with the help of Gmail API and specific function in our uh like next implementation what we will try to do is we will try to get the message at least one of the the very first message of our inbox so so far we have uh created function to get the labels send the email and now it's time to read the message okay that is something we will Implement now so now we we going to create another function which can help us to fetch the latest message of our inbox okay so let's see that so again we're going to create one Asing function uh function and sorry this should be like asnc and we can say that get latest message okay again or is something we are trying to get from the user and now what we can do is we can actually uh write the same type of configuration whatever we have done so far so again const Gmail equal to Google do Gmail in the body version it should be like V1 and then comma and then off we can pass and then we can also say that uh so this is done Gmail part is done now response right so const rest equal to again AET and then the similar way that is called Gmail dot users dot messages Dot and this time we just wanted to fetch the list of the messages so list and we need to start the body okay now we need to specify certain parameters over here so one is obviously that is user ID that is kind of a common for all of the functions second is the max result is something we wanted to Define because this method purpose is like we wanted to get the latest message only the latest message of our inbox that's the reason the max result we have uh said that the max result we would like to get from this function is only one okay now if You observe our same message uh response right so if you see that once message has been sent from the body we are actually getting the ID that means ID is very crucial in terms of identifying the message okay so that's the reason we need to capture the message or latest message ID so we can say that latest message ID and how we can get the latest message ID so like this we can get so rest we can say rest. data so in our send email we are saving the rest. data right so here we are writing rest. data and then do messages so it's an add so we are targeting to F the very first one so that's the reason zero and ID very simple we have got it and just to be ensure that we are actually getting the ID of the latest message we are printing it so we can say that um this one you can say that latest message ID is dollar and then bracket you can say that latest message ID okay saving it so until this point it is kind of uh like clear to us okay so latest uh message ID is something that we have got right and now uh message ID that we received now the we wanted to fetch the content of the message okay so to do that what we need to do is we need to create one more constant uh constant we can say that message content say for example equal to again a function need to call we need to call out the Gmail do user do messages do instead of list we can call out get okay because we wanted to get the content of the message and this time we need to to pass again two things one is user ID second thing is message ID here need to pass the latest message ID whatever we have faced in the line number 45 okay so this part is also done so once we have got this we have got this specific message content we can convert this we can say that body and we can convert this specific message content uh into the into the string okay so we can say that Jon do stringify and message content so message content is a whole object that we could get but let's say we just wanted to see the message body data only right so it could contain subject and all those things to do that we need to like purse this entire object so we can say dot data dot payload okay dot body and Dot data okay so by this we can actually get the content of the body and finally if we try to console it so what we can get right so this is something we have got let's say okay and now as our our one more function has been inre so we can just simply export it so we can say that this is something we wanted to export so one more function we can add it here right and this time we just wanted to comment out the same email because that is already uh been checked we just wanted to check one more method so get latest message which is expecting the O and Dot catch for any certain eror if we get so error and Terminator and now if we just clear our terminal or console and just try to execute this so if you see folks this time the uh latest message ID that we are getting that is this one and the body is something we are getting in this format okay so it is not like a proper sting format that we are getting now if we if we go back to the service and if we just try to re understand this send email if you see that in this send email method or function we actually converted our content into the base 64 version that means whatever the value you going to get that is also in the format of Bas 64 and we need to convert it the a human understanding format okay so that's the reason we need to add one more line here to understand the message body and we can say that let mail body equal to equal to new buffer Dot from so we have stored this one so body comma base 64 Dot two string okay once we have done it if we just now try to log this mail body and also try to return it for further use and now if we try to run our program so what we we could get see so we are getting the latest message ID we are getting the encoded message and as well as the decoded message which is hello world right so that's what we have seen here correct so this is the only uh currently only message that we are actually having in our inbox that is this one test email and the content is hello world and that's what we are getting after decoding as well right this is what we are getting okay so this is the this is the like this is all as part of this entire session so if we just try to segregate what exactly we have learned from this session so first we try to we understood like how we can create a project on Google Cloud workspace how we can enable Gmail API how we can generate the access token how we can generate the Google authentication programmatically how we can handle Gmail API function functionalities the basic kind of a basic functionalities like the list of levels we can get how we can get the how we can uh get the message body and how we can send an email right so that's all as part of this session and I hope uh you like it and uh like you got benefited throughout this uh knowledge share right so thanks for watching
Info
Channel: CodeWithKrishnendu
Views: 1,380
Rating: undefined out of 5
Keywords: #nodejsproject, #javascript, #gmail, #googlecloud, #sendemail, #nodemailer, #googleworkspace, #oauth2, gmail api
Id: WaPaYlXbVHs
Channel Id: undefined
Length: 95min 27sec (5727 seconds)
Published: Sat Nov 04 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.