简体   繁体   中英

Sendgrid & Firebase Functions: Error Sending Transactional Email with Dynamic Template Data

Once a new vendor is registered on my Firebase Realtime Database, I want to send the new vendor a welcome email via Sendgrid. I've constructed a Firebase function newVendorEmail() to do this in my app's functions/src/index.ts folder and configured everything there as per https://app.sendgrid.com/guide/integrate/langs/nodejs/verify . I'm also able to retrieve vendor details from Firebase via onCreate() in newVendorEmail() and pass them to the dynamic_template_data part of the msg object without any problem. But when the newVendorEmail() function was triggered in Firebase Functions the email was not sent and I got this response instead in my Firebase Functions Console: TypeError: Object.values is not a function at Mail.setDynamicTemplateData (/user_code/node_modules/@sendgrid/mail/node_modules/@sendgrid/helpers/classes/mail.js:342:12). Help, please?

I've tried upgrading to the latest @sendgrid/mail npm package v6.4.0, tried switching to a new Sendgrid API key, tried storing this new API key in process.env as per Sendgrid's github example https://github.com/sendgrid/sendgrid-nodejs/blob/master/use-cases/kitchen-sink.md instead of functions.config(), but to no avail.

in node/process.env:

{ SENDGRID_API_KEY:
   'SG....E',
...
}

in functions/src/index.ts:

'use strict'

const functions = require('firebase-functions')
const admin = require('firebase-admin')
const sendgrid = require('@sendgrid/mail')

// init function
admin.initializeApp()

//init firebase ref const
const ref = admin.database().ref()

// set sendgrid api from process env
sendgrid.setApiKey(process.env.SENDGRID_API_KEY)

export const newVendorEmail = functions.database
.ref('users/{userId}/profile')
.onCreate((snapshot, context) => {
  // call field data using snapshot.val()
  let msg
  const userData = snapshot.val()
  if (userData.type === 'vendor') {
    // set email data
    msg = {
      to: userData.email,
      from: {
        name: 'Blk. Party',
        email: '...@blkparty.com'
      },
      // custom templates
      templateId: '...',
      dynamic_template_data: {
        subject: 'Welcome to Blk. Party!',
        name: userData.name,
        regLink: userData.regLink
      },
    }    
  }
  // send email via sendgrid
  return sendgrid.send(msg) 
})

in package.json:
...
"dependencies": {
  "@sendgrid/mail": "^6.4.0",
  "firebase-admin": "~6.0.0",
  "firebase-functions": "^2.1.0"
},
"devDependencies": {
  "@sendgrid/mail": "^6.4.0",
  ...
}
...

I expect emails to be sent without any error.

I had the same problem. In my case, the solution was to switch from node6 to node8 in firebase functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM