4108

Nodemailer error while using gmail in firebase functions

Question:

I am using firebase cloud functions. I have the following setup configured. While that is working completely fine on my local machine, It's giving me an issue when run on the servers. I have tried gazillion work arounds on the internet but no luck. What is wrong with this?

'use strict' const functions = require('firebase-functions'); var admin = require('firebase-admin'); const express = require('express'); const nodemailer = require('nodemailer'); const app = express() var emailRecepient; var userName; const smtpTransport = nodemailer.createTransport({ service: "gmail", host: 'smtp.gmail.com', port: 587, // tried enabling and disabling these, but no luck secure: false, // similar as above auth: { user: '<emailid>', pass: '<password>' }, tls: { rejectUnauthorized: false } }); var mailOptions = { from: 'test <hello@example.com>', to: emailRecepient, subject: 'Welcome to test', text: 'welcome ' + userName + ". did you see the new things?" }; function sendmail() { smtpTransport.sendMail(mailOptions, function (error, info) { if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); }; exports.sendEmails = functions.database.ref('/users/{userID}/credentials').onCreate((snap, context) => { const userID = context.params.userID; const vals = snap.val() userName = vals.name; emailRecepient = vals.email; smtpTransport.sendMail(mailOptions, function (error, info) { if (error) { console.log("Error sending email ---- ",error); } else { console.log('Email sent: ' + info.response); } }); return true; });

The error I got on all cases is :

Error sending email 2 ---- { Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbsi 534-5.7.14 qRQLfD9YlFZDsPj7b8QQACro9c41PjhSVo0NZ4i5ZHNlyycFi_FyRp8VdZ_dH5ffWWAABQ 534-5.7.14 8rH2VcXkyZBFu00-YHJUQNOqL-IqxEsZqbFCwCgk4-bo1ZeDaKTdkEPhwMeIM2geChH8av 534-5.7.14 0suN293poXFBAk3TzqKMMI34zCvrZlDio-E6JVmTrxyQ-Vn9Ji26LaojCvdm9Bq_4anc4U 534-5.7.14 SpQrTnR57GNvB0vRX1BihDqKuKiXBJ5bfozV1D1euQq18PZK2m> Please log in via 534-5.7.14 your web browser and then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 t2sm3669477iob.7 - gsmtp at SMTPConnection._formatError (/user_code/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/lib/smtp-connection.js:528:15) at SMTPConnection._actionAUTHComplete (/user_code/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/lib/smtp-connection.js:1231:30) at SMTPConnection.<anonymous> (/user_code/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/lib/smtp-connection.js:319:22) at SMTPConnection._processResponse (/user_code/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/lib/smtp-connection.js:669:16) at SMTPConnection._onData (/user_code/node_modules/nodemailer-smtp-transport/node_modules/smtp-connection/lib/smtp-connection.js:493:10) at emitOne (events.js:96:13) at TLSSocket.emit (events.js:188:7) at readableAddChunk (_stream_readable.js:176:18) at TLSSocket.Readable.push (_stream_readable.js:134:10) at TLSWrap.onread (net.js:559:20) code: 'EAUTH', response: '534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbsi\n534-5.7.14 qRQLfD9YlFZDsPj7b8QQACro9c41PjhSVo0NZ4i5ZHNlyycFi_FyRp8VdZ_dH5ffWWAABQ\n534-5.7.14 8rH2VcXkyZBFu00-YHJUQNOqL-IqxEsZqbFCwCgk4-bo1ZeDaKTdkEPhwMeIM2geChH8av\n534-5.7.14 0suN293poXFBAk3TzqKMMI34zCvrZlDio-E6JVmTrxyQ-Vn9Ji26LaojCvdm9Bq_4anc4U\n534-5.7.14 SpQrTnR57GNvB0vRX1BihDqKuKiXBJ5bfozV1D1euQq18PZK2m> Please log in via\n534-5.7.14 your web browser and then try again.\n534-5.7.14 Learn more at\n534 5.7.14 https://support.google.com/mail/answer/78754 t2sm3669477iob.7 - gsmtp', responseCode: 534, command: 'AUTH PLAIN' }

I have even turned of the allow secure apps in the google settings. But for some reason this doesn't seem to work. Any help is extremely appreciated.

As advised by Renaud, I tried firebase-samples/email-confirmation and I am having following error :

TypeError: snapshot.changed is not a function at exports.sendEmailConfirmation.functions.database.ref.onWrite (/user_code/index.js:38:17) at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) at next (native) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36) at /var/tmp/worker/worker.js:758:24 at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Cheers

Answer1:

When you execute an asynchronous operation in a background triggered Cloud Function, you must return a promise, in such a way the Cloud Function waits that this promise resolves in order to terminate.

This is very well explained in the official Firebase video series here: <a href="https://firebase.google.com/docs/functions/video-series/" rel="nofollow">https://firebase.google.com/docs/functions/video-series/</a>. In particular watch the three videos titled "Learn JavaScript Promises" (Parts 2 & 3 especially focus on background triggered Cloud Functions, but it really worth watching Part 1 before).

So you should modify your code as follows:

exports.sendEmails = functions.database.ref('/users/{userID}/credentials').onCreate((snap, context) => { const userID = context.params.userID; const vals = snap.val() userName = vals.name; emailRecepient = vals.email; return smtpTransport.sendMail(mailOptions); });

If you want to print to the console the result of the email sending, you can do as follows:

return smtpTransport.sendMail(mailOptions) .then((info) => console.log('Email sent: ' + info.response)) .catch((error) => console.log("Error sending email ---- ", error)); }); <hr />

Actually there is an official Cloud Functions sample that does exactly that, see <a href="https://github.com/firebase/functions-samples/blob/master/email-confirmation/functions/index.js" rel="nofollow">https://github.com/firebase/functions-samples/blob/master/email-confirmation/functions/index.js</a>

Recommend

  • Google Sheets email once based on cell values
  • How to make a 2D Gaussian Filter in Tensorflow?
  • NetworkX: how to create an incidence matrix of a weighted graph?
  • How to prevent QStringBuilder from outliving the scope it was initialised in
  • JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
  • Contact form problem - I do receive messages, but no contents (blank page)
  • Google Calendar Api is not showing event list
  • Encrypting credit card details using AngularJS in Braintree
  • How to access recipient on sent messages page with mailboxer
  • Dynamically set LESS variables from user settings
  • Replace Fragment with another on back button
  • ASP.NET windows authentication should always ask for credentials
  • testing a POST using phpunit in laravel 4
  • How to concat Pandas dataframe columns
  • Avoid registering duplicate broadcast receivers in Android
  • how to get username into sql trigger when multiple users signed on from asp membership
  • Access object instance inside an event handler
  • Extract All Possible Paths from Expression-Tree and evaluate them to hold TRUE
  • How to get listview position?
  • How to get links to open in the native browser in iOS Meteor apps?
  • 550 Access denied - Invalid HELO name
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Login not working in Firefox in Meteor
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • How do I access an unhandled exception in an MVC Error view?
  • Email verification using google app script and google forms
  • jQuery .attr() and value
  • Email format validation in mvc3 view
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • How to extract text from Word files using C#?
  • How to check if every primary key value is being referenced as foreign key in another table
  • Sending data from AppleScript to FileMaker records
  • Cassandra Data Model
  • sending/ receiving email in Java
  • Invalid access key error using credentials redeemed from an amazon open id token
  • Codeigniter doesn't let me update entry, because some fields must be unique
  • apache spark aggregate function using min value
  • EntityFramework adding new object to nested object collection
  • sending mail using smtp is too slow
  • How to get NHibernate ISession to cache entity not retrieved by primary key