【问题标题】:sendGrid + firebase cloud functions: Email is not sending with Callable functionssendGrid + firebase 云功能:电子邮件未使用可调用功能发送
【发布时间】:2021-06-18 06:26:48
【问题描述】:

我是 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)}
            
        }

并且应该发送的邮件被保存在邮件集合中,没有问题。

【问题讨论】:

  • 您在日志中看到任何错误吗?如果你发现潜在的错误怎么办?此外,请注意,您应该将异步 set() 和 send() 方法返回的 Promise 链接起来。
  • 您好,请问如何退货?

标签: javascript google-cloud-firestore swiftui google-cloud-functions sendgrid


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2019-08-08
    • 2019-05-21
    • 2017-12-03
    • 2020-11-22
    • 2018-11-15
    • 2022-01-19
    • 2019-04-20
    • 1970-01-01
    相关资源
    最近更新 更多