Search code examples
node.jsfirebasegoogle-cloud-functionsgmailnodemailer

Google blocks login when sending gmail in firebase functions


Im trying to send emails in firebase functions with node and nodemailer but google always send this mail to me. problem alert

This is my code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');

admin.initializeApp();

const transporter = nodemailer.createTransport({
  service: 'gmail',
  host: 'smtp.gmail.com',
  port: 465,
  secure: true,
  auth: {
    user: '*****@gmail.com',
    pass: '******',
  },
});

exports.registerCompany = functions.https.onCall((data, context) => {
  return new Promise((resolve, reject) => { 
    //do somethings
    const mailOptions = {
      from: '[email protected]',
      to: '[email protected]',
      subject: 'New Register Company',
      text: `Company: ${company.name} \nUser: ${user.email}`,
    };

    transporter.sendMail(mailOptions, function (error, info) {
      if (error) {
         console.log(error);
       } else {
         console.log('Email sent: ' + info.response);
       }
    });
  }
}

When I run it on localhost, I don't get the alert or blocking from Google.


Solution

  • It is for security reasons and is not an issue with your code or Firebase Functions.

    When you use your code in your PC, Google has recognized that your PC is a trusted device. When you run your code in another location, server, etc, for security reasons Gmail will block the log in because it is not known if this is you or another person.

    Then, it is necessary to add a permission for Gmail to allow apps login using your account.

    This answer could help you with this:

    Head over to Account Security Settings (https://www.google.com/settings/security/lesssecureapps) and enable "Access for less secure apps", this allows you to use the google smtp for clients other than the official ones.

    Update

    Google has been so kind as to list all the potential problems and fixes for us. Although I recommend trying the less secure apps setting. Be sure you are applying these to the correct account.

    • If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.
    • Sign in to your account from the web version of Gmail at https://mail.google.com. Once you’re signed in, try signing in to the mail app again.
    • Visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If asked, enter the letters in the distorted picture.
    • Your app might not support the latest security standards. Try changing a few settings to allow less secure apps access to your account.
    • Make sure your mail app isn't set to check for new email too often. If your mail app checks for new messages more than once every 10 minutes, the app’s access to your account could be blocked.