0
votes

I am currently developing a website for a friend and he has a valet company. I am creating a website for him so people can go online and request a private event for their location such as a house party, or a gathering.

The requesting part is all complete but now he has asked me if it is possible to have the website send him an email every time there is a new request instead of going to the website login in and then continuing from there.

I have learned that you can use sendgrid to send emails. I am using firebase/firestore for my project. I have installed @sendgrid/mail and created a JS file to see if the email service works.

I created just to see if i can send the email. If i run it the code with node adn terminal it works perfectly fine

The I proceeded to add the code to the JS file that is on the client side. I did some research and saw that i could not use require on the client side and saw that if i install require.js it would allow me to do just that.

i then installed requirejs and proceeded to add the same code to the new JS file which contains the client side html.

I got this error at first

" Module name "@sendgrid/mail" has not been loaded yet for context: _. Use require([] )"

then i read the error and tried to add the "[]" . That took me to where i am stuck right now This shows all the code with the " [] " added in there. I Now get a new error which goes like this code picture This is the error i am getting now

This is my JS file which is on the client side with the sendgrid/mail.

const sgMail = require(['@sendgrid/mail']);
const API_KEY = '';
sgMail.setApiKey(API_KEY);

(function(){ 
//configuration file for firebase. The way we acess the app location in the database
 var firebaseConfig = {
 apiKey: "",
 authDomain: "",
 projectId: "",
 storageBucket: "",
 messagingSenderId: "",
 appId: "",
 measurementId: ""
 };

 //firebase initialiaztion. The way we initialize
  firebase.initializeApp(firebaseConfig);
  var db = firebase.firestore();

const email = document.getElementById('emailTxt');
const firstName = document.getElementById('firstNameTxt');
const lastName = document.getElementById('lastNameTxt');
const firstPhone = document.getElementById('numberTxtArea'); 
const secondPhone = document.getElementById('numberTxtMiddle');
const thirdPhone = document.getElementById('numberTxtEnd');
const location = document.getElementById('locationTxt');
const numberOfCars = document.getElementById('carCount');
const numberOfPeople = document.getElementById('peopleCount'); 
const startTime = document.getElementById('starTime');
const endTime = document.getElementById('endTime'); 
const parking = document.getElementById('availability'); 
const details = document.getElementById('details'); 
const submitQuoteBtn = document.getElementById('requestQuoteBtn');
const succesfullySubmited = document.getElementById('requestConfirm');




submitQuoteBtn.addEventListener('click', e=>{ 


  const emailValue = email.value;
  const firstNameValue = firstName.value;
  const lastNameValue = lastName.value;
  const firstPhoneValue = firstPhone.value;
  const secondPhoneValue = secondPhone.value;
  const thirdPhoneValue = thirdPhone.value;
  const phoneNumber = firstPhoneValue + "-" + secondPhoneValue + "-" + thirdPhoneValue;
  const locationValue = location.value;
  const numberOfCarsValue = numberOfCars.value;
  const numberOfPeopleValue = numberOfPeople.value;
  const startTimeValue = startTime.value;
  const endTimeValue = endTime.value;
  const parkingValue = parking.value;
  const detailsValue = details.value;
  var datePlaced = new Date();
  var dd = datePlaced.getDate();
  var mm = datePlaced.getMonth() +1;
  var yyyy =  datePlaced.getFullYear();
  var fullDate = (mm + "-" + dd + "-" + yyyy);

const message  = {
  to: '',
  from: '',
  subject: 'New Private EVENT',
  text: "hi",
  html: "hello",
};


sgMail.send(message)
.then((response) => console.log('Email sent'))
.catch((error) => console.log(error.message));
 db.collection("Manager").doc("Quote").collection("Quotes").doc((firstNameValue + " " + 
lastNameValue)).set({

  email: emailValue,
  firstName: firstNameValue,
  lastName: lastNameValue,
  phone: phoneNumber,
  location: locationValue,
  numberOfCars: numberOfCarsValue,
  numberOfPeople: numberOfPeopleValue,
  startTime: startTimeValue,
  endTime: endTimeValue,
  parking: parkingValue,
  details: detailsValue,
  date: fullDate,




 }).then(() =>{
    console.log("i am here 6");
 console.log("document written successfully");

 succesfullySubmited.style = "visible";

 }).catch((error) => {
    console.log(error);
})   
});

})()

This is my html file connected to the js file

<!DOCTYPE html>
<html lang="en">
<head>
 <link rel = "stylesheet" href="RCMA.css" >
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta name="description" content="Providing proffesional valet services around the Cleveland 
Area. Restaurants, Private events, and more">
    <title></title>

</head>

<body>


    <script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-firestore.js"></script>
    <script src="scripts/require.js"></script>






    <div class= "banner">

        <div class="navbar">
            <img src="pictures/rcmalogo.jpeg" class= "logo">
                    <ul>
                        <li><a href="index.html">Home</a></li>
                        <li><a href="contact.html">Contact</a></li>
                        <li><a href="Quote.html">Get a Quote</a></li>
                        <li><a href="AboutUs.html">About Us</a></li>
                        <li><a href="SignIn.html">Sign In</a></li>
                    </ul>
                
            </div>
            
            <div class="inputBoxes">
                                    
                <input  type="email" id="emailTxt" class="emailTxt" placeholder="Email..." /> <br>
                <input type="textfield" id="firstNameTxt" class="firstNameTxt" placeholder="First Name..." /> 
                <input type="textfield" id="lastNameTxt" class="lastNameTxt" placeholder="Last Name..." /><br>
                <input type="textfield" id="numberTxtArea" class="numberTxtArea" placeholder="###" /> 
                <input type="textfield" id="numberTxtMiddle" class="numberTxtMiddle" placeholder="###" />
                <input type="textfield" id="numberTxtEnd" class="numberTxtEnd" placeholder="####" /> <br>
                <input type="textfield" id="locationTxt" class="locationTxt" placeholder="Location..." /><br>
                <input type="textfield" id="carCount" class="carCount" placeholder="Estimated # of Cars..." /><br>
                <input type="textfield" id="peopleCount" class="peopleCount" placeholder="Estimated # of People..." /><br>
                <input type="textfield" id="starTime" class="starTime" placeholder="Event Start time..." />
                <input type="textfield" id="endTime" class="endTime" placeholder="Event End Time..."/><br>
                <input type="textfield" id="availability" class="availability" placeholder="Parking Availability..."/> <br>
                <input type="textfield" id="details" class="details" placeholder="Details / Questions..."/><br> <br> <br>
                <button id="requestQuoteBtn"> Request Quote</button>
                <h1 id="requestConfirm" style="display: none;" >Submited Succesfully! </h1>
            </div>
            
            
        </div>
        



</body>

<script type="module" src="scripts/quote.js"></script>



</html>
1

1 Answers

0
votes

You need to do that from a backend you control, either a Node.js server, or, easier, a Cloud Function. And you need to use the Sendgrid APi for Node.js.

Also, you should not share your Sendgrid API key in your front-end code, because one can easily read the source.

So, a simple Cloud Function to send an email would be like that:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(functions.config().sendgrid.apikey);
// See the doc for the config: https://firebase.google.com/docs/functions/config-env
// The API key is securely stored as a Cloud Function configuration item

exports.createUser = functions.firestore
    .document('requests/{requestId}')
    .onCreate((snap, context) => {
        const newValue = snap.data();

        // access a particular field as you would any JS property
        const requestName = newValue.name;

        const msg = {
            to: '[email protected]',
            from: '....', // Change to your verified sender
            subject: '',
            html: 'Here is the name: ' + requestName  // Adapt that with HTML code
        }

        return sgMail.send(msg)
        .catch(error => {
          console.log(JSON.stringify(error));
          return null;
        })

    });

Every time a new request doc is created, an email will be sent.


Another possibility would be to use the "Trigger Email" Firebase extension. You'll find in the "Firebase Tips & Tricks" publication on Medium, an article which explains how to configure the extension with Sendgrid.