Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 968
Μελέτης Πέππας Avatar asked Nov 25 '25 09:11

Μελέτης Πέππας


2 Answers

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"
    }
)
like image 195
krupali makadiya Avatar answered Nov 27 '25 21:11

krupali makadiya


You should check out Xoauth2.

Nodmailer supports serval types of Oauth

let transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    type: "OAuth2",
    user: "[email protected]",
    clientId: "000000000000-xxx0.apps.googleusercontent.com",
    clientSecret: "XxxxxXXxX0xxxxxxxx0XXxX0",
    refreshToken: "1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx",
    accessToken: "ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x",
    expires: 1484314697598,
  },
});
like image 45
DaImTo Avatar answered Nov 27 '25 23:11

DaImTo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!