首页 > 解决方案 > 想要使用 sendgrid 通过云功能发送电子邮件

问题描述

我正在使用云功能向存储在 google firestore 中的数据已更新的人发送电子邮件。我正在使用 sendgrid 发送电子邮件。

我的云功能运行良好,每当我更新数据时都会触发它。但我无法发送电子邮件。

const sendgridemail = require('@sendgrid/mail');
const MY_SENDGRID_API_KEY = '<API key>'
sendgridemail.setApiKey(MY_SENDGRID_API_KEY);
exports.helloFirestore = (event, callback) => {
const triggerResource = event.resource;
console.log('Function triggered by change to: ' +  triggerResource);
console.log(JSON.stringify(event));

 const msgbody = {
                    to: 'laaaf09@gmail.com',
                    from: 'abc@nnn.co',
                    subject:  'database updated - xyzshopping.com',
                    templateId: '<template ID>',
 }
return helloFirestore.send(msgbody)

            .then(() => console.log('payment mail sent success') )
            .catch(err => console.log(err) )
             callback();


};

我已经使用内联编辑器和 zip 上传从控制台部署了代码。它被触发但不发送电子邮件。它向我抛出错误:

错误:getaddrinfo ENOTFOUND api.sendgrid.com api.sendgrid.com:443 at errnoException (dns.js:28:10) at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26) 代码:'ENOTFOUND', errno:'ENOTFOUND',系统调用:'getaddrinfo',主机名:'api.sendgrid.com',主机:'api.sendgrid.com',端口:443

标签: node.jsgoogle-cloud-functionssendgrid

解决方案


您应该callback()仅在完成所有异步工作后才调用。你甚至在工作开始之前就调用它。那肯定行不通。从文档中:

打回来

表示函数执行完成的回调。

您过早地发出了函数结束的信号。您应该只在工作完成后调用它,无论是在异步工作的回调中then还是在回调中。catch


推荐阅读