5

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?

  • If less secure app is not working for you then your best bet is to try the official method: oAuth -- https://medium.com/@RistaSB/use-expressjs-to-send-mails-with-gmail-oauth-2-0-and-nodemailer-d585bba71343 – slebetman Feb 04 '20 at 03:34

3 Answers3

12

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

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

auth: {
    type: 'OAuth2',
    user: 'user@example.com',
    accessToken: 'ya29.Xx_XX0xxxxx-xX0X0XxXXxXxXXXxX0x'
}
C.Gochev
  • 1,837
  • 11
  • 21
  • Do the `accessToken` and `refreshToken` have to be renewed periodically by the server running `nodemailer`? Or do you generate them manually and use them indefinitely? – Clifton Labrum Jan 14 '21 at 19:17
  • 1
    @CliftonLabrum the accessToken must be renewed using the refreshToken. I use the `googleapis` npm package to generate the accessToken using the refreshToken. – aryanm Mar 24 '21 at 16:12
  • 1
    Recently google introduce an app password that can be used to access your Gmail account. - No need to turn on less secure apps in setting - No need to provide any accessToken. – Srujal Patel Apr 24 '21 at 01:19
0

Sometimes people who don't assign recovery email, phone number .In that scenario also google hinders login. In my case google first allowed me on turning less secure app but very next day it denied. So I added recovery email for that particular email and it worked. So that's how I think google security algo works.

-1

Had to fill out some hidden captcha for gmail, then everything worked fine. Sadly dont have the link, or id post it.