javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functionsnodemailer

Sending email upon document creation in firebase with cloud function


I'm currently building a flutter app that allows users to request meetings with others. When one user requests another user, the requested user should receive an email saying they got a request. when a new request is created, a new document is appended into the collection meeting_requests. Using the Google Cloud functions, I was able to write the following code with nodemailer to send an email upon creation of a request:

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: <MY EMAIL HERE>
    pass: <MY APPS PASSWORD HERE>,
  },
});

exports.sendMeetingNotification = functions.firestore
    .document("meeting_requests/{docId}")
    .onCreate(async (snap, context) => {
      const data = snap.data();
      const receiverId = data.receiverId;

      console.log("Fetching user data for receiverId:", receiverId);

      try {
        const userDoc = await admin.firestore().collection(
            "users").doc(receiverId).get();

        if (!userDoc.exists) {
          console.log("No user found with the given receiverId:", receiverId);
          return;
        }

        const email = userDoc.data().email;

        console.log("Found user with email:", email);

        const mailOptions = {
          from: "\"ConnectEd\" connected.app.contact@gmail.com",
          to: email,
          subject: "New Meeting Request from Teacher",
          html: `
        <div style="background-color: #f9f7cf; padding: 20px;
         font-family: Arial, sans-serif; color: #333;">
          <div style="text-align: center; margin-bottom: 20px;">
            <img src="https://your-logo-url.com/logo.png" alt="ConnectEd Logo" style="width: 100px; height: auto;" />
          </div>
          <div style="background-color: #fff; 
          padding: 20px; border-radius: 8px; 
          box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
            <h2 style="color: #2c3e50;
            ">New Meeting Request from ${data.senderName}</h2>
            <p style="font-size: 16px; line-height: 1.6;">
              <strong>Note from teacher:</strong> ${data.note}
            </p>
            <p style="font-size: 16px; line-height: 1.6;">
              Please click the link below to view the request:
            </p>
            <div style="text-align: center; margin: 20px 0;">
              <a href="yourapp://app/openRequest?requestId=${context.params.docId}" style="background-color: #f39c12; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-size: 16px;">View Request</a>
            </div>
          </div>
          <div style="text-align: center; 
          margin-top: 20px; font-size: 12px; color: #999;">
            <p>© 2024 ConnectEd. All rights reserved.</p>
            <p>If you did not request this email, please ignore it.</p>
          </div>
        </div>
        `,
        };

        console.log("Sending email to:", email);

        await transporter.sendMail(mailOptions);
        console.log("Email sent successfully to:", email);
      } catch (error) {
        console.error("Error sending email notification:", error);
      }
    });


However, when I run it, no email is sent, and I get the following log error:

2024-09-07T14:37:34.038106Z ? sendMeetingNotification: Error sending email notification: Error: 7 PERMISSION_DENIED: Missing or insufficient permissions.
2024-09-07T14:37:34.038127Z ? sendMeetingNotification:     at callErrorFromStatus (/workspace/node_modules/@grpc/grpc-js/build/src/call.js:31:19)

2024-09-07T14:37:34.038251Z ? sendMeetingNotification:   code: 7,
2024-09-07T14:37:34.038256Z ? sendMeetingNotification:   details: 'Missing or insufficient permissions.',
s.',
2024-09-07T14:37:34.038261Z ? sendMeetingNotification:   metadata: Metadata {
2024-09-07T14:37:34.038266Z ? sendMeetingNotification:     internalRepr: Map(1) { 'x-debug-tracking-id' => [Array] },
d' => [Array] },
2024-09-07T14:37:34.038270Z ? sendMeetingNotification:     options: {}
2024-09-07T14:37:34.038274Z ? sendMeetingNotification:   }
2024-09-07T14:37:34.038274Z ? sendMeetingNotification:   }
2024-09-07T14:37:34.038279Z ? sendMeetingNotification: }
2024-09-07T14:37:34.039269068Z D sendMeetingNotification: Function execution took 54 ms, finished with status: 'ok'

I'm new to this, so really did not understand what was going on.

I tried changing the firebase permissions, adding this gmail account to my cloud permissions, but nothing has worked. The odd thing was that it was working perfectly yesterday, and today it just doesn't which is really confusing to me.

Thanks for the help!


Solution

  • Wrap your firestore logic into a separate try/catch block before sending emails because this error isn't a nodemailer's error. Likely the error means that service account that is used for your gcp cloud function has no permission to query data from firestore. Give roles/datastore.user to your service account. Please check the docs.

    https://cloud.google.com/datastore/docs/access/iam

    Check permissions that your service account has in iam in gcp console.