0
votes

I have written code for sending mail from my gmail account to another account by OAuth2. In OAuth2, we need a refreshToken and accessToken generated on https://developers.google.com/oauthplayground/ The accessToken generated by this will expires in 3600 seconds. I want some code that will generate accessToken.

I have written code where i direct put refreshToken and acessToken from this site https://developers.google.com/oauthplayground/ .

//javascript code main file app.js

async function sendEmail() {
    const nodemailer = require("nodemailer");
    const { google } = require("googleapis");
    const OAuth2 = google.auth.OAuth2;

    const smtpTransport = nodemailer.createTransport({
        service: "gmail",
        auth: {
            type: "OAuth2",
            user: "***************@gmail.com", 
            clientId: "***********.apps.googleusercontent.com",
            clientSecret: "*************",
            refreshToken: "**************",
            accessToken: "********************************"
        }
    });

    const mailOptions = {
        from: "**************@gmail.com",
        to: "**************@gmail.com",
        subject: "Hello",
        generateTextFromHTML: true,
        html: "<h1>TEST MAIL SAYS HELLO</h1>"
    };
       smtpTransport.sendMail(mailOptions, (error, response) => {
         error ? console.log(error) : console.log(response);
         smtpTransport.close();
        });
     } 
 sendEmail();

This is working fine but i want that accessToken generated by using some code.

1
In case you are using a web app, take a look at this. - Jescanellas
Thank u Jescnallas, but i want this for server side web apps and i had already read the docs, but do not find a solution. - Shivam Singhal
Have you tried following the 4 steps of the documentation? Could you share in your post what you have tried regarding the oauth tokens? - Jescanellas

1 Answers

0
votes

In order to get the access token and refresh token you will need to enter your credentials at some point in your app. This will require some sort of front end portion. On the back end you will use the auth package in the googleapis node library to take those credentials and generate the tokens you need.

Another way is to make a service account that will send emails on behalf of your account. What is the flow you want, anyone to send an email using Gmail or just yourself?