使用sendgrid通过Firebase触发器发送电子邮件

时间:2019-07-18 06:28:51

标签: node.js google-cloud-firestore sendgrid-templates

我正在使用Firebase中的onCreate触发器向用户发送电子邮件。我正在使用sendgrid模板发送电子邮件。在Firestore中创建新文档时,它将触发向用户发送电子邮件。

 const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const sgMail = require('@sendgrid/mail');
const SENDGRID_API_KEY = 'SG.ivqQZKFcSdqONZZ7IRtkjA.1RdSs50..kBaQ';
sgMail.setApiKey(SENDGRID_API_KEY);
exports.firestoreEmail = functions.firestore
.document('userAccount/{userId}')
.onCreate(event => {
  const userID = event.params.userId;

  if (userID === undefined) {
    console.log('userID DOES NOT EXIST')
    // This was a deletion event, we don't want to process this
    return;
  }
else{

    console.log(userID )
    return db.collection('userAccount').doc(userID)
             .get()
             .then(doc => {

                const user = doc.data()

                const msg = {
                    to: 'lekha.saraf@nexivo.co',
                    from: 'lekhasaraf09@gmail.com',
                    subject: 'NewFollower',

                    templateId: '8...............d760e',
                    substitutionWrappers: ['{{', '}}'],
                    substitutions: {
                      name: user.UserName
                      // and other custom properties here
                    }
                };

                return sgMail.send(msg)
            })
            // .then(() => console.log('email sent!') )
          }  // .catch(err => console.log(err) )

        });

我得到的错误是:    TypeError:无法读取未定义的属性“ userId”

1 个答案:

答案 0 :(得分:0)

您可以使用.onCreate()方法中的2个参数。创建的文档和事件的快照。

exports.firestoreEmail = functions.firestore
  .document('userAccount/{userId}')
  .onCreate((documentSnapshot, event) => {
      const userID = event.params.userId;
      const documentData = documentSnapshot.data();

我不知道event.params.userId是否适用于Firestore。

如果您需要创建文档的用户的userId,则可以使用const userID = event.auth.uid

如果您需要用户的userId,则将邮件发送给您,应该在文档中写入userId。