首页 > 解决方案 > Firebase Cloud Functions - 发送电子邮件时出错

问题描述

我需要通过 HTTP 请求向 Firebase Cloud Function 发送电子邮件。我使用 Sparkpost 作为提供程序,但是当我使用 Postman 调用函数时,我收到以下错误:

{
    "message": {
        "errno": "EAI_AGAIN",
        "code": "EAI_AGAIN",
        "syscall": "getaddrinfo",
        "hostname": "api.sparkpost.com",
        "host": "api.sparkpost.com",
        "port": "443"
    }
}

如果我尝试使用命令调用在本地提供的相同函数firebase serve --only functions,然后使用 Postman 对其进行测试,我不会收到任何错误。

我的代码如下:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const SparkPost = require('sparkpost');

// Initialize App
admin.initializeApp();

exports.sendSurveyRecap = functions.https.onRequest((req, res) => {
  try {
    if (req.method !== 'POST') {
      return res.status(405).json({
        message: `Method ${req.method} is not allowed`,
      });
    }

    const client = new SparkPost('<MY API KEY>');

    return client.transmissions.send({
      content: {
        from: '<MY EMAIL DOMAIN>',
        subject: 'Hello from node-sparkpost',
        html: '<p>Hello world</p>',
      },
      recipients: [
        { address: 'foo@example.com' },
      ],
    }).then(() => res.status(200).json({
      message: 'Message sent successful',
    })).catch(error => res.status(500).json({
      message: error,
    }));
  } catch (error) {
    return res.status(500).json({
      message: error.message,
    });
  }
});

那么,为什么当我使用“已部署”的 url 调用云函数时收到该错误,而不是使用“已服务的”url 我没有收到任何错误?

标签: firebasegoogle-cloud-functionsnodemailersparkpost

解决方案


推荐阅读