Section 15: Sending Emails (Task App)

130. Section Intro

 

131. Exploring SendGrid

We are going to use SendGrid to send emails when a user creates an account.  In order to use it, we need to first create an account at sendgrid.com.

Navigate to the website and click Start For Free. Fill out the form and submit.

When you get the Set up 2-factor authentication email, press the link in the email and set up 2-factor auth.  I don’t think you can avoid it.

On the Welcome page, press Create a Single Sender.  Fill out the form.  SendGrid will email you AGAIN.  Press the link in the email to verify the sender.

Click Email API drop down and select Integration Guide.

Choose Web API setup method.

Choose Node.js

On the Integrate using our Web API or SMTP Relay page, enter a name for the API key and press Create Key.

Save the API key.

In VSC install the sendgrid/main npm module

$ npm install @sendgrid/mail

Create a new directory named src/emails.

Create a new file src/emails/account.js.

const sgMail = require('@sendgrid/main')

const sendgridAPIKey = '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'

sgMail.setApiKey(sendgridAPIKey)

sgMail.send({
  to: 'rmcgregor@bridgewater.edu',
  from: 'rmcgregor@bridgewater.edu',
  subject: 'Welcome to the Web App',
  text: 'I hope you are well!'
})

132. Sending Welcome and Cancelation Emails

const sgMail = require('@sendgrid/main')

const sendgridAPIKey = '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'

sgMail.setApiKey(sendgridAPIKey)

const sendWelcomeEmail = (email, name) => {
  sgMail.send({
    to: email,
    from: 'rmcgregor@bridgewater.edu',
    subject: 'Thanks for joining!',
    text: Welcome to the app ${name}. Hope you enjoy the app! }) } module.exports = { sendWelcomeEmail }

Now in routers/user.js.

const {sendWelcomeEmail} = require('../emails/account')

...

// in router.post('/users'. ...
  ...
  try {
    await user.save()
    sendWelcomeEmail(user.email, user.name)
    ...

133. Environment Variables

Let’s add a file named .env in the base directory of our project.  Inside that file, let’s add the following lines of code.

PORT=3000
MONGODB_URL=mongodb://127.0.0.1:27017/web-app-api

Load the env-cmd npm module as a development dependency.

$ npm install env-cmd --save-dev

We now need to tell env-cmd to load the environmental variables

"dev": "env-cmd ./config/dev.env nodemon src/app.js"

We can set the port constant in src/app.js to the following

const port = process.env.PORT

and in src/mongoose.js we need to modify replace the hard coded URL with the MONGODB_URL environmental variable.

mongoose.connect(process.env.MONGODB_URL).catch(() => {
    console.log('error connecting mongoose to the mongodb')
})

 

134. Creating a Production MongoDB Database

The MongoDB website has a tutorial named How to deploy MongoDB on Heroku.  We’re going to follow the instructions from the Udemy site.

Go to the MongoDB Altas homepage at https://www.mongodb.com/cloud/atlas/register.

Click the Start free button.

Register for an account by adding your email address, First name, Last name, and passsword.  Click on the check box to agree to the terms of service and press Get started free.  Click link in verification email.

Navigate to cloud.mongodb.com and log in.

Warning: Throughout the process of creating a database, make sure you are mindful and only select technologies on the Free Tier.

Create a project. Name it anything you’d like. Click Next, then Create Project.

On the Database Deployments page, click Build a Database.

On the Deploy a cloud database page, click Create for the FREE Shared server.

On the Create a Shared Cluster page, you only need to change the cluster name to the name of your web app.   The other default settings (shown below) should suffice.

Cloud Provider: AWS
Region: N. Virginia
Cluster Tier: M0 Sandbox (Shared RAM, 512 MB Storage)
Additional Setting: MongoDB 4.4, No Backup

When ready, click Create Cluster.

On the Security Quickstart page, for 1) How would you like to authenticate your connection”, choose Username and Password, enter a username and password (save your password, as you’ll need it later in this tutorial), then press Create User.

For 2) Where would you like to connect from, choose My Local Environment and set the IP address to 0.0.0.0/0 and set the description to anywhere.  When complete press Add Entry.

After the IP address has been entered, press Finish and Close.  You will be redirected to the Database Deployments page.

Retrieve the MongoDB Connect Connection String

On the Database Deployments page, you should see the database that you deployed.  Press Connect.  On the next page that reads Choose a connection method, choose Connect using MongoDB Compass.  Copy the connection string, and press Close.

Connect to the Database with MongoDB Compass

Open MongoDB Compass.

If MongoDB Compass is still connected to the MongoDB database on localhost, press Connect -> Disconnect in the application’s main menu.

Now press New Connection found at the top of the left hand side panel.

Next to New Connection in the right side panel, click FAVORITES.  In the pop up dialog, give the connection an name (e.g. Atlas MongoDB), choose a color, and press Save.

Next, paste your connection string in the field under the label that reads Paste your connection string.  Before pressing connect, replace <password> with the password that you used when you created your database user account.

When you press Connect, MongoDB should connect to your Atlas MongoDB database.

135. Heroku Deployment

Back on the Atlas Dashboard, on the Database Deployments page, press Connect.  Now select Connect your application. On the following page, make sure that Node.js is chosen as the Driver and the Version is 4.0 or later, then copy the connection string to your clipboard.

mongodb+srv://web-api:<password>@web-app-api.jrkvn.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Replace <password> with the password of the user account you created for the  Altas database.

Also replace myFirstDatabase with the name of the database that we are using in our node app (e.g. web-app-api).

We need to set up Heroku environmental variables

$ heroku config:set MONGODB_URL='mongodb+srv://web-api:H3reWeG0%21@web-app-api.jrkvn.mongodb.net/web-app-api?retryWrites=true&w=majority'

Use double quotes around the url if you are on Windows and single quotes if you are on a Mac.

 

 

© 2022 – 2024, Eric McGregor. All rights reserved. Unauthorized use, distribution and/or duplication of this material without express and written permission from the author is strictly prohibited.