Sendgrid和Firebase功能:发送带有动态模板数据的交易电子邮件时出错

时间:2019-05-07 22:08:23

标签: firebase google-cloud-functions sendgrid

在我的Firebase实时数据库上注册了新的供应商之后,我想通过Sendgrid向新的供应商发送欢迎电子邮件。我已经构建了一个Firebase函数newVendorEmail()来在我的应用程序的functions / src / index.ts文件夹中执行此操作,并按照https://app.sendgrid.com/guide/integrate/langs/nodejs/verify在此处配置所有内容。我还能够通过newVendorEmail()中的onCreate()从Firebase检索供应商详细信息,并将它们传递到msg对象的dynamic_template_data部分,而不会出现任何问题。但是,当在Firebase Functions中触发newVendorEmail()函数时,未发送电子邮件,而是在Firebase Functions Console中收到此响应:TypeError:Object.values不是Mail.setDynamicTemplateData(/ user_code / node_modules / @ sendgrid /mail/node_modules/@sendgrid/helpers/classes/mail.js:342:12)。请帮忙吗?

我尝试升级到最新的@ sendgrid / mail npm软件包v6.4.0,尝试切换到新的Sendgrid API密钥,并尝试按照Sendgrid的github示例https://github.com/sendgrid/sendgrid-nodejs/blob/master/use-cases/kitchen-sink.md将此新API密钥存储在process.env中而不是functions.config(),但无济于事。

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",
  ...
}
...

我希望发送的电子邮件没有任何错误。

1 个答案:

答案 0 :(得分:5)

我有同样的问题。就我而言,解决方案是将Firebase功能从node6切换到node8。