sendGrid + firebase 云函数:电子邮件不使用可调用函数发送

sendGrid + firebase cloud functions: Email is not sending with Callable functions

我是 javascript 的新手,我正在尝试使用 firebase 可调用函数发送电子邮件。这个想法是在从 iOS 应用程序调用时从云功能向用户电子邮件发送代码。但问题是,可以部署功能,但我不确定我的代码有什么问题,因为它没有发送电子邮件。我已经配置了 Sendgrid api 密钥和模板 ID,因此这里似乎不是问题所在。另外,firebase 上的函数日志没有返回任何错误。有人可以帮忙吗?这是我的代码

云函数代码:

const functions = require("firebase-functions");

const admin = require("firebase-admin");
admin.initializeApp();

const db = admin.firestore();

const sgMail = require("@sendgrid/mail");
const SENDGRID_API_KEY = functions.config().sendgrid.key;
const TEMPLATE_ID = functions.config().sendgrid.template;
sgMail.setApiKey(SENDGRID_API_KEY);

exports.requestTurn = functions.https.onCall((data, context) => {
  const uid = context.auth.uid;
  console.log("UID: " + uid);
  const email = context.auth.token.email;
  console.log("Name: " + email);

  const send = "Here is your query number!";

  const docRef = db.collection("Users").doc(uid);
  const code = docRef.set({"sentEmail": send}, {merge: true});

  const msg = {
     to: email,
     from: "myemailaddress",
     templateId: TEMPLATE_ID,
     dynamic_template_data: {
        subject: "Welcome",
        CODE: send,
     }
  };

  const res = db.collection("mail").doc().set(msg);

  console.log("email saved to Firestore!");
  return sgMail.send(msg);
  // return {
  //   message: text,
  //   code,
  // };
})

这就是我在 swiftui 应用程序中调用它的方式:

func requestTurn(){
        let data = ["Hello!"]
        
        functions.httpsCallable("requestTurn").call(data) { (result, error) in
            print("Function returned")
            if let err = error {print(err)}
            if let res = result {print(res)}
            
        }

并且本该发送的邮件在收件箱中保存没有问题。

我对 Sendgrid 不是很熟悉,但是我查看了文档。我认为这与根据 documentation send 是异步方法的事实有关,因此,如果您不等待它,云功能将在此之前结束。 实际上我认为它可能会起作用,如果你将添加 then 作为文档中的示例:

sgMail
  .send(msg)
  .then(() => {}, error => {
    console.error(error);

我不确定它是否会解决这个问题,但它应该会给你可能的错误提示。