Skip to content
Advertisement

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

I’m new to javascript and I’m trying to send email with the firebase callable functions. the idea is to send code to user email from a cloud function when called from the iOS app. But the thing is, functions can be deployed but I’m not sure what is wrong with my code as it is not sending the email. I have already configure the Sendgrid api key and template id so it doesn’t seems like the issue here. Plus the functions log on firebase is not returning any Error. Can someone help? here’s my code

Cloud Function code:

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,
  // };
})

and this is how I call it from swiftui app:

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

and the mail that was supposed to be sent is saved with no problem in the mail collection. firestore database

Advertisement

Answer

I am not very familiar with Sendgrid, however I have looked at documentation. I think this is related with the fact that according to the documentation send is asynchronous method so, if you do not await for it, Cloud function will end before. Actually I think that it might work, if you will add then as in example from the docs:

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

I am not sure if it will solve the case, however it should give you possible error massage.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement