简体   繁体   English

向客户发送关于将数据保存到 Firestore 的确认电子邮件

[英]Send confirmation e-mail to client on saving data to firestore

I am trying to make a website for taking online bookings.我正在尝试制作一个用于在线预订的网站。 The site has been hosted in firebase and I am using firestore to collect the details of booking.该网站已托管在 firebase 中,我正在使用 firestore 收集预订的详细信息。 I am using the code given below to collect the details in firestore.我正在使用下面给出的代码来收集 firestore 中的详细信息。

var firestore =  firebase.firestore();

var messagesRef = firestore.collection("BookingData");


//listen for submit
document.getElementById('bookingForm').addEventListener('submit',submitForm);

function submitForm(e){
 e.preventDefault();

 //get values
var email = getInputVal('email');
var packageFields = getInputVal('packageFields');
var name = getInputVal('name');
var phone = getInputVal('phone');
var date = getInputVal('date');

saveMessage(email, packageFields, name, phone, date);

//show alert
}

// function to get form values

 function getInputVal(id) {
return document.getElementById(id).value;
 }

//save messages

function saveMessage(email, packageFields, name, phone, date) {

  messagesRef.add({
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }).then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
 .catch(function(error) {
  console.error("Error adding document: ", error);
});

}

Now the problem is, I would like to send email to my client and get a email at my personal email id whenever there is a booking [ie the data get saved in firestore (Document Written with id)] using JS and SMTP.现在的问题是,我想使用 JS 和 SMTP 向我的客户发送电子邮件,并在有预订时通过我的个人电子邮件 ID 收到一封电子邮件[即数据保存在 Firestore 中(用 ID 编写的文档)]。

The email will be send automatically to the provided email id.电子邮件将自动发送到提供的电子邮件 ID。

How can I do so.我怎么能这样做。

Thanks for any kind of help in advance.提前感谢您的任何帮助。

One of the possible solutions is to use the Firebase extension dedicated to email sending.一种可能的解决方案是使用专用于电子邮件发送的 Firebase 扩展

Since you want to send an email when a new document is created in the BookingData collection, it will be a piece of cake to configure it.由于您希望在BookingData集合中创建新文档时发送电子邮件,因此对其进行配置将是小菜一碟。

Just follow the configuration instructions and enter "BookingData" for the field "Email documents collection" ("Email documents collection" is "the path to the collection that contains the documents used to build and send the emails")只需按照配置说明并在“电子邮件文档集合”字段中输入“BookingData”(“电子邮件文档集合”是“包含用于构建和发送电子邮件的文档的集合的路径”)

Then, as explained in the doc here , in the document created in the BookingData collection, include a to field with the same value than the email and a cc , (or bcc ) field with your own email.然后,在文档的解释这里的BookingData集合中创建的文档中,包括to外地具有比相同值emailcc (或bcc )字段用您自己的电子邮件。 Then, use the document's message field to specify the other email elements, like subject line and email body (either plaintext or HTML).然后,使用文档的message字段指定其他电子邮件元素,如主题行和电子邮件正文(纯文本或 HTML)。


Note that doing so will add all this extra info (together with some fields containing the status of the extension execution) to the BookingData document .请注意,这样做会将所有这些额外信息(连同一些包含扩展执行状态的字段)添加到 BookingData 文档中 If you prefer to avoid having these extra info added to this document, just use another dedicated collection to trigger (and configure) the emails.如果您不想将这些额外信息添加到此文档中,只需使用另一个专用集合来触发(和配置)电子邮件。

To generate and send an email via this specific, dedicated collection, you could use a batched write, as follows:要通过此特定的专用集合生成和发送电子邮件,您可以使用批量写入,如下所示:

var messagesRef = firestore.collection("BookingData");
var emailsRef = firestore.collection("emails");  // Additional collection

var batch = firestore.batch();

batch.set(messagesRef, 
 {
   email:email,
   packageFields:packageFields,
   name:name,
   phone:phone,
   date:date
   }
);

batch.set(emailsRef, 
 {
   to:email,
   bcc:'youremail@mail.com',
   message: {
    subject: 'New order',
    html: 'This is an <code>HTML</code> email body.',
   }
  }
);
// Commit the batch
batch.commit().then(function () {
    // ...
});

Don't forget to:不要忘记:

  • Deny read and write access rights to the emails collection via security rules.通过安全规则拒绝对emails集合的读写访问权限。
  • Enter "emails" for the field "Email documents collection", when configuring the extension.配置扩展时,为“电子邮件文档集合”字段输入“电子邮件”。

And note that to install and use Firebase extensions, your project must be on the Blaze plan.请注意,要安装和使用 Firebase 扩展,您的项目必须在 Blaze 计划中。

I would probably use a service that provides a HTTP API for mailing.我可能会使用为邮件提供 HTTP API 的服务。

SendGrid is a great option, here is a quick example ( src ): SendGrid 是一个很好的选择,这里有一个简单的例子( src ):

const functions = require("firebase-functions");
const sgMail = require("@sendgrid/mail");
const cors = require("cors")({
  origin: true
});

exports.emailMessage = functions.https.onRequest((req, res) => {
  const { name, email, phone, message } = req.body;
  return cors(req, res, () => {
    var text = `<div>
      <h4>Information</h4>
      <ul>
        <li>
          Name - ${name || ""}
        </li>
        <li>
          Email - ${email || ""}
        </li>
        <li>
          Phone - ${phone || ""}
        </li>
      </ul>
      <h4>Message</h4>
      <p>${message || ""}</p>
    </div>`;
    const msg = {
      to: "myemail@myemail.com",
      from: "no-reply@myemail.com",
      subject: `${name} sent you a new message`,
      text: text,
      html: text
    };
    sgMail.setApiKey(
      "SENDGRID API KEY"
    );
    sgMail.send(msg);
    res.status(200).send("success");
  }).catch(() => {
    res.status(500).send("error");
  });
});

This can be done using smtp.js using the code given below这可以使用下面给出的代码使用 smtp.js 来完成

var firestore = firebase.firestore();

var messagesRef = firestore.collection("bookingData");

//listen for submit
document.getElementById("bookingForm").addEventListener("submit", submitForm);

function submitForm(e) {
  e.preventDefault();

  //get values
  var email = getInputVal("email");
  var packageFields = getInputVal("packageFields");
  var name = getInputVal("name");
  var phone = getInputVal("phone");
  var date = getInputVal("date");
  var [persons] = getInputVal("persons");

  saveMessage(email, packageFields, name, phone, date, persons);
  sendEmail(packageFields, name, date, persons);
  //show alert
}

// function to get form values

function getInputVal(id) {
  return document.getElementById(id).value;
}

//save messages

function saveMessage(email, packageFields, name, phone, date, persons) {
  messagesRef
    .add({
      email: email,
      packageFields: packageFields,
      name: name,
      phone: phone,
      date: date,
      persons: persons,
    })
    .then(function (docRef) {
      console.log("Document written with ID: ", docRef.id);
      console.log(email);
    })
    .catch(function (error) {
      console.error("Error adding document: ", error);
    });
}

function sendEmail(packageFields, name, date, persons) {
  Email.send({
    Host: "smtp.gmail.com",
    Username: "trippyadive.web.app@gmail.com",
    Password: "xxxxxxxxxx",
    To: "subhodiproy161101@gmail.com",
    From: "trippyadive.web.app@gmail.com",
    Subject: "Sending Email using javascript",
    Body: `Your package of ${packageFields} for ${name} with total ${persons} persons (incl. ${name}) dated ${date} has been provisonalised. Your seat will be confirmed once you complete the payment of the Security Deposit`,
  }).then(function (message) {
    alert("mail sent successfully");
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM