Search code examples
node.jsoauth-2.0gmailnodemailer

How to send emails with google using nodemailer after Google disabled less sure app option?


I would like to find a way to send email from my app using nodemailer to the users either with some kind of google authentication or any other way. Below mentioned working code has stopped working after Google has disabled less secure app option.

const nodemailer = require('nodemailer')

const sendEmail = async options => {
const transporter = nodemailer.createTransport({
    // host: "smtp.gmail.com",
    // port: "465",
    // secure: true,
    service:'gmail',
    auth: {
        user: "USER_EMAIL",
        pass: "USER_PASSWORD"
    },
    tls:{rejectUnauthorized:false}
})

const message = {
    from: `${process.env.FROM_NAME} <${process.env.FROM_EMAIL}>`,
    to: options.email,
    subject: options.subject,
    text: options.message,
    html: options.message,
    attachments: [
        {
            filename: '.png',
            path: __dirname + '.png',
            cid: '.png'
        }
    ]
}

const info = await transporter.sendMail(message)
console.log('Message sent : %s', info.messageId)
console.log(__dirname)
}
module.exports = sendEmail

Solution

  • At the time of writing, Less Secure Apps is no longer supported by google. And you can't use your google account password.

    You're gonna have to generate a new app password.

    App passwords only work if 2-step verification is turned on. Follow this steps to get the app password

    1. Go to https://myaccount.google.com/security
    2. Enable 2FA
    3. Create App Password for Email
    4. Copy that password (16 characters) into the pass parameter in Nodemailer auth.
    const client = nodemailer.createTransport({
        service: "Gmail",
        auth: {
            user: "[email protected]",
            pass: "Google-App-Password-Without-Spaces"
        }
    });
    
    client.sendMail(
        {
            from: "sender",
            to: "recipient",
            subject: "Sending it from Heroku",
            text: "Hey, I'm being sent from the cloud"
        }
    )