To send emails securely through gmail with a web application, you need to use the Gmail API and OAuth 2. This blog will teach you how to obtain credentials for your project.
Google cloud platform
We must first register with our google account on the google cloud platform. So, head over to console.cloud.google.com where you can sign in / sign up. After doing so, you have to create a new project by clicking on the Select project button on the top navigation bar
Next, we can name our project and assign it a location. With that done, our new project will be created
Setting up the consent screen
First, we will set up our OAuth consent screen that can be found when hovering over the API and services button
Select the External radio button and then fill in details about your application. Leave the scopes and optional info page with the default configurations.
We will now create our credentials that will eventually be used in our code for sending emails securely. Open the hamburger menu and hover over the API and services button. From there, select the credentials button to open the credentials page
Here, we will click on the Create credentials button and select the OAuth client ID option.
Select web application from the dropdown menu for the application type field. Then, name your application.
An important step is to scroll down and enter the following link in the redirect URI input: developers.google.com/oauthplayground.
Click on the create button
Now, you will have access to your client ID and client secret values. Make sure to copy and store them safely — they will be needed for the next step.
You must now navigate to developers.google.com/oauthplayground — the link you provided as the redirect URI earlier. Then, in the Select & Authorize APIs dropdown, input the following text: mail.google.com. In the settings button, tick the 'Use your own OAuth credentials' check box and enter the client ID and secret previously copied.
Click on the Authorize APIs button now.
If after selecting your gmail account you get the above error, return to the OAuth consent screen and add your own email ID as a test user.
Now, if you provide your app permission to read and compose emails, you will be returned to the OAuth playground page where an authorization code will be provided. Exchange this code for a refresh and access token.
Congratulations ! You have now received all the necessary credentials. Refer to the following blog to understand how you can use the data obtained to send emails securely:
Thank you for reading and happy coding !