18

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
Adil
  • 21,278
  • 7
  • 27
  • 54

2 Answers2

41

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: "username@gmail.com",
        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"
    }
)
2

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: "user@example.com",
    clientId: "000000000000-xxx0.apps.googleusercontent.com",
    clientSecret: "XxxxxXXxX0xxxxxxxx0XXxX0",
    refreshToken: "1/XXxXxsss-xxxXXXXXxXxx0XXXxxXXx0x00xxx",
    accessToken: "ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x",
    expires: 1484314697598,
  },
});
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449