Firebase在线预订系统:Firestore存数据后JS+SMTP自动发邮件实现咨询
Got it, let's figure out how to make this work. Sending emails directly from your front-end with SMTP is a big no-no—you'd end up exposing your SMTP credentials (like your email password) to anyone who inspects your website's code. That's a huge security risk. Instead, we'll use Firebase Cloud Functions to handle the email sending securely, since they run on Google's servers and keep your credentials hidden.
Here's a step-by-step solution:
1. Set Up Firebase Cloud Functions
First, make sure you have the Firebase CLI installed on your local machine. If not, run:
npm install -g firebase-tools
Then, initialize Cloud Functions in your project:
- Run
firebase loginto authenticate with your Google account - Navigate to your project folder and run
firebase init functions - Choose JavaScript as the language, and enable ESLint if you want.
2. Install Email Dependencies
In the functions subfolder of your project, install Nodemailer (the library we'll use to send emails via SMTP):
npm install nodemailer
3. Write the Cloud Function to Send Emails
Replace the code in functions/index.js with this:
const functions = require("firebase-functions"); const nodemailer = require("nodemailer"); // Configure your SMTP transporter (use your email service details here) const transporter = nodemailer.createTransport({ service: "Gmail", // Swap with SendGrid, Mailgun, or another service if preferred auth: { user: "your-personal-email@gmail.com", // Your admin email pass: "your-app-password" // For Gmail, use an App Password if 2FA is enabled } }); // Send confirmation email to the customer async function sendCustomerConfirmation(bookingData) { const mailOptions = { from: "Your Booking Site <your-personal-email@gmail.com>", to: bookingData.email, subject: "Your Booking Confirmation", html: ` <h1>Thanks for booking with us, ${bookingData.name}!</h1> <p>Here are your booking details:</p> <ul> <li>Package: ${bookingData.packageFields}</li> <li>Phone Number: ${bookingData.phone}</li> <li>Booking Date: ${bookingData.date}</li> </ul> <p>We’ll reach out shortly if we need any more details. Feel free to reply to this email with questions!</p> ` }; await transporter.sendMail(mailOptions); } // Send notification email to you async function sendAdminAlert(bookingData, bookingId) { const mailOptions = { from: "Booking Notifier <your-personal-email@gmail.com>", to: "your-personal-email@gmail.com", subject: "New Booking Received!", html: ` <h1>You’ve got a new booking!</h1> <p>Booking ID: ${bookingId}</p> <p>Customer Details:</p> <ul> <li>Name: ${bookingData.name}</li> <li>Email: ${bookingData.email}</li> <li>Phone: ${bookingData.phone}</li> <li>Package: ${bookingData.packageFields}</li> <li>Date: ${bookingData.date}</li> </ul> ` }; await transporter.sendMail(mailOptions); } // Trigger the function when a new booking is added to Firestore exports.sendBookingEmails = functions.firestore .document("BookingData/{bookingId}") .onCreate(async (snap, context) => { const bookingData = snap.data(); const bookingId = context.params.bookingId; try { await sendCustomerConfirmation(bookingData); await sendAdminAlert(bookingData, bookingId); functions.logger.info("Emails sent successfully!"); return null; } catch (error) { functions.logger.error("Failed to send emails:", error); throw error; } });
4. Deploy the Cloud Function
Run this command from your project root to deploy the function to Firebase:
firebase deploy --only functions
5. Update Your Front-End Code (Optional but Recommended)
You don’t need to change much of your existing code—since the Cloud Function automatically triggers when a new document is added to BookingData. But you can add a success message for your users:
}).then(function(docRef) { console.log("Document written with ID: ", docRef.id); // Show a friendly confirmation to the user alert("Your booking has been submitted! A confirmation email is on its way to your inbox."); }) .catch(function(error) { console.error("Error adding document: ", error); alert("Oops, something went wrong. Please try again later."); });
Important Notes
- Gmail Users: If you have 2FA enabled on your Gmail account, you’ll need to create an App Password instead of using your regular password. Avoid enabling "less secure apps"—it’s a security risk.
- Alternative Email Services: If you don’t want to use Gmail, services like SendGrid or Mailgun offer better deliverability for transactional emails. Just update the
transporterconfiguration with their SMTP details. - Cloud Functions Pricing: Firebase gives you a free tier for Cloud Functions, but be aware of usage limits. Check Firebase’s pricing page for details if you expect high booking volumes.
内容的提问来源于stack exchange,提问作者Subhodip Roy

