Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gmail blocks Nodemailer from sending mail

I am working on deploying my Node.js app. However I am having issues with having the registration email getting sent out.

const transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: GMAIL_USER,
        pass: GMAIL_PASS,
    },
});
......
......
transporter.sendMail({
                        to: newUser.email,
                        subject: 'Confirm Email',
                        html: `Please click this email to confirm your email: <a href="${url}">${url}</a>`
                    });

This works perfectly when I try running it on local host, but as soon as I upload the files to my server and try it, google blocks the sign in attempt, and I get an email saying

Someone just used your password to try to sign in to your account. Google blocked them, but you should check what happened.

Every time, I click the button "this was me", but any future attempts still get blocked.

I have "less secure apps" enabled. Is there a way to whitelist an IP to send from my gmail? or a way to get this working in general?

like image 597
The Traveling Coder Avatar asked Feb 04 '20 03:02

The Traveling Coder


People also ask

Does Nodemailer work with gmail?

Once less secure apps is enabled now nodemailer can use your gmail for sending the emails.

How many emails can you send with Nodemailer?

The default value is 100 which means that once a connection is used to send 100 messages it is removed from the pool and a new connection is created. Set maxConnections to whatever your system can handle.


1 Answers

You have two options.Either you set the access to less secure apps setting to Enabled or you obtain an accessToken and a refreshToken from Google OAuth2.0 and use them in your nodemailer config

  • For option one go to https://www.google.com/settings/security/lesssecureapps
  • For option two go to https://console.developers.google.com/apis/credentials

if you choose option two your config for the transport will look something like this:

auth: {
    type: 'OAuth2',
    user: '[email protected]',
    accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x'
}
like image 98
C.Gochev Avatar answered Oct 03 '22 04:10

C.Gochev