receive mail with nodemailer without setting "Allow less secure apps to access"

Viewed 2775

I want to ask something about nodemailer, i make code like

Var client = nodemailer.createTransport ({ 
Service: 'gmail',
Auth: {
User: 'example@gmail.com', // Your email address
Pass: '123' // Your password},
Tls: {rejectUnauthorized: false}
});

And this works, but after successful delivery, when I have to receive email messages that have been sent, I need to enable gmail settings like "Allow less secure apps to access". I do not want to set it.

So how do I send emails from example@gmail.com TO example1@gmail.com, without setting "Allow less secure apps to access" and message directly accept in email box !!??? Or any other plugin that should be added ??

THANX;)

2 Answers

You need to get the access token, you cannot give it statically. googleapis can be user for gmail. for example:

        const { google } = require('googleapis');
        const { OAuth2 } = google.auth;

        const {
            MAILING_SERVICE_CLIENT_ID,
            MAILING_SERVICE_CLIENT_SECRET,
            MAILING_SERVICE_REFRESH_TOKEN,
            SENDER_EMAIL_ADDRESS,
            OAUTH_PLAYGROUND //https://developers.google.com/oauthplayground
        } = process.env;

        const oauth2Client = new OAuth2(
            MAILING_SERVICE_CLIENT_ID,
            MAILING_SERVICE_CLIENT_SECRET,
            OAUTH_PLAYGROUND
        );

        oauth2Client.setCredentials({
            refresh_token: MAILING_SERVICE_REFRESH_TOKEN,
        });
        //>>> get the accessToken
        const accessToken = oauth2Client.getAccessToken();

        
        let transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                type: 'OAuth2',
                user: SENDER_EMAIL_ADDRESS,
                clientId: MAILING_SERVICE_CLIENT_ID,
                clientSecret: MAILING_SERVICE_CLIENT_SECRET,
                refreshToken: MAILING_SERVICE_REFRESH_TOKEN,
                accessToken,
            },
        });

        let mailOptions = {
            from: 'no-reply@blah.com',
            to: 'to_blah@blah.com',
            subject: 'test',
            text: 'test'
        };
        let result = await transporter.sendMail(mailOptions);
Related