Sending Emails with MongoDB Stitch and SendGrid

Christian Hissibini
7 min readAug 4, 2019

--

The main purpose of this article is to introduce MongoDB Stitch and demonstrate how to trigger emails from it using SendGrid.

Context

While I was developing an app for managing guestlists using MongoDB, I needed a quick and reliable solution to send an email invitation to each guest when they get added to the list.

Why MongoDB Stitch?

MongoDB Stitch is a Backend-as-a-Service (BaaS) from MongoDB. Here are the reasons why I used it for this project:

· Reliability: Stitch has direct access to MongoDB databases and safely exposes existing data.

· Faster development: With MongoDB Stitch, we can focus on building our application and not worry about managing data manipulation code, service integration, or backend infrastructure.

· Scalability: The integration with MongoDB Atlas allows for easy scaling of capacity and performance as an application grows.

· Security and Privacy: · Stitch allows us to directly manage access control, plus it stores encrypted values for all the services credentials, so we don’t need a separate secret management system.

· Extensibility: MongoDB Stitch allows seamless integration with external services.

Why SendGrid?

SendGrid is a leading provider in trusted cloud-based email delivery. They provide a platform that allows developers to easily create applications that send emails.

Not to mention, I already had an existing account which I used for previous projects, and I have never been disappointed with their service. 😊

If you don’t have one yet, you can get a free one at https://sendgrid.com/

Getting started

For the next steps you will need to have:

· A MongoDB Atlas cluster running. See this guide if you don’t have a MongoDB Atlas account yet.

· A SendGrid account from where we’ll get or create an API Key.

Don’t forget to take note of the SendGrid API key

Creating a MongoDB Stitch Application

1. Log in to MongoDB Cloud.

2. Click on Stitch located in the SERVICES section in the left-hand navigation.

3. Click the Create New Application.

4. In the Create a new application dialog, enter the Application Name. In our case, it’s “Guestlist_Mailer”.

Creating a MongoDB Stitch application

Setting up an authentication method

For a start, we wanted to run our app with anonymous authentication. Since MongoDB and Atlas have security features enabled by default, we need to enable the Anonymous Authentication option on the Turn on Authentication section on the Stitch UI as well.

Enabling Anonymous Authentication — MongoDB Stitch application

Adding a MongoDB collection

Once the authentication method is settled, the next step is to add the MongoDB collection that our application will have access to.

1. Here you can:
· Either add an existing database, then select a collection
· Or initialize a new database and collection by entering their names

2. Click on Add Collection

For our app, the database name is “GuestDatabase” and the collection name is “GuestCollection”.

Initializing a MongoDB collection — MongoDB Stitch application
Initializing a MongoDB collection — MongoDB Stitch application

Securely storing the SendGrid API key

Stitch provides two simple and secure ways to store values associated with applications:

· Stitch values are named references to a piece of static data stored by Stitch that we can access in Functions and rules.

· Stitch secrets are private values that are stored on the Stitch server, hidden from users, and not included in exported applications.

Since our SendGrid API key is very sensitive information, it makes sense to store it in a Stitch Secret.

1. Click on Values & Secrets in the left-hand navigation, select the Secrets tab and then click Create New Value.

2. Enter a unique Secret Name. In our case “SendGridApiKeySecret”.

3. Enter the SendGrid API key value in the input box Secret Value and then click Save.

4. Select the Values tab and then click Create New Value.

5. Enter a unique Value Name. In our case “SendGridApiKey”.

6. Select the Secret radio button, then select the name of the Secret that the value should reference from the Secret Name dropdown. In our case “SendGridApiKeySecret”.

7. Click on Save to store the value.

Adding a Stitch Secret — MongoDB Stitch application

Now we can access our SendGrid API key without exposing it!

Adding a MongoDB Stitch Trigger

Stitch triggers allow us to run functions automatically when something changes in your database, when a particular authentication event occurs, or based on a pre-defined schedule.

In our case, we want to trigger an email when a new document is inserted in our database. Here‘s how we’ll do it’:

1. Click on Triggers in the left-hand navigation, and then click on Add a Trigger.

2. On the Add Trigger page, make sure that the Trigger Type is set to Database Triggers.

3. Name the Trigger. In our case, we chose the name “Mailing_Trigger”.

4. In the TRIGGER SOURCE DETAILS section, choose our previously named resources from the dropdowns for Select The Linked Cluster, then Database Name and Collection Name.

5. As Operation Type, select Insert (we want to trigger an email only when a new document is inserted in our collection).

6. Set Full Document option at ON. This will allow us to access the full document data in the Change Event.

Adding a MongoDB Stitch Trigger

7. In the FUNCTION section, click on the Select a function dropdown, then +New Function.

8. Enter the function name in the input box Function Name.

9. Click on the Function Editor tab and replace the content by copying and pasting the code below into the editor, then click Save.

The code in Stitch Functions is written in JavaScript (ES6+) with a few constraints.

In our Stitch function, we have:

· An exported module which takes the database change event object as the parameter and executes a POST call to SendGrid API with email data of the newly created document using the HTTP Service.

· Two helper functions: BuildEmailData and BuildEmailContentFromTemplate which generate a formatted JSON object required as the request body by SendGrid API.

— The inserted document has the following general form:

Inserted document form

For clarity reasons, I decided to put the two helper functions together with the exported module in the same Stitch Function. For an optimal scenario, I suggest creating a separate Stitch Function for each function you may need in order to observe the principle of Separation of Concerns.

Deploying our Stitch Application and Going Live

After creating a Trigger Function, the next step is to save our changes and make the application live.

To proceed:

1. Click on the REVIEW & DEPLOY CHANGES button appearing at the top of Stitch UI.

2. Then in Review & Deploy Changes dialog, click on Deploy.

And that’s it! 🥳

Deploying a MongoDB Stitch Application

Wrapping up

Now our Stitch Application is live, each time a new document is inserted in our collection, an email will be triggered through SendGrid. In our Guestlist Manager application, we use this to automatically send invitations to each guest!

Here is the recap of what we’ve covered:

· Creating and configuring a MongoDB Stitch application

· Using Stitch Secret to securely store sensitive information

· Setting up a MongoDB Stitch Trigger

· Writing a Stitch Function that makes calls to SendGrid API for email sending

· Making a Stich Application go live

Next steps

Now, each time we add a new guest in our Guestlist Manager app, an email invitation is automatically sent. BUT there’s still more we can do — wouldn’t it be cool if we could implement a way of tracking RSVPs? In my next post, I’ll show you how to use another powerful feature of MongoDB Stitch called Stitch Service to do just that.

Feedback

Thanks for reading! I hope this helped you dive into MongoDB Stitch and SendGrid. I kept this project intentionally simple, and there are many ways it can be built upon and improved. Please feel free to leave a comment here or reach out to me on Twitter @histechup — this will help me continue to create content that is most helpful to you and the community. Til next time!

--

--

Christian Hissibini

Cross-plat architect-developer & startup mentor. Founder DVLUP Inc & @MtlMobileDev . Xamarin and Windows MVP for @Microsoft — ask me about our community! 💪